~ubuntu-branches/ubuntu/oneiric/postgresql-9.1/oneiric-security

« back to all changes in this revision

Viewing changes to contrib/pgbench/pgbench.c

  • Committer: Bazaar Package Importer
  • Author(s): Martin Pitt
  • Date: 2011-05-11 10:41:53 UTC
  • Revision ID: james.westby@ubuntu.com-20110511104153-psbh2o58553fv1m0
Tags: upstream-9.1~beta1
ImportĀ upstreamĀ versionĀ 9.1~beta1

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
/*
 
2
 * pgbench.c
 
3
 *
 
4
 * A simple benchmark program for PostgreSQL
 
5
 * Originally written by Tatsuo Ishii and enhanced by many contributors.
 
6
 *
 
7
 * contrib/pgbench/pgbench.c
 
8
 * Copyright (c) 2000-2011, PostgreSQL Global Development Group
 
9
 * ALL RIGHTS RESERVED;
 
10
 *
 
11
 * Permission to use, copy, modify, and distribute this software and its
 
12
 * documentation for any purpose, without fee, and without a written agreement
 
13
 * is hereby granted, provided that the above copyright notice and this
 
14
 * paragraph and the following two paragraphs appear in all copies.
 
15
 *
 
16
 * IN NO EVENT SHALL THE AUTHOR OR DISTRIBUTORS BE LIABLE TO ANY PARTY FOR
 
17
 * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, INCLUDING
 
18
 * LOST PROFITS, ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS
 
19
 * DOCUMENTATION, EVEN IF THE AUTHOR OR DISTRIBUTORS HAVE BEEN ADVISED OF THE
 
20
 * POSSIBILITY OF SUCH DAMAGE.
 
21
 *
 
22
 * THE AUTHOR AND DISTRIBUTORS SPECIFICALLY DISCLAIMS ANY WARRANTIES,
 
23
 * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
 
24
 * AND FITNESS FOR A PARTICULAR PURPOSE.  THE SOFTWARE PROVIDED HEREUNDER IS
 
25
 * ON AN "AS IS" BASIS, AND THE AUTHOR AND DISTRIBUTORS HAS NO OBLIGATIONS TO
 
26
 * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
 
27
 *
 
28
 */
 
29
 
 
30
#ifdef WIN32
 
31
#define FD_SETSIZE 1024                 /* set before winsock2.h is included */
 
32
#endif   /* ! WIN32 */
 
33
 
 
34
#include "postgres_fe.h"
 
35
 
 
36
#include "libpq-fe.h"
 
37
#include "libpq/pqsignal.h"
 
38
#include "portability/instr_time.h"
 
39
 
 
40
#include <ctype.h>
 
41
 
 
42
#ifndef WIN32
 
43
#include <sys/time.h>
 
44
#include <unistd.h>
 
45
#endif   /* ! WIN32 */
 
46
 
 
47
#ifdef HAVE_GETOPT_H
 
48
#include <getopt.h>
 
49
#endif
 
50
 
 
51
#ifdef HAVE_SYS_SELECT_H
 
52
#include <sys/select.h>
 
53
#endif
 
54
 
 
55
#ifdef HAVE_SYS_RESOURCE_H
 
56
#include <sys/resource.h>               /* for getrlimit */
 
57
#endif
 
58
 
 
59
#ifndef INT64_MAX
 
60
#define INT64_MAX       INT64CONST(0x7FFFFFFFFFFFFFFF)
 
61
#endif
 
62
 
 
63
/*
 
64
 * Multi-platform pthread implementations
 
65
 */
 
66
 
 
67
#ifdef WIN32
 
68
/* Use native win32 threads on Windows */
 
69
typedef struct win32_pthread *pthread_t;
 
70
typedef int pthread_attr_t;
 
71
 
 
72
static int      pthread_create(pthread_t *thread, pthread_attr_t * attr, void *(*start_routine) (void *), void *arg);
 
73
static int      pthread_join(pthread_t th, void **thread_return);
 
74
#elif defined(ENABLE_THREAD_SAFETY)
 
75
/* Use platform-dependent pthread capability */
 
76
#include <pthread.h>
 
77
#else
 
78
/* Use emulation with fork. Rename pthread identifiers to avoid conflicts */
 
79
 
 
80
#include <sys/wait.h>
 
81
 
 
82
#define pthread_t                               pg_pthread_t
 
83
#define pthread_attr_t                  pg_pthread_attr_t
 
84
#define pthread_create                  pg_pthread_create
 
85
#define pthread_join                    pg_pthread_join
 
86
 
 
87
typedef struct fork_pthread *pthread_t;
 
88
typedef int pthread_attr_t;
 
89
 
 
90
static int      pthread_create(pthread_t *thread, pthread_attr_t * attr, void *(*start_routine) (void *), void *arg);
 
91
static int      pthread_join(pthread_t th, void **thread_return);
 
92
#endif
 
93
 
 
94
extern char *optarg;
 
95
extern int      optind;
 
96
 
 
97
 
 
98
/********************************************************************
 
99
 * some configurable parameters */
 
100
 
 
101
/* max number of clients allowed */
 
102
#ifdef FD_SETSIZE
 
103
#define MAXCLIENTS      (FD_SETSIZE - 10)
 
104
#else
 
105
#define MAXCLIENTS      1024
 
106
#endif
 
107
 
 
108
#define DEFAULT_NXACTS  10              /* default nxacts */
 
109
 
 
110
int                     nxacts = 0;                     /* number of transactions per client */
 
111
int                     duration = 0;           /* duration in seconds */
 
112
 
 
113
/*
 
114
 * scaling factor. for example, scale = 10 will make 1000000 tuples in
 
115
 * pgbench_accounts table.
 
116
 */
 
117
int                     scale = 1;
 
118
 
 
119
/*
 
120
 * fillfactor. for example, fillfactor = 90 will use only 90 percent
 
121
 * space during inserts and leave 10 percent free.
 
122
 */
 
123
int                     fillfactor = 100;
 
124
 
 
125
/*
 
126
 * end of configurable parameters
 
127
 *********************************************************************/
 
128
 
 
129
#define nbranches       1                       /* Makes little sense to change this.  Change
 
130
                                                                 * -s instead */
 
131
#define ntellers        10
 
132
#define naccounts       100000
 
133
 
 
134
bool            use_log;                        /* log transaction latencies to a file */
 
135
bool            is_connect;                     /* establish connection for each transaction */
 
136
bool            is_latencies;           /* report per-command latencies */
 
137
int                     main_pid;                       /* main process id used in log filename */
 
138
 
 
139
char       *pghost = "";
 
140
char       *pgport = "";
 
141
char       *pgoptions = NULL;
 
142
char       *pgtty = NULL;
 
143
char       *login = NULL;
 
144
char       *dbName;
 
145
 
 
146
volatile bool timer_exceeded = false;   /* flag from signal handler */
 
147
 
 
148
/* variable definitions */
 
149
typedef struct
 
150
{
 
151
        char       *name;                       /* variable name */
 
152
        char       *value;                      /* its value */
 
153
} Variable;
 
154
 
 
155
#define MAX_FILES               128             /* max number of SQL script files allowed */
 
156
#define SHELL_COMMAND_SIZE      256 /* maximum size allowed for shell command */
 
157
 
 
158
/*
 
159
 * structures used in custom query mode
 
160
 */
 
161
 
 
162
typedef struct
 
163
{
 
164
        PGconn     *con;                        /* connection handle to DB */
 
165
        int                     id;                             /* client No. */
 
166
        int                     state;                  /* state No. */
 
167
        int                     cnt;                    /* xacts count */
 
168
        int                     ecnt;                   /* error count */
 
169
        int                     listen;                 /* 0 indicates that an async query has been
 
170
                                                                 * sent */
 
171
        int                     sleeping;               /* 1 indicates that the client is napping */
 
172
        int64           until;                  /* napping until (usec) */
 
173
        Variable   *variables;          /* array of variable definitions */
 
174
        int                     nvariables;
 
175
        instr_time      txn_begin;              /* used for measuring transaction latencies */
 
176
        instr_time      stmt_begin;             /* used for measuring statement latencies */
 
177
        int                     use_file;               /* index in sql_files for this client */
 
178
        bool            prepared[MAX_FILES];
 
179
} CState;
 
180
 
 
181
/*
 
182
 * Thread state and result
 
183
 */
 
184
typedef struct
 
185
{
 
186
        int                     tid;                    /* thread id */
 
187
        pthread_t       thread;                 /* thread handle */
 
188
        CState     *state;                      /* array of CState */
 
189
        int                     nstate;                 /* length of state[] */
 
190
        instr_time      start_time;             /* thread start time */
 
191
        instr_time *exec_elapsed;       /* time spent executing cmds (per Command) */
 
192
        int                *exec_count;         /* number of cmd executions (per Command) */
 
193
} TState;
 
194
 
 
195
#define INVALID_THREAD          ((pthread_t) 0)
 
196
 
 
197
typedef struct
 
198
{
 
199
        instr_time      conn_time;
 
200
        int                     xacts;
 
201
} TResult;
 
202
 
 
203
/*
 
204
 * queries read from files
 
205
 */
 
206
#define SQL_COMMAND             1
 
207
#define META_COMMAND    2
 
208
#define MAX_ARGS                10
 
209
 
 
210
typedef enum QueryMode
 
211
{
 
212
        QUERY_SIMPLE,                           /* simple query */
 
213
        QUERY_EXTENDED,                         /* extended query */
 
214
        QUERY_PREPARED,                         /* extended query with prepared statements */
 
215
        NUM_QUERYMODE
 
216
} QueryMode;
 
217
 
 
218
static QueryMode querymode = QUERY_SIMPLE;
 
219
static const char *QUERYMODE[] = {"simple", "extended", "prepared"};
 
220
 
 
221
typedef struct
 
222
{
 
223
        char       *line;                       /* full text of command line */
 
224
        int                     command_num;    /* unique index of this Command struct */
 
225
        int                     type;                   /* command type (SQL_COMMAND or META_COMMAND) */
 
226
        int                     argc;                   /* number of command words */
 
227
        char       *argv[MAX_ARGS]; /* command word list */
 
228
} Command;
 
229
 
 
230
static Command **sql_files[MAX_FILES];  /* SQL script files */
 
231
static int      num_files;                      /* number of script files */
 
232
static int      num_commands = 0;       /* total number of Command structs */
 
233
static int      debug = 0;                      /* debug flag */
 
234
 
 
235
/* default scenario */
 
236
static char *tpc_b = {
 
237
        "\\set nbranches " CppAsString2(nbranches) " * :scale\n"
 
238
        "\\set ntellers " CppAsString2(ntellers) " * :scale\n"
 
239
        "\\set naccounts " CppAsString2(naccounts) " * :scale\n"
 
240
        "\\setrandom aid 1 :naccounts\n"
 
241
        "\\setrandom bid 1 :nbranches\n"
 
242
        "\\setrandom tid 1 :ntellers\n"
 
243
        "\\setrandom delta -5000 5000\n"
 
244
        "BEGIN;\n"
 
245
        "UPDATE pgbench_accounts SET abalance = abalance + :delta WHERE aid = :aid;\n"
 
246
        "SELECT abalance FROM pgbench_accounts WHERE aid = :aid;\n"
 
247
        "UPDATE pgbench_tellers SET tbalance = tbalance + :delta WHERE tid = :tid;\n"
 
248
        "UPDATE pgbench_branches SET bbalance = bbalance + :delta WHERE bid = :bid;\n"
 
249
        "INSERT INTO pgbench_history (tid, bid, aid, delta, mtime) VALUES (:tid, :bid, :aid, :delta, CURRENT_TIMESTAMP);\n"
 
250
        "END;\n"
 
251
};
 
252
 
 
253
/* -N case */
 
254
static char *simple_update = {
 
255
        "\\set nbranches " CppAsString2(nbranches) " * :scale\n"
 
256
        "\\set ntellers " CppAsString2(ntellers) " * :scale\n"
 
257
        "\\set naccounts " CppAsString2(naccounts) " * :scale\n"
 
258
        "\\setrandom aid 1 :naccounts\n"
 
259
        "\\setrandom bid 1 :nbranches\n"
 
260
        "\\setrandom tid 1 :ntellers\n"
 
261
        "\\setrandom delta -5000 5000\n"
 
262
        "BEGIN;\n"
 
263
        "UPDATE pgbench_accounts SET abalance = abalance + :delta WHERE aid = :aid;\n"
 
264
        "SELECT abalance FROM pgbench_accounts WHERE aid = :aid;\n"
 
265
        "INSERT INTO pgbench_history (tid, bid, aid, delta, mtime) VALUES (:tid, :bid, :aid, :delta, CURRENT_TIMESTAMP);\n"
 
266
        "END;\n"
 
267
};
 
268
 
 
269
/* -S case */
 
270
static char *select_only = {
 
271
        "\\set naccounts " CppAsString2(naccounts) " * :scale\n"
 
272
        "\\setrandom aid 1 :naccounts\n"
 
273
        "SELECT abalance FROM pgbench_accounts WHERE aid = :aid;\n"
 
274
};
 
275
 
 
276
/* Function prototypes */
 
277
static void setalarm(int seconds);
 
278
static void *threadRun(void *arg);
 
279
 
 
280
 
 
281
/*
 
282
 * routines to check mem allocations and fail noisily.
 
283
 */
 
284
static void *
 
285
xmalloc(size_t size)
 
286
{
 
287
        void       *result;
 
288
 
 
289
        result = malloc(size);
 
290
        if (!result)
 
291
        {
 
292
                fprintf(stderr, "out of memory\n");
 
293
                exit(1);
 
294
        }
 
295
        return result;
 
296
}
 
297
 
 
298
static void *
 
299
xrealloc(void *ptr, size_t size)
 
300
{
 
301
        void       *result;
 
302
 
 
303
        result = realloc(ptr, size);
 
304
        if (!result)
 
305
        {
 
306
                fprintf(stderr, "out of memory\n");
 
307
                exit(1);
 
308
        }
 
309
        return result;
 
310
}
 
311
 
 
312
static char *
 
313
xstrdup(const char *s)
 
314
{
 
315
        char       *result;
 
316
 
 
317
        result = strdup(s);
 
318
        if (!result)
 
319
        {
 
320
                fprintf(stderr, "out of memory\n");
 
321
                exit(1);
 
322
        }
 
323
        return result;
 
324
}
 
325
 
 
326
 
 
327
static void
 
328
usage(const char *progname)
 
329
{
 
330
        printf("%s is a benchmarking tool for PostgreSQL.\n\n"
 
331
                   "Usage:\n"
 
332
                   "  %s [OPTIONS]... [DBNAME]\n"
 
333
                   "\nInitialization options:\n"
 
334
                   "  -i           invokes initialization mode\n"
 
335
                   "  -F NUM       fill factor\n"
 
336
                   "  -s NUM       scaling factor\n"
 
337
                   "\nBenchmarking options:\n"
 
338
                "  -c NUM       number of concurrent database clients (default: 1)\n"
 
339
                   "  -C           establish new connection for each transaction\n"
 
340
                   "  -D VARNAME=VALUE\n"
 
341
                   "               define variable for use by custom script\n"
 
342
                   "  -f FILENAME  read transaction script from FILENAME\n"
 
343
                   "  -j NUM       number of threads (default: 1)\n"
 
344
                   "  -r           report average latency per command\n"
 
345
                   "  -l           write transaction times to log file\n"
 
346
                   "  -M {simple|extended|prepared}\n"
 
347
                   "               protocol for submitting queries to server (default: simple)\n"
 
348
                   "  -n           do not run VACUUM before tests\n"
 
349
                   "  -N           do not update tables \"pgbench_tellers\" and \"pgbench_branches\"\n"
 
350
                   "  -s NUM       report this scale factor in output\n"
 
351
                   "  -S           perform SELECT-only transactions\n"
 
352
         "  -t NUM       number of transactions each client runs (default: 10)\n"
 
353
                   "  -T NUM       duration of benchmark test in seconds\n"
 
354
                   "  -v           vacuum all four standard tables before tests\n"
 
355
                   "\nCommon options:\n"
 
356
                   "  -d           print debugging output\n"
 
357
                   "  -h HOSTNAME  database server host or socket directory\n"
 
358
                   "  -p PORT      database server port number\n"
 
359
                   "  -U USERNAME  connect as specified database user\n"
 
360
                   "  --help       show this help, then exit\n"
 
361
                   "  --version    output version information, then exit\n"
 
362
                   "\n"
 
363
                   "Report bugs to <pgsql-bugs@postgresql.org>.\n",
 
364
                   progname, progname);
 
365
}
 
366
 
 
367
/* random number generator: uniform distribution from min to max inclusive */
 
368
static int
 
369
getrand(int min, int max)
 
370
{
 
371
        /*
 
372
         * Odd coding is so that min and max have approximately the same chance of
 
373
         * being selected as do numbers between them.
 
374
         */
 
375
        return min + (int) (((max - min + 1) * (double) random()) / (MAX_RANDOM_VALUE + 1.0));
 
376
}
 
377
 
 
378
/* call PQexec() and exit() on failure */
 
379
static void
 
380
executeStatement(PGconn *con, const char *sql)
 
381
{
 
382
        PGresult   *res;
 
383
 
 
384
        res = PQexec(con, sql);
 
385
        if (PQresultStatus(res) != PGRES_COMMAND_OK)
 
386
        {
 
387
                fprintf(stderr, "%s", PQerrorMessage(con));
 
388
                exit(1);
 
389
        }
 
390
        PQclear(res);
 
391
}
 
392
 
 
393
/* set up a connection to the backend */
 
394
static PGconn *
 
395
doConnect(void)
 
396
{
 
397
        PGconn     *conn;
 
398
        static char *password = NULL;
 
399
        bool            new_pass;
 
400
 
 
401
        /*
 
402
         * Start the connection.  Loop until we have a password if requested by
 
403
         * backend.
 
404
         */
 
405
        do
 
406
        {
 
407
                new_pass = false;
 
408
 
 
409
                conn = PQsetdbLogin(pghost, pgport, pgoptions, pgtty, dbName,
 
410
                                                        login, password);
 
411
                if (!conn)
 
412
                {
 
413
                        fprintf(stderr, "Connection to database \"%s\" failed\n",
 
414
                                        dbName);
 
415
                        return NULL;
 
416
                }
 
417
 
 
418
                if (PQstatus(conn) == CONNECTION_BAD &&
 
419
                        PQconnectionNeedsPassword(conn) &&
 
420
                        password == NULL)
 
421
                {
 
422
                        PQfinish(conn);
 
423
                        password = simple_prompt("Password: ", 100, false);
 
424
                        new_pass = true;
 
425
                }
 
426
        } while (new_pass);
 
427
 
 
428
        /* check to see that the backend connection was successfully made */
 
429
        if (PQstatus(conn) == CONNECTION_BAD)
 
430
        {
 
431
                fprintf(stderr, "Connection to database \"%s\" failed:\n%s",
 
432
                                dbName, PQerrorMessage(conn));
 
433
                PQfinish(conn);
 
434
                return NULL;
 
435
        }
 
436
 
 
437
        return conn;
 
438
}
 
439
 
 
440
/* throw away response from backend */
 
441
static void
 
442
discard_response(CState *state)
 
443
{
 
444
        PGresult   *res;
 
445
 
 
446
        do
 
447
        {
 
448
                res = PQgetResult(state->con);
 
449
                if (res)
 
450
                        PQclear(res);
 
451
        } while (res);
 
452
}
 
453
 
 
454
static int
 
455
compareVariables(const void *v1, const void *v2)
 
456
{
 
457
        return strcmp(((const Variable *) v1)->name,
 
458
                                  ((const Variable *) v2)->name);
 
459
}
 
460
 
 
461
static char *
 
462
getVariable(CState *st, char *name)
 
463
{
 
464
        Variable        key,
 
465
                           *var;
 
466
 
 
467
        /* On some versions of Solaris, bsearch of zero items dumps core */
 
468
        if (st->nvariables <= 0)
 
469
                return NULL;
 
470
 
 
471
        key.name = name;
 
472
        var = (Variable *) bsearch((void *) &key,
 
473
                                                           (void *) st->variables,
 
474
                                                           st->nvariables,
 
475
                                                           sizeof(Variable),
 
476
                                                           compareVariables);
 
477
        if (var != NULL)
 
478
                return var->value;
 
479
        else
 
480
                return NULL;
 
481
}
 
482
 
 
483
/* check whether the name consists of alphabets, numerals and underscores. */
 
484
static bool
 
485
isLegalVariableName(const char *name)
 
486
{
 
487
        int                     i;
 
488
 
 
489
        for (i = 0; name[i] != '\0'; i++)
 
490
        {
 
491
                if (!isalnum((unsigned char) name[i]) && name[i] != '_')
 
492
                        return false;
 
493
        }
 
494
 
 
495
        return true;
 
496
}
 
497
 
 
498
static int
 
499
putVariable(CState *st, const char *context, char *name, char *value)
 
500
{
 
501
        Variable        key,
 
502
                           *var;
 
503
 
 
504
        key.name = name;
 
505
        /* On some versions of Solaris, bsearch of zero items dumps core */
 
506
        if (st->nvariables > 0)
 
507
                var = (Variable *) bsearch((void *) &key,
 
508
                                                                   (void *) st->variables,
 
509
                                                                   st->nvariables,
 
510
                                                                   sizeof(Variable),
 
511
                                                                   compareVariables);
 
512
        else
 
513
                var = NULL;
 
514
 
 
515
        if (var == NULL)
 
516
        {
 
517
                Variable   *newvars;
 
518
 
 
519
                /*
 
520
                 * Check for the name only when declaring a new variable to avoid
 
521
                 * overhead.
 
522
                 */
 
523
                if (!isLegalVariableName(name))
 
524
                {
 
525
                        fprintf(stderr, "%s: invalid variable name '%s'\n", context, name);
 
526
                        return false;
 
527
                }
 
528
 
 
529
                if (st->variables)
 
530
                        newvars = (Variable *) xrealloc(st->variables,
 
531
                                                                        (st->nvariables + 1) * sizeof(Variable));
 
532
                else
 
533
                        newvars = (Variable *) xmalloc(sizeof(Variable));
 
534
 
 
535
                st->variables = newvars;
 
536
 
 
537
                var = &newvars[st->nvariables];
 
538
 
 
539
                var->name = xstrdup(name);
 
540
                var->value = xstrdup(value);
 
541
 
 
542
                st->nvariables++;
 
543
 
 
544
                qsort((void *) st->variables, st->nvariables, sizeof(Variable),
 
545
                          compareVariables);
 
546
        }
 
547
        else
 
548
        {
 
549
                char       *val;
 
550
 
 
551
                /* dup then free, in case value is pointing at this variable */
 
552
                val = xstrdup(value);
 
553
 
 
554
                free(var->value);
 
555
                var->value = val;
 
556
        }
 
557
 
 
558
        return true;
 
559
}
 
560
 
 
561
static char *
 
562
parseVariable(const char *sql, int *eaten)
 
563
{
 
564
        int                     i = 0;
 
565
        char       *name;
 
566
 
 
567
        do
 
568
        {
 
569
                i++;
 
570
        } while (isalnum((unsigned char) sql[i]) || sql[i] == '_');
 
571
        if (i == 1)
 
572
                return NULL;
 
573
 
 
574
        name = xmalloc(i);
 
575
        memcpy(name, &sql[1], i - 1);
 
576
        name[i - 1] = '\0';
 
577
 
 
578
        *eaten = i;
 
579
        return name;
 
580
}
 
581
 
 
582
static char *
 
583
replaceVariable(char **sql, char *param, int len, char *value)
 
584
{
 
585
        int                     valueln = strlen(value);
 
586
 
 
587
        if (valueln > len)
 
588
        {
 
589
                size_t          offset = param - *sql;
 
590
 
 
591
                *sql = xrealloc(*sql, strlen(*sql) - len + valueln + 1);
 
592
                param = *sql + offset;
 
593
        }
 
594
 
 
595
        if (valueln != len)
 
596
                memmove(param + valueln, param + len, strlen(param + len) + 1);
 
597
        strncpy(param, value, valueln);
 
598
 
 
599
        return param + valueln;
 
600
}
 
601
 
 
602
static char *
 
603
assignVariables(CState *st, char *sql)
 
604
{
 
605
        char       *p,
 
606
                           *name,
 
607
                           *val;
 
608
 
 
609
        p = sql;
 
610
        while ((p = strchr(p, ':')) != NULL)
 
611
        {
 
612
                int                     eaten;
 
613
 
 
614
                name = parseVariable(p, &eaten);
 
615
                if (name == NULL)
 
616
                {
 
617
                        while (*p == ':')
 
618
                        {
 
619
                                p++;
 
620
                        }
 
621
                        continue;
 
622
                }
 
623
 
 
624
                val = getVariable(st, name);
 
625
                free(name);
 
626
                if (val == NULL)
 
627
                {
 
628
                        p++;
 
629
                        continue;
 
630
                }
 
631
 
 
632
                p = replaceVariable(&sql, p, eaten, val);
 
633
        }
 
634
 
 
635
        return sql;
 
636
}
 
637
 
 
638
static void
 
639
getQueryParams(CState *st, const Command *command, const char **params)
 
640
{
 
641
        int                     i;
 
642
 
 
643
        for (i = 0; i < command->argc - 1; i++)
 
644
                params[i] = getVariable(st, command->argv[i + 1]);
 
645
}
 
646
 
 
647
/*
 
648
 * Run a shell command. The result is assigned to the variable if not NULL.
 
649
 * Return true if succeeded, or false on error.
 
650
 */
 
651
static bool
 
652
runShellCommand(CState *st, char *variable, char **argv, int argc)
 
653
{
 
654
        char            command[SHELL_COMMAND_SIZE];
 
655
        int                     i,
 
656
                                len = 0;
 
657
        FILE       *fp;
 
658
        char            res[64];
 
659
        char       *endptr;
 
660
        int                     retval;
 
661
 
 
662
        /*----------
 
663
         * Join arguments with whitespace separators. Arguments starting with
 
664
         * exactly one colon are treated as variables:
 
665
         *      name - append a string "name"
 
666
         *      :var - append a variable named 'var'
 
667
         *      ::name - append a string ":name"
 
668
         *----------
 
669
         */
 
670
        for (i = 0; i < argc; i++)
 
671
        {
 
672
                char       *arg;
 
673
                int                     arglen;
 
674
 
 
675
                if (argv[i][0] != ':')
 
676
                {
 
677
                        arg = argv[i];          /* a string literal */
 
678
                }
 
679
                else if (argv[i][1] == ':')
 
680
                {
 
681
                        arg = argv[i] + 1;      /* a string literal starting with colons */
 
682
                }
 
683
                else if ((arg = getVariable(st, argv[i] + 1)) == NULL)
 
684
                {
 
685
                        fprintf(stderr, "%s: undefined variable %s\n", argv[0], argv[i]);
 
686
                        return false;
 
687
                }
 
688
 
 
689
                arglen = strlen(arg);
 
690
                if (len + arglen + (i > 0 ? 1 : 0) >= SHELL_COMMAND_SIZE - 1)
 
691
                {
 
692
                        fprintf(stderr, "%s: too long shell command\n", argv[0]);
 
693
                        return false;
 
694
                }
 
695
 
 
696
                if (i > 0)
 
697
                        command[len++] = ' ';
 
698
                memcpy(command + len, arg, arglen);
 
699
                len += arglen;
 
700
        }
 
701
 
 
702
        command[len] = '\0';
 
703
 
 
704
        /* Fast path for non-assignment case */
 
705
        if (variable == NULL)
 
706
        {
 
707
                if (system(command))
 
708
                {
 
709
                        if (!timer_exceeded)
 
710
                                fprintf(stderr, "%s: cannot launch shell command\n", argv[0]);
 
711
                        return false;
 
712
                }
 
713
                return true;
 
714
        }
 
715
 
 
716
        /* Execute the command with pipe and read the standard output. */
 
717
        if ((fp = popen(command, "r")) == NULL)
 
718
        {
 
719
                fprintf(stderr, "%s: cannot launch shell command\n", argv[0]);
 
720
                return false;
 
721
        }
 
722
        if (fgets(res, sizeof(res), fp) == NULL)
 
723
        {
 
724
                if (!timer_exceeded)
 
725
                        fprintf(stderr, "%s: cannot read the result\n", argv[0]);
 
726
                return false;
 
727
        }
 
728
        if (pclose(fp) < 0)
 
729
        {
 
730
                fprintf(stderr, "%s: cannot close shell command\n", argv[0]);
 
731
                return false;
 
732
        }
 
733
 
 
734
        /* Check whether the result is an integer and assign it to the variable */
 
735
        retval = (int) strtol(res, &endptr, 10);
 
736
        while (*endptr != '\0' && isspace((unsigned char) *endptr))
 
737
                endptr++;
 
738
        if (*res == '\0' || *endptr != '\0')
 
739
        {
 
740
                fprintf(stderr, "%s: must return an integer ('%s' returned)\n", argv[0], res);
 
741
                return false;
 
742
        }
 
743
        snprintf(res, sizeof(res), "%d", retval);
 
744
        if (!putVariable(st, "setshell", variable, res))
 
745
                return false;
 
746
 
 
747
#ifdef DEBUG
 
748
        printf("shell parameter name: %s, value: %s\n", argv[1], res);
 
749
#endif
 
750
        return true;
 
751
}
 
752
 
 
753
#define MAX_PREPARE_NAME                32
 
754
static void
 
755
preparedStatementName(char *buffer, int file, int state)
 
756
{
 
757
        sprintf(buffer, "P%d_%d", file, state);
 
758
}
 
759
 
 
760
static bool
 
761
clientDone(CState *st, bool ok)
 
762
{
 
763
        (void) ok;                                      /* unused */
 
764
 
 
765
        if (st->con != NULL)
 
766
        {
 
767
                PQfinish(st->con);
 
768
                st->con = NULL;
 
769
        }
 
770
        return false;                           /* always false */
 
771
}
 
772
 
 
773
/* return false iff client should be disconnected */
 
774
static bool
 
775
doCustom(TState *thread, CState *st, instr_time *conn_time, FILE *logfile)
 
776
{
 
777
        PGresult   *res;
 
778
        Command   **commands;
 
779
 
 
780
top:
 
781
        commands = sql_files[st->use_file];
 
782
 
 
783
        if (st->sleeping)
 
784
        {                                                       /* are we sleeping? */
 
785
                instr_time      now;
 
786
 
 
787
                INSTR_TIME_SET_CURRENT(now);
 
788
                if (st->until <= INSTR_TIME_GET_MICROSEC(now))
 
789
                        st->sleeping = 0;       /* Done sleeping, go ahead with next command */
 
790
                else
 
791
                        return true;            /* Still sleeping, nothing to do here */
 
792
        }
 
793
 
 
794
        if (st->listen)
 
795
        {                                                       /* are we receiver? */
 
796
                if (commands[st->state]->type == SQL_COMMAND)
 
797
                {
 
798
                        if (debug)
 
799
                                fprintf(stderr, "client %d receiving\n", st->id);
 
800
                        if (!PQconsumeInput(st->con))
 
801
                        {                                       /* there's something wrong */
 
802
                                fprintf(stderr, "Client %d aborted in state %d. Probably the backend died while processing.\n", st->id, st->state);
 
803
                                return clientDone(st, false);
 
804
                        }
 
805
                        if (PQisBusy(st->con))
 
806
                                return true;    /* don't have the whole result yet */
 
807
                }
 
808
 
 
809
                /*
 
810
                 * command finished: accumulate per-command execution times in
 
811
                 * thread-local data structure, if per-command latencies are requested
 
812
                 */
 
813
                if (is_latencies)
 
814
                {
 
815
                        instr_time      now;
 
816
                        int                     cnum = commands[st->state]->command_num;
 
817
 
 
818
                        INSTR_TIME_SET_CURRENT(now);
 
819
                        INSTR_TIME_ACCUM_DIFF(thread->exec_elapsed[cnum],
 
820
                                                                  now, st->stmt_begin);
 
821
                        thread->exec_count[cnum]++;
 
822
                }
 
823
 
 
824
                /*
 
825
                 * if transaction finished, record the time it took in the log
 
826
                 */
 
827
                if (logfile && commands[st->state + 1] == NULL)
 
828
                {
 
829
                        instr_time      now;
 
830
                        instr_time      diff;
 
831
                        double          usec;
 
832
 
 
833
                        INSTR_TIME_SET_CURRENT(now);
 
834
                        diff = now;
 
835
                        INSTR_TIME_SUBTRACT(diff, st->txn_begin);
 
836
                        usec = (double) INSTR_TIME_GET_MICROSEC(diff);
 
837
 
 
838
#ifndef WIN32
 
839
                        /* This is more than we really ought to know about instr_time */
 
840
                        fprintf(logfile, "%d %d %.0f %d %ld %ld\n",
 
841
                                        st->id, st->cnt, usec, st->use_file,
 
842
                                        (long) now.tv_sec, (long) now.tv_usec);
 
843
#else
 
844
                        /* On Windows, instr_time doesn't provide a timestamp anyway */
 
845
                        fprintf(logfile, "%d %d %.0f %d 0 0\n",
 
846
                                        st->id, st->cnt, usec, st->use_file);
 
847
#endif
 
848
                }
 
849
 
 
850
                if (commands[st->state]->type == SQL_COMMAND)
 
851
                {
 
852
                        /*
 
853
                         * Read and discard the query result; note this is not included in
 
854
                         * the statement latency numbers.
 
855
                         */
 
856
                        res = PQgetResult(st->con);
 
857
                        switch (PQresultStatus(res))
 
858
                        {
 
859
                                case PGRES_COMMAND_OK:
 
860
                                case PGRES_TUPLES_OK:
 
861
                                        break;          /* OK */
 
862
                                default:
 
863
                                        fprintf(stderr, "Client %d aborted in state %d: %s",
 
864
                                                        st->id, st->state, PQerrorMessage(st->con));
 
865
                                        PQclear(res);
 
866
                                        return clientDone(st, false);
 
867
                        }
 
868
                        PQclear(res);
 
869
                        discard_response(st);
 
870
                }
 
871
 
 
872
                if (commands[st->state + 1] == NULL)
 
873
                {
 
874
                        if (is_connect)
 
875
                        {
 
876
                                PQfinish(st->con);
 
877
                                st->con = NULL;
 
878
                        }
 
879
 
 
880
                        ++st->cnt;
 
881
                        if ((st->cnt >= nxacts && duration <= 0) || timer_exceeded)
 
882
                                return clientDone(st, true);    /* exit success */
 
883
                }
 
884
 
 
885
                /* increment state counter */
 
886
                st->state++;
 
887
                if (commands[st->state] == NULL)
 
888
                {
 
889
                        st->state = 0;
 
890
                        st->use_file = getrand(0, num_files - 1);
 
891
                        commands = sql_files[st->use_file];
 
892
                }
 
893
        }
 
894
 
 
895
        if (st->con == NULL)
 
896
        {
 
897
                instr_time      start,
 
898
                                        end;
 
899
 
 
900
                INSTR_TIME_SET_CURRENT(start);
 
901
                if ((st->con = doConnect()) == NULL)
 
902
                {
 
903
                        fprintf(stderr, "Client %d aborted in establishing connection.\n", st->id);
 
904
                        return clientDone(st, false);
 
905
                }
 
906
                INSTR_TIME_SET_CURRENT(end);
 
907
                INSTR_TIME_ACCUM_DIFF(*conn_time, end, start);
 
908
        }
 
909
 
 
910
        /* Record transaction start time if logging is enabled */
 
911
        if (logfile && st->state == 0)
 
912
                INSTR_TIME_SET_CURRENT(st->txn_begin);
 
913
 
 
914
        /* Record statement start time if per-command latencies are requested */
 
915
        if (is_latencies)
 
916
                INSTR_TIME_SET_CURRENT(st->stmt_begin);
 
917
 
 
918
        if (commands[st->state]->type == SQL_COMMAND)
 
919
        {
 
920
                const Command *command = commands[st->state];
 
921
                int                     r;
 
922
 
 
923
                if (querymode == QUERY_SIMPLE)
 
924
                {
 
925
                        char       *sql;
 
926
 
 
927
                        sql = xstrdup(command->argv[0]);
 
928
                        sql = assignVariables(st, sql);
 
929
 
 
930
                        if (debug)
 
931
                                fprintf(stderr, "client %d sending %s\n", st->id, sql);
 
932
                        r = PQsendQuery(st->con, sql);
 
933
                        free(sql);
 
934
                }
 
935
                else if (querymode == QUERY_EXTENDED)
 
936
                {
 
937
                        const char *sql = command->argv[0];
 
938
                        const char *params[MAX_ARGS];
 
939
 
 
940
                        getQueryParams(st, command, params);
 
941
 
 
942
                        if (debug)
 
943
                                fprintf(stderr, "client %d sending %s\n", st->id, sql);
 
944
                        r = PQsendQueryParams(st->con, sql, command->argc - 1,
 
945
                                                                  NULL, params, NULL, NULL, 0);
 
946
                }
 
947
                else if (querymode == QUERY_PREPARED)
 
948
                {
 
949
                        char            name[MAX_PREPARE_NAME];
 
950
                        const char *params[MAX_ARGS];
 
951
 
 
952
                        if (!st->prepared[st->use_file])
 
953
                        {
 
954
                                int                     j;
 
955
 
 
956
                                for (j = 0; commands[j] != NULL; j++)
 
957
                                {
 
958
                                        PGresult   *res;
 
959
                                        char            name[MAX_PREPARE_NAME];
 
960
 
 
961
                                        if (commands[j]->type != SQL_COMMAND)
 
962
                                                continue;
 
963
                                        preparedStatementName(name, st->use_file, j);
 
964
                                        res = PQprepare(st->con, name,
 
965
                                                  commands[j]->argv[0], commands[j]->argc - 1, NULL);
 
966
                                        if (PQresultStatus(res) != PGRES_COMMAND_OK)
 
967
                                                fprintf(stderr, "%s", PQerrorMessage(st->con));
 
968
                                        PQclear(res);
 
969
                                }
 
970
                                st->prepared[st->use_file] = true;
 
971
                        }
 
972
 
 
973
                        getQueryParams(st, command, params);
 
974
                        preparedStatementName(name, st->use_file, st->state);
 
975
 
 
976
                        if (debug)
 
977
                                fprintf(stderr, "client %d sending %s\n", st->id, name);
 
978
                        r = PQsendQueryPrepared(st->con, name, command->argc - 1,
 
979
                                                                        params, NULL, NULL, 0);
 
980
                }
 
981
                else    /* unknown sql mode */
 
982
                        r = 0;
 
983
 
 
984
                if (r == 0)
 
985
                {
 
986
                        if (debug)
 
987
                                fprintf(stderr, "client %d cannot send %s\n", st->id, command->argv[0]);
 
988
                        st->ecnt++;
 
989
                }
 
990
                else
 
991
                        st->listen = 1;         /* flags that should be listened */
 
992
        }
 
993
        else if (commands[st->state]->type == META_COMMAND)
 
994
        {
 
995
                int                     argc = commands[st->state]->argc,
 
996
                                        i;
 
997
                char      **argv = commands[st->state]->argv;
 
998
 
 
999
                if (debug)
 
1000
                {
 
1001
                        fprintf(stderr, "client %d executing \\%s", st->id, argv[0]);
 
1002
                        for (i = 1; i < argc; i++)
 
1003
                                fprintf(stderr, " %s", argv[i]);
 
1004
                        fprintf(stderr, "\n");
 
1005
                }
 
1006
 
 
1007
                if (pg_strcasecmp(argv[0], "setrandom") == 0)
 
1008
                {
 
1009
                        char       *var;
 
1010
                        int                     min,
 
1011
                                                max;
 
1012
                        char            res[64];
 
1013
 
 
1014
                        if (*argv[2] == ':')
 
1015
                        {
 
1016
                                if ((var = getVariable(st, argv[2] + 1)) == NULL)
 
1017
                                {
 
1018
                                        fprintf(stderr, "%s: undefined variable %s\n", argv[0], argv[2]);
 
1019
                                        st->ecnt++;
 
1020
                                        return true;
 
1021
                                }
 
1022
                                min = atoi(var);
 
1023
                        }
 
1024
                        else
 
1025
                                min = atoi(argv[2]);
 
1026
 
 
1027
#ifdef NOT_USED
 
1028
                        if (min < 0)
 
1029
                        {
 
1030
                                fprintf(stderr, "%s: invalid minimum number %d\n", argv[0], min);
 
1031
                                st->ecnt++;
 
1032
                                return;
 
1033
                        }
 
1034
#endif
 
1035
 
 
1036
                        if (*argv[3] == ':')
 
1037
                        {
 
1038
                                if ((var = getVariable(st, argv[3] + 1)) == NULL)
 
1039
                                {
 
1040
                                        fprintf(stderr, "%s: undefined variable %s\n", argv[0], argv[3]);
 
1041
                                        st->ecnt++;
 
1042
                                        return true;
 
1043
                                }
 
1044
                                max = atoi(var);
 
1045
                        }
 
1046
                        else
 
1047
                                max = atoi(argv[3]);
 
1048
 
 
1049
                        if (max < min || max > MAX_RANDOM_VALUE)
 
1050
                        {
 
1051
                                fprintf(stderr, "%s: invalid maximum number %d\n", argv[0], max);
 
1052
                                st->ecnt++;
 
1053
                                return true;
 
1054
                        }
 
1055
 
 
1056
#ifdef DEBUG
 
1057
                        printf("min: %d max: %d random: %d\n", min, max, getrand(min, max));
 
1058
#endif
 
1059
                        snprintf(res, sizeof(res), "%d", getrand(min, max));
 
1060
 
 
1061
                        if (!putVariable(st, argv[0], argv[1], res))
 
1062
                        {
 
1063
                                st->ecnt++;
 
1064
                                return true;
 
1065
                        }
 
1066
 
 
1067
                        st->listen = 1;
 
1068
                }
 
1069
                else if (pg_strcasecmp(argv[0], "set") == 0)
 
1070
                {
 
1071
                        char       *var;
 
1072
                        int                     ope1,
 
1073
                                                ope2;
 
1074
                        char            res[64];
 
1075
 
 
1076
                        if (*argv[2] == ':')
 
1077
                        {
 
1078
                                if ((var = getVariable(st, argv[2] + 1)) == NULL)
 
1079
                                {
 
1080
                                        fprintf(stderr, "%s: undefined variable %s\n", argv[0], argv[2]);
 
1081
                                        st->ecnt++;
 
1082
                                        return true;
 
1083
                                }
 
1084
                                ope1 = atoi(var);
 
1085
                        }
 
1086
                        else
 
1087
                                ope1 = atoi(argv[2]);
 
1088
 
 
1089
                        if (argc < 5)
 
1090
                                snprintf(res, sizeof(res), "%d", ope1);
 
1091
                        else
 
1092
                        {
 
1093
                                if (*argv[4] == ':')
 
1094
                                {
 
1095
                                        if ((var = getVariable(st, argv[4] + 1)) == NULL)
 
1096
                                        {
 
1097
                                                fprintf(stderr, "%s: undefined variable %s\n", argv[0], argv[4]);
 
1098
                                                st->ecnt++;
 
1099
                                                return true;
 
1100
                                        }
 
1101
                                        ope2 = atoi(var);
 
1102
                                }
 
1103
                                else
 
1104
                                        ope2 = atoi(argv[4]);
 
1105
 
 
1106
                                if (strcmp(argv[3], "+") == 0)
 
1107
                                        snprintf(res, sizeof(res), "%d", ope1 + ope2);
 
1108
                                else if (strcmp(argv[3], "-") == 0)
 
1109
                                        snprintf(res, sizeof(res), "%d", ope1 - ope2);
 
1110
                                else if (strcmp(argv[3], "*") == 0)
 
1111
                                        snprintf(res, sizeof(res), "%d", ope1 * ope2);
 
1112
                                else if (strcmp(argv[3], "/") == 0)
 
1113
                                {
 
1114
                                        if (ope2 == 0)
 
1115
                                        {
 
1116
                                                fprintf(stderr, "%s: division by zero\n", argv[0]);
 
1117
                                                st->ecnt++;
 
1118
                                                return true;
 
1119
                                        }
 
1120
                                        snprintf(res, sizeof(res), "%d", ope1 / ope2);
 
1121
                                }
 
1122
                                else
 
1123
                                {
 
1124
                                        fprintf(stderr, "%s: unsupported operator %s\n", argv[0], argv[3]);
 
1125
                                        st->ecnt++;
 
1126
                                        return true;
 
1127
                                }
 
1128
                        }
 
1129
 
 
1130
                        if (!putVariable(st, argv[0], argv[1], res))
 
1131
                        {
 
1132
                                st->ecnt++;
 
1133
                                return true;
 
1134
                        }
 
1135
 
 
1136
                        st->listen = 1;
 
1137
                }
 
1138
                else if (pg_strcasecmp(argv[0], "sleep") == 0)
 
1139
                {
 
1140
                        char       *var;
 
1141
                        int                     usec;
 
1142
                        instr_time      now;
 
1143
 
 
1144
                        if (*argv[1] == ':')
 
1145
                        {
 
1146
                                if ((var = getVariable(st, argv[1] + 1)) == NULL)
 
1147
                                {
 
1148
                                        fprintf(stderr, "%s: undefined variable %s\n", argv[0], argv[1]);
 
1149
                                        st->ecnt++;
 
1150
                                        return true;
 
1151
                                }
 
1152
                                usec = atoi(var);
 
1153
                        }
 
1154
                        else
 
1155
                                usec = atoi(argv[1]);
 
1156
 
 
1157
                        if (argc > 2)
 
1158
                        {
 
1159
                                if (pg_strcasecmp(argv[2], "ms") == 0)
 
1160
                                        usec *= 1000;
 
1161
                                else if (pg_strcasecmp(argv[2], "s") == 0)
 
1162
                                        usec *= 1000000;
 
1163
                        }
 
1164
                        else
 
1165
                                usec *= 1000000;
 
1166
 
 
1167
                        INSTR_TIME_SET_CURRENT(now);
 
1168
                        st->until = INSTR_TIME_GET_MICROSEC(now) + usec;
 
1169
                        st->sleeping = 1;
 
1170
 
 
1171
                        st->listen = 1;
 
1172
                }
 
1173
                else if (pg_strcasecmp(argv[0], "setshell") == 0)
 
1174
                {
 
1175
                        bool            ret = runShellCommand(st, argv[1], argv + 2, argc - 2);
 
1176
 
 
1177
                        if (timer_exceeded) /* timeout */
 
1178
                                return clientDone(st, true);
 
1179
                        else if (!ret)          /* on error */
 
1180
                        {
 
1181
                                st->ecnt++;
 
1182
                                return true;
 
1183
                        }
 
1184
                        else    /* succeeded */
 
1185
                                st->listen = 1;
 
1186
                }
 
1187
                else if (pg_strcasecmp(argv[0], "shell") == 0)
 
1188
                {
 
1189
                        bool            ret = runShellCommand(st, NULL, argv + 1, argc - 1);
 
1190
 
 
1191
                        if (timer_exceeded) /* timeout */
 
1192
                                return clientDone(st, true);
 
1193
                        else if (!ret)          /* on error */
 
1194
                        {
 
1195
                                st->ecnt++;
 
1196
                                return true;
 
1197
                        }
 
1198
                        else    /* succeeded */
 
1199
                                st->listen = 1;
 
1200
                }
 
1201
                goto top;
 
1202
        }
 
1203
 
 
1204
        return true;
 
1205
}
 
1206
 
 
1207
/* discard connections */
 
1208
static void
 
1209
disconnect_all(CState *state, int length)
 
1210
{
 
1211
        int                     i;
 
1212
 
 
1213
        for (i = 0; i < length; i++)
 
1214
        {
 
1215
                if (state[i].con)
 
1216
                {
 
1217
                        PQfinish(state[i].con);
 
1218
                        state[i].con = NULL;
 
1219
                }
 
1220
        }
 
1221
}
 
1222
 
 
1223
/* create tables and setup data */
 
1224
static void
 
1225
init(void)
 
1226
{
 
1227
        /*
 
1228
         * Note: TPC-B requires at least 100 bytes per row, and the "filler"
 
1229
         * fields in these table declarations were intended to comply with that.
 
1230
         * But because they default to NULLs, they don't actually take any space.
 
1231
         * We could fix that by giving them non-null default values. However, that
 
1232
         * would completely break comparability of pgbench results with prior
 
1233
         * versions.  Since pgbench has never pretended to be fully TPC-B
 
1234
         * compliant anyway, we stick with the historical behavior.
 
1235
         */
 
1236
        static char *DDLs[] = {
 
1237
                "drop table if exists pgbench_branches",
 
1238
                "create table pgbench_branches(bid int not null,bbalance int,filler char(88)) with (fillfactor=%d)",
 
1239
                "drop table if exists pgbench_tellers",
 
1240
                "create table pgbench_tellers(tid int not null,bid int,tbalance int,filler char(84)) with (fillfactor=%d)",
 
1241
                "drop table if exists pgbench_accounts",
 
1242
                "create table pgbench_accounts(aid int not null,bid int,abalance int,filler char(84)) with (fillfactor=%d)",
 
1243
                "drop table if exists pgbench_history",
 
1244
                "create table pgbench_history(tid int,bid int,aid int,delta int,mtime timestamp,filler char(22))"
 
1245
        };
 
1246
        static char *DDLAFTERs[] = {
 
1247
                "alter table pgbench_branches add primary key (bid)",
 
1248
                "alter table pgbench_tellers add primary key (tid)",
 
1249
                "alter table pgbench_accounts add primary key (aid)"
 
1250
        };
 
1251
 
 
1252
        PGconn     *con;
 
1253
        PGresult   *res;
 
1254
        char            sql[256];
 
1255
        int                     i;
 
1256
 
 
1257
        if ((con = doConnect()) == NULL)
 
1258
                exit(1);
 
1259
 
 
1260
        for (i = 0; i < lengthof(DDLs); i++)
 
1261
        {
 
1262
                /*
 
1263
                 * set fillfactor for branches, tellers and accounts tables
 
1264
                 */
 
1265
                if ((strstr(DDLs[i], "create table pgbench_branches") == DDLs[i]) ||
 
1266
                        (strstr(DDLs[i], "create table pgbench_tellers") == DDLs[i]) ||
 
1267
                        (strstr(DDLs[i], "create table pgbench_accounts") == DDLs[i]))
 
1268
                {
 
1269
                        char            ddl_stmt[128];
 
1270
 
 
1271
                        snprintf(ddl_stmt, 128, DDLs[i], fillfactor);
 
1272
                        executeStatement(con, ddl_stmt);
 
1273
                        continue;
 
1274
                }
 
1275
                else
 
1276
                        executeStatement(con, DDLs[i]);
 
1277
        }
 
1278
 
 
1279
        executeStatement(con, "begin");
 
1280
 
 
1281
        for (i = 0; i < nbranches * scale; i++)
 
1282
        {
 
1283
                snprintf(sql, 256, "insert into pgbench_branches(bid,bbalance) values(%d,0)", i + 1);
 
1284
                executeStatement(con, sql);
 
1285
        }
 
1286
 
 
1287
        for (i = 0; i < ntellers * scale; i++)
 
1288
        {
 
1289
                snprintf(sql, 256, "insert into pgbench_tellers(tid,bid,tbalance) values (%d,%d,0)",
 
1290
                                 i + 1, i / ntellers + 1);
 
1291
                executeStatement(con, sql);
 
1292
        }
 
1293
 
 
1294
        executeStatement(con, "commit");
 
1295
 
 
1296
        /*
 
1297
         * fill the pgbench_accounts table with some data
 
1298
         */
 
1299
        fprintf(stderr, "creating tables...\n");
 
1300
 
 
1301
        executeStatement(con, "begin");
 
1302
        executeStatement(con, "truncate pgbench_accounts");
 
1303
 
 
1304
        res = PQexec(con, "copy pgbench_accounts from stdin");
 
1305
        if (PQresultStatus(res) != PGRES_COPY_IN)
 
1306
        {
 
1307
                fprintf(stderr, "%s", PQerrorMessage(con));
 
1308
                exit(1);
 
1309
        }
 
1310
        PQclear(res);
 
1311
 
 
1312
        for (i = 0; i < naccounts * scale; i++)
 
1313
        {
 
1314
                int                     j = i + 1;
 
1315
 
 
1316
                snprintf(sql, 256, "%d\t%d\t%d\t\n", j, i / naccounts + 1, 0);
 
1317
                if (PQputline(con, sql))
 
1318
                {
 
1319
                        fprintf(stderr, "PQputline failed\n");
 
1320
                        exit(1);
 
1321
                }
 
1322
 
 
1323
                if (j % 10000 == 0)
 
1324
                        fprintf(stderr, "%d tuples done.\n", j);
 
1325
        }
 
1326
        if (PQputline(con, "\\.\n"))
 
1327
        {
 
1328
                fprintf(stderr, "very last PQputline failed\n");
 
1329
                exit(1);
 
1330
        }
 
1331
        if (PQendcopy(con))
 
1332
        {
 
1333
                fprintf(stderr, "PQendcopy failed\n");
 
1334
                exit(1);
 
1335
        }
 
1336
        executeStatement(con, "commit");
 
1337
 
 
1338
        /*
 
1339
         * create indexes
 
1340
         */
 
1341
        fprintf(stderr, "set primary key...\n");
 
1342
        for (i = 0; i < lengthof(DDLAFTERs); i++)
 
1343
                executeStatement(con, DDLAFTERs[i]);
 
1344
 
 
1345
        /* vacuum */
 
1346
        fprintf(stderr, "vacuum...");
 
1347
        executeStatement(con, "vacuum analyze pgbench_branches");
 
1348
        executeStatement(con, "vacuum analyze pgbench_tellers");
 
1349
        executeStatement(con, "vacuum analyze pgbench_accounts");
 
1350
        executeStatement(con, "vacuum analyze pgbench_history");
 
1351
 
 
1352
        fprintf(stderr, "done.\n");
 
1353
        PQfinish(con);
 
1354
}
 
1355
 
 
1356
/*
 
1357
 * Parse the raw sql and replace :param to $n.
 
1358
 */
 
1359
static bool
 
1360
parseQuery(Command *cmd, const char *raw_sql)
 
1361
{
 
1362
        char       *sql,
 
1363
                           *p;
 
1364
 
 
1365
        sql = xstrdup(raw_sql);
 
1366
        cmd->argc = 1;
 
1367
 
 
1368
        p = sql;
 
1369
        while ((p = strchr(p, ':')) != NULL)
 
1370
        {
 
1371
                char            var[12];
 
1372
                char       *name;
 
1373
                int                     eaten;
 
1374
 
 
1375
                name = parseVariable(p, &eaten);
 
1376
                if (name == NULL)
 
1377
                {
 
1378
                        while (*p == ':')
 
1379
                        {
 
1380
                                p++;
 
1381
                        }
 
1382
                        continue;
 
1383
                }
 
1384
 
 
1385
                if (cmd->argc >= MAX_ARGS)
 
1386
                {
 
1387
                        fprintf(stderr, "statement has too many arguments (maximum is %d): %s\n", MAX_ARGS - 1, raw_sql);
 
1388
                        return false;
 
1389
                }
 
1390
 
 
1391
                sprintf(var, "$%d", cmd->argc);
 
1392
                p = replaceVariable(&sql, p, eaten, var);
 
1393
 
 
1394
                cmd->argv[cmd->argc] = name;
 
1395
                cmd->argc++;
 
1396
        }
 
1397
 
 
1398
        cmd->argv[0] = sql;
 
1399
        return true;
 
1400
}
 
1401
 
 
1402
/* Parse a command; return a Command struct, or NULL if it's a comment */
 
1403
static Command *
 
1404
process_commands(char *buf)
 
1405
{
 
1406
        const char      delim[] = " \f\n\r\t\v";
 
1407
 
 
1408
        Command    *my_commands;
 
1409
        int                     j;
 
1410
        char       *p,
 
1411
                           *tok;
 
1412
 
 
1413
        /* Make the string buf end at the next newline */
 
1414
        if ((p = strchr(buf, '\n')) != NULL)
 
1415
                *p = '\0';
 
1416
 
 
1417
        /* Skip leading whitespace */
 
1418
        p = buf;
 
1419
        while (isspace((unsigned char) *p))
 
1420
                p++;
 
1421
 
 
1422
        /* If the line is empty or actually a comment, we're done */
 
1423
        if (*p == '\0' || strncmp(p, "--", 2) == 0)
 
1424
                return NULL;
 
1425
 
 
1426
        /* Allocate and initialize Command structure */
 
1427
        my_commands = (Command *) xmalloc(sizeof(Command));
 
1428
        my_commands->line = xstrdup(buf);
 
1429
        my_commands->command_num = num_commands++;
 
1430
        my_commands->type = 0;          /* until set */
 
1431
        my_commands->argc = 0;
 
1432
 
 
1433
        if (*p == '\\')
 
1434
        {
 
1435
                my_commands->type = META_COMMAND;
 
1436
 
 
1437
                j = 0;
 
1438
                tok = strtok(++p, delim);
 
1439
 
 
1440
                while (tok != NULL)
 
1441
                {
 
1442
                        my_commands->argv[j++] = xstrdup(tok);
 
1443
                        my_commands->argc++;
 
1444
                        tok = strtok(NULL, delim);
 
1445
                }
 
1446
 
 
1447
                if (pg_strcasecmp(my_commands->argv[0], "setrandom") == 0)
 
1448
                {
 
1449
                        if (my_commands->argc < 4)
 
1450
                        {
 
1451
                                fprintf(stderr, "%s: missing argument\n", my_commands->argv[0]);
 
1452
                                exit(1);
 
1453
                        }
 
1454
 
 
1455
                        for (j = 4; j < my_commands->argc; j++)
 
1456
                                fprintf(stderr, "%s: extra argument \"%s\" ignored\n",
 
1457
                                                my_commands->argv[0], my_commands->argv[j]);
 
1458
                }
 
1459
                else if (pg_strcasecmp(my_commands->argv[0], "set") == 0)
 
1460
                {
 
1461
                        if (my_commands->argc < 3)
 
1462
                        {
 
1463
                                fprintf(stderr, "%s: missing argument\n", my_commands->argv[0]);
 
1464
                                exit(1);
 
1465
                        }
 
1466
 
 
1467
                        for (j = my_commands->argc < 5 ? 3 : 5; j < my_commands->argc; j++)
 
1468
                                fprintf(stderr, "%s: extra argument \"%s\" ignored\n",
 
1469
                                                my_commands->argv[0], my_commands->argv[j]);
 
1470
                }
 
1471
                else if (pg_strcasecmp(my_commands->argv[0], "sleep") == 0)
 
1472
                {
 
1473
                        if (my_commands->argc < 2)
 
1474
                        {
 
1475
                                fprintf(stderr, "%s: missing argument\n", my_commands->argv[0]);
 
1476
                                exit(1);
 
1477
                        }
 
1478
 
 
1479
                        /*
 
1480
                         * Split argument into number and unit to allow "sleep 1ms" etc.
 
1481
                         * We don't have to terminate the number argument with null
 
1482
                         * because it will be parsed with atoi, which ignores trailing
 
1483
                         * non-digit characters.
 
1484
                         */
 
1485
                        if (my_commands->argv[1][0] != ':')
 
1486
                        {
 
1487
                                char       *c = my_commands->argv[1];
 
1488
 
 
1489
                                while (isdigit((unsigned char) *c))
 
1490
                                        c++;
 
1491
                                if (*c)
 
1492
                                {
 
1493
                                        my_commands->argv[2] = c;
 
1494
                                        if (my_commands->argc < 3)
 
1495
                                                my_commands->argc = 3;
 
1496
                                }
 
1497
                        }
 
1498
 
 
1499
                        if (my_commands->argc >= 3)
 
1500
                        {
 
1501
                                if (pg_strcasecmp(my_commands->argv[2], "us") != 0 &&
 
1502
                                        pg_strcasecmp(my_commands->argv[2], "ms") != 0 &&
 
1503
                                        pg_strcasecmp(my_commands->argv[2], "s"))
 
1504
                                {
 
1505
                                        fprintf(stderr, "%s: unknown time unit '%s' - must be us, ms or s\n",
 
1506
                                                        my_commands->argv[0], my_commands->argv[2]);
 
1507
                                        exit(1);
 
1508
                                }
 
1509
                        }
 
1510
 
 
1511
                        for (j = 3; j < my_commands->argc; j++)
 
1512
                                fprintf(stderr, "%s: extra argument \"%s\" ignored\n",
 
1513
                                                my_commands->argv[0], my_commands->argv[j]);
 
1514
                }
 
1515
                else if (pg_strcasecmp(my_commands->argv[0], "setshell") == 0)
 
1516
                {
 
1517
                        if (my_commands->argc < 3)
 
1518
                        {
 
1519
                                fprintf(stderr, "%s: missing argument\n", my_commands->argv[0]);
 
1520
                                exit(1);
 
1521
                        }
 
1522
                }
 
1523
                else if (pg_strcasecmp(my_commands->argv[0], "shell") == 0)
 
1524
                {
 
1525
                        if (my_commands->argc < 1)
 
1526
                        {
 
1527
                                fprintf(stderr, "%s: missing command\n", my_commands->argv[0]);
 
1528
                                exit(1);
 
1529
                        }
 
1530
                }
 
1531
                else
 
1532
                {
 
1533
                        fprintf(stderr, "Invalid command %s\n", my_commands->argv[0]);
 
1534
                        exit(1);
 
1535
                }
 
1536
        }
 
1537
        else
 
1538
        {
 
1539
                my_commands->type = SQL_COMMAND;
 
1540
 
 
1541
                switch (querymode)
 
1542
                {
 
1543
                        case QUERY_SIMPLE:
 
1544
                                my_commands->argv[0] = xstrdup(p);
 
1545
                                my_commands->argc++;
 
1546
                                break;
 
1547
                        case QUERY_EXTENDED:
 
1548
                        case QUERY_PREPARED:
 
1549
                                if (!parseQuery(my_commands, p))
 
1550
                                        exit(1);
 
1551
                                break;
 
1552
                        default:
 
1553
                                exit(1);
 
1554
                }
 
1555
        }
 
1556
 
 
1557
        return my_commands;
 
1558
}
 
1559
 
 
1560
static int
 
1561
process_file(char *filename)
 
1562
{
 
1563
#define COMMANDS_ALLOC_NUM 128
 
1564
 
 
1565
        Command   **my_commands;
 
1566
        FILE       *fd;
 
1567
        int                     lineno;
 
1568
        char            buf[BUFSIZ];
 
1569
        int                     alloc_num;
 
1570
 
 
1571
        if (num_files >= MAX_FILES)
 
1572
        {
 
1573
                fprintf(stderr, "Up to only %d SQL files are allowed\n", MAX_FILES);
 
1574
                exit(1);
 
1575
        }
 
1576
 
 
1577
        alloc_num = COMMANDS_ALLOC_NUM;
 
1578
        my_commands = (Command **) xmalloc(sizeof(Command *) * alloc_num);
 
1579
 
 
1580
        if (strcmp(filename, "-") == 0)
 
1581
                fd = stdin;
 
1582
        else if ((fd = fopen(filename, "r")) == NULL)
 
1583
        {
 
1584
                fprintf(stderr, "%s: %s\n", filename, strerror(errno));
 
1585
                return false;
 
1586
        }
 
1587
 
 
1588
        lineno = 0;
 
1589
 
 
1590
        while (fgets(buf, sizeof(buf), fd) != NULL)
 
1591
        {
 
1592
                Command    *command;
 
1593
 
 
1594
                command = process_commands(buf);
 
1595
                if (command == NULL)
 
1596
                        continue;
 
1597
 
 
1598
                my_commands[lineno] = command;
 
1599
                lineno++;
 
1600
 
 
1601
                if (lineno >= alloc_num)
 
1602
                {
 
1603
                        alloc_num += COMMANDS_ALLOC_NUM;
 
1604
                        my_commands = xrealloc(my_commands, sizeof(Command *) * alloc_num);
 
1605
                }
 
1606
        }
 
1607
        fclose(fd);
 
1608
 
 
1609
        my_commands[lineno] = NULL;
 
1610
 
 
1611
        sql_files[num_files++] = my_commands;
 
1612
 
 
1613
        return true;
 
1614
}
 
1615
 
 
1616
static Command **
 
1617
process_builtin(char *tb)
 
1618
{
 
1619
#define COMMANDS_ALLOC_NUM 128
 
1620
 
 
1621
        Command   **my_commands;
 
1622
        int                     lineno;
 
1623
        char            buf[BUFSIZ];
 
1624
        int                     alloc_num;
 
1625
 
 
1626
        alloc_num = COMMANDS_ALLOC_NUM;
 
1627
        my_commands = (Command **) xmalloc(sizeof(Command *) * alloc_num);
 
1628
 
 
1629
        lineno = 0;
 
1630
 
 
1631
        for (;;)
 
1632
        {
 
1633
                char       *p;
 
1634
                Command    *command;
 
1635
 
 
1636
                p = buf;
 
1637
                while (*tb && *tb != '\n')
 
1638
                        *p++ = *tb++;
 
1639
 
 
1640
                if (*tb == '\0')
 
1641
                        break;
 
1642
 
 
1643
                if (*tb == '\n')
 
1644
                        tb++;
 
1645
 
 
1646
                *p = '\0';
 
1647
 
 
1648
                command = process_commands(buf);
 
1649
                if (command == NULL)
 
1650
                        continue;
 
1651
 
 
1652
                my_commands[lineno] = command;
 
1653
                lineno++;
 
1654
 
 
1655
                if (lineno >= alloc_num)
 
1656
                {
 
1657
                        alloc_num += COMMANDS_ALLOC_NUM;
 
1658
                        my_commands = xrealloc(my_commands, sizeof(Command *) * alloc_num);
 
1659
                }
 
1660
        }
 
1661
 
 
1662
        my_commands[lineno] = NULL;
 
1663
 
 
1664
        return my_commands;
 
1665
}
 
1666
 
 
1667
/* print out results */
 
1668
static void
 
1669
printResults(int ttype, int normal_xacts, int nclients,
 
1670
                         TState *threads, int nthreads,
 
1671
                         instr_time total_time, instr_time conn_total_time)
 
1672
{
 
1673
        double          time_include,
 
1674
                                tps_include,
 
1675
                                tps_exclude;
 
1676
        char       *s;
 
1677
 
 
1678
        time_include = INSTR_TIME_GET_DOUBLE(total_time);
 
1679
        tps_include = normal_xacts / time_include;
 
1680
        tps_exclude = normal_xacts / (time_include -
 
1681
                                                (INSTR_TIME_GET_DOUBLE(conn_total_time) / nthreads));
 
1682
 
 
1683
        if (ttype == 0)
 
1684
                s = "TPC-B (sort of)";
 
1685
        else if (ttype == 2)
 
1686
                s = "Update only pgbench_accounts";
 
1687
        else if (ttype == 1)
 
1688
                s = "SELECT only";
 
1689
        else
 
1690
                s = "Custom query";
 
1691
 
 
1692
        printf("transaction type: %s\n", s);
 
1693
        printf("scaling factor: %d\n", scale);
 
1694
        printf("query mode: %s\n", QUERYMODE[querymode]);
 
1695
        printf("number of clients: %d\n", nclients);
 
1696
        printf("number of threads: %d\n", nthreads);
 
1697
        if (duration <= 0)
 
1698
        {
 
1699
                printf("number of transactions per client: %d\n", nxacts);
 
1700
                printf("number of transactions actually processed: %d/%d\n",
 
1701
                           normal_xacts, nxacts * nclients);
 
1702
        }
 
1703
        else
 
1704
        {
 
1705
                printf("duration: %d s\n", duration);
 
1706
                printf("number of transactions actually processed: %d\n",
 
1707
                           normal_xacts);
 
1708
        }
 
1709
        printf("tps = %f (including connections establishing)\n", tps_include);
 
1710
        printf("tps = %f (excluding connections establishing)\n", tps_exclude);
 
1711
 
 
1712
        /* Report per-command latencies */
 
1713
        if (is_latencies)
 
1714
        {
 
1715
                int                     i;
 
1716
 
 
1717
                for (i = 0; i < num_files; i++)
 
1718
                {
 
1719
                        Command   **commands;
 
1720
 
 
1721
                        if (num_files > 1)
 
1722
                                printf("statement latencies in milliseconds, file %d:\n", i + 1);
 
1723
                        else
 
1724
                                printf("statement latencies in milliseconds:\n");
 
1725
 
 
1726
                        for (commands = sql_files[i]; *commands != NULL; commands++)
 
1727
                        {
 
1728
                                Command    *command = *commands;
 
1729
                                int                     cnum = command->command_num;
 
1730
                                double          total_time;
 
1731
                                instr_time      total_exec_elapsed;
 
1732
                                int                     total_exec_count;
 
1733
                                int                     t;
 
1734
 
 
1735
                                /* Accumulate per-thread data for command */
 
1736
                                INSTR_TIME_SET_ZERO(total_exec_elapsed);
 
1737
                                total_exec_count = 0;
 
1738
                                for (t = 0; t < nthreads; t++)
 
1739
                                {
 
1740
                                        TState     *thread = &threads[t];
 
1741
 
 
1742
                                        INSTR_TIME_ADD(total_exec_elapsed,
 
1743
                                                                   thread->exec_elapsed[cnum]);
 
1744
                                        total_exec_count += thread->exec_count[cnum];
 
1745
                                }
 
1746
 
 
1747
                                if (total_exec_count > 0)
 
1748
                                        total_time = INSTR_TIME_GET_MILLISEC(total_exec_elapsed) / (double) total_exec_count;
 
1749
                                else
 
1750
                                        total_time = 0.0;
 
1751
 
 
1752
                                printf("\t%f\t%s\n", total_time, command->line);
 
1753
                        }
 
1754
                }
 
1755
        }
 
1756
}
 
1757
 
 
1758
 
 
1759
int
 
1760
main(int argc, char **argv)
 
1761
{
 
1762
        int                     c;
 
1763
        int                     nclients = 1;   /* default number of simulated clients */
 
1764
        int                     nthreads = 1;   /* default number of threads */
 
1765
        int                     is_init_mode = 0;               /* initialize mode? */
 
1766
        int                     is_no_vacuum = 0;               /* no vacuum at all before testing? */
 
1767
        int                     do_vacuum_accounts = 0; /* do vacuum accounts before testing? */
 
1768
        int                     ttype = 0;              /* transaction type. 0: TPC-B, 1: SELECT only,
 
1769
                                                                 * 2: skip update of branches and tellers */
 
1770
        char       *filename = NULL;
 
1771
        bool            scale_given = false;
 
1772
 
 
1773
        CState     *state;                      /* status of clients */
 
1774
        TState     *threads;            /* array of thread */
 
1775
 
 
1776
        instr_time      start_time;             /* start up time */
 
1777
        instr_time      total_time;
 
1778
        instr_time      conn_total_time;
 
1779
        int                     total_xacts;
 
1780
 
 
1781
        int                     i;
 
1782
 
 
1783
#ifdef HAVE_GETRLIMIT
 
1784
        struct rlimit rlim;
 
1785
#endif
 
1786
 
 
1787
        PGconn     *con;
 
1788
        PGresult   *res;
 
1789
        char       *env;
 
1790
 
 
1791
        char            val[64];
 
1792
 
 
1793
        const char *progname;
 
1794
 
 
1795
        progname = get_progname(argv[0]);
 
1796
 
 
1797
        if (argc > 1)
 
1798
        {
 
1799
                if (strcmp(argv[1], "--help") == 0 || strcmp(argv[1], "-?") == 0)
 
1800
                {
 
1801
                        usage(progname);
 
1802
                        exit(0);
 
1803
                }
 
1804
                if (strcmp(argv[1], "--version") == 0 || strcmp(argv[1], "-V") == 0)
 
1805
                {
 
1806
                        puts("pgbench (PostgreSQL) " PG_VERSION);
 
1807
                        exit(0);
 
1808
                }
 
1809
        }
 
1810
 
 
1811
#ifdef WIN32
 
1812
        /* stderr is buffered on Win32. */
 
1813
        setvbuf(stderr, NULL, _IONBF, 0);
 
1814
#endif
 
1815
 
 
1816
        if ((env = getenv("PGHOST")) != NULL && *env != '\0')
 
1817
                pghost = env;
 
1818
        if ((env = getenv("PGPORT")) != NULL && *env != '\0')
 
1819
                pgport = env;
 
1820
        else if ((env = getenv("PGUSER")) != NULL && *env != '\0')
 
1821
                login = env;
 
1822
 
 
1823
        state = (CState *) xmalloc(sizeof(CState));
 
1824
        memset(state, 0, sizeof(CState));
 
1825
 
 
1826
        while ((c = getopt(argc, argv, "ih:nvp:dSNc:j:Crs:t:T:U:lf:D:F:M:")) != -1)
 
1827
        {
 
1828
                switch (c)
 
1829
                {
 
1830
                        case 'i':
 
1831
                                is_init_mode++;
 
1832
                                break;
 
1833
                        case 'h':
 
1834
                                pghost = optarg;
 
1835
                                break;
 
1836
                        case 'n':
 
1837
                                is_no_vacuum++;
 
1838
                                break;
 
1839
                        case 'v':
 
1840
                                do_vacuum_accounts++;
 
1841
                                break;
 
1842
                        case 'p':
 
1843
                                pgport = optarg;
 
1844
                                break;
 
1845
                        case 'd':
 
1846
                                debug++;
 
1847
                                break;
 
1848
                        case 'S':
 
1849
                                ttype = 1;
 
1850
                                break;
 
1851
                        case 'N':
 
1852
                                ttype = 2;
 
1853
                                break;
 
1854
                        case 'c':
 
1855
                                nclients = atoi(optarg);
 
1856
                                if (nclients <= 0 || nclients > MAXCLIENTS)
 
1857
                                {
 
1858
                                        fprintf(stderr, "invalid number of clients: %d\n", nclients);
 
1859
                                        exit(1);
 
1860
                                }
 
1861
#ifdef HAVE_GETRLIMIT
 
1862
#ifdef RLIMIT_NOFILE                    /* most platforms use RLIMIT_NOFILE */
 
1863
                                if (getrlimit(RLIMIT_NOFILE, &rlim) == -1)
 
1864
#else                                                   /* but BSD doesn't ... */
 
1865
                                if (getrlimit(RLIMIT_OFILE, &rlim) == -1)
 
1866
#endif   /* RLIMIT_NOFILE */
 
1867
                                {
 
1868
                                        fprintf(stderr, "getrlimit failed: %s\n", strerror(errno));
 
1869
                                        exit(1);
 
1870
                                }
 
1871
                                if (rlim.rlim_cur <= (nclients + 2))
 
1872
                                {
 
1873
                                        fprintf(stderr, "You need at least %d open files but you are only allowed to use %ld.\n", nclients + 2, (long) rlim.rlim_cur);
 
1874
                                        fprintf(stderr, "Use limit/ulimit to increase the limit before using pgbench.\n");
 
1875
                                        exit(1);
 
1876
                                }
 
1877
#endif   /* HAVE_GETRLIMIT */
 
1878
                                break;
 
1879
                        case 'j':                       /* jobs */
 
1880
                                nthreads = atoi(optarg);
 
1881
                                if (nthreads <= 0)
 
1882
                                {
 
1883
                                        fprintf(stderr, "invalid number of threads: %d\n", nthreads);
 
1884
                                        exit(1);
 
1885
                                }
 
1886
                                break;
 
1887
                        case 'C':
 
1888
                                is_connect = true;
 
1889
                                break;
 
1890
                        case 'r':
 
1891
                                is_latencies = true;
 
1892
                                break;
 
1893
                        case 's':
 
1894
                                scale_given = true;
 
1895
                                scale = atoi(optarg);
 
1896
                                if (scale <= 0)
 
1897
                                {
 
1898
                                        fprintf(stderr, "invalid scaling factor: %d\n", scale);
 
1899
                                        exit(1);
 
1900
                                }
 
1901
                                break;
 
1902
                        case 't':
 
1903
                                if (duration > 0)
 
1904
                                {
 
1905
                                        fprintf(stderr, "specify either a number of transactions (-t) or a duration (-T), not both.\n");
 
1906
                                        exit(1);
 
1907
                                }
 
1908
                                nxacts = atoi(optarg);
 
1909
                                if (nxacts <= 0)
 
1910
                                {
 
1911
                                        fprintf(stderr, "invalid number of transactions: %d\n", nxacts);
 
1912
                                        exit(1);
 
1913
                                }
 
1914
                                break;
 
1915
                        case 'T':
 
1916
                                if (nxacts > 0)
 
1917
                                {
 
1918
                                        fprintf(stderr, "specify either a number of transactions (-t) or a duration (-T), not both.\n");
 
1919
                                        exit(1);
 
1920
                                }
 
1921
                                duration = atoi(optarg);
 
1922
                                if (duration <= 0)
 
1923
                                {
 
1924
                                        fprintf(stderr, "invalid duration: %d\n", duration);
 
1925
                                        exit(1);
 
1926
                                }
 
1927
                                break;
 
1928
                        case 'U':
 
1929
                                login = optarg;
 
1930
                                break;
 
1931
                        case 'l':
 
1932
                                use_log = true;
 
1933
                                break;
 
1934
                        case 'f':
 
1935
                                ttype = 3;
 
1936
                                filename = optarg;
 
1937
                                if (process_file(filename) == false || *sql_files[num_files - 1] == NULL)
 
1938
                                        exit(1);
 
1939
                                break;
 
1940
                        case 'D':
 
1941
                                {
 
1942
                                        char       *p;
 
1943
 
 
1944
                                        if ((p = strchr(optarg, '=')) == NULL || p == optarg || *(p + 1) == '\0')
 
1945
                                        {
 
1946
                                                fprintf(stderr, "invalid variable definition: %s\n", optarg);
 
1947
                                                exit(1);
 
1948
                                        }
 
1949
 
 
1950
                                        *p++ = '\0';
 
1951
                                        if (!putVariable(&state[0], "option", optarg, p))
 
1952
                                                exit(1);
 
1953
                                }
 
1954
                                break;
 
1955
                        case 'F':
 
1956
                                fillfactor = atoi(optarg);
 
1957
                                if ((fillfactor < 10) || (fillfactor > 100))
 
1958
                                {
 
1959
                                        fprintf(stderr, "invalid fillfactor: %d\n", fillfactor);
 
1960
                                        exit(1);
 
1961
                                }
 
1962
                                break;
 
1963
                        case 'M':
 
1964
                                if (num_files > 0)
 
1965
                                {
 
1966
                                        fprintf(stderr, "query mode (-M) should be specifiled before transaction scripts (-f)\n");
 
1967
                                        exit(1);
 
1968
                                }
 
1969
                                for (querymode = 0; querymode < NUM_QUERYMODE; querymode++)
 
1970
                                        if (strcmp(optarg, QUERYMODE[querymode]) == 0)
 
1971
                                                break;
 
1972
                                if (querymode >= NUM_QUERYMODE)
 
1973
                                {
 
1974
                                        fprintf(stderr, "invalid query mode (-M): %s\n", optarg);
 
1975
                                        exit(1);
 
1976
                                }
 
1977
                                break;
 
1978
                        default:
 
1979
                                fprintf(stderr, _("Try \"%s --help\" for more information.\n"), progname);
 
1980
                                exit(1);
 
1981
                                break;
 
1982
                }
 
1983
        }
 
1984
 
 
1985
        if (argc > optind)
 
1986
                dbName = argv[optind];
 
1987
        else
 
1988
        {
 
1989
                if ((env = getenv("PGDATABASE")) != NULL && *env != '\0')
 
1990
                        dbName = env;
 
1991
                else if (login != NULL && *login != '\0')
 
1992
                        dbName = login;
 
1993
                else
 
1994
                        dbName = "";
 
1995
        }
 
1996
 
 
1997
        if (is_init_mode)
 
1998
        {
 
1999
                init();
 
2000
                exit(0);
 
2001
        }
 
2002
 
 
2003
        /* Use DEFAULT_NXACTS if neither nxacts nor duration is specified. */
 
2004
        if (nxacts <= 0 && duration <= 0)
 
2005
                nxacts = DEFAULT_NXACTS;
 
2006
 
 
2007
        if (nclients % nthreads != 0)
 
2008
        {
 
2009
                fprintf(stderr, "number of clients (%d) must be a multiple of number of threads (%d)\n", nclients, nthreads);
 
2010
                exit(1);
 
2011
        }
 
2012
 
 
2013
        /*
 
2014
         * is_latencies only works with multiple threads in thread-based
 
2015
         * implementations, not fork-based ones, because it supposes that the
 
2016
         * parent can see changes made to the per-thread execution stats by child
 
2017
         * threads.  It seems useful enough to accept despite this limitation, but
 
2018
         * perhaps we should FIXME someday (by passing the stats data back up
 
2019
         * through the parent-to-child pipes).
 
2020
         */
 
2021
#ifndef ENABLE_THREAD_SAFETY
 
2022
        if (is_latencies && nthreads > 1)
 
2023
        {
 
2024
                fprintf(stderr, "-r does not work with -j larger than 1 on this platform.\n");
 
2025
                exit(1);
 
2026
        }
 
2027
#endif
 
2028
 
 
2029
        /*
 
2030
         * save main process id in the global variable because process id will be
 
2031
         * changed after fork.
 
2032
         */
 
2033
        main_pid = (int) getpid();
 
2034
 
 
2035
        if (nclients > 1)
 
2036
        {
 
2037
                state = (CState *) xrealloc(state, sizeof(CState) * nclients);
 
2038
                memset(state + 1, 0, sizeof(CState) * (nclients - 1));
 
2039
 
 
2040
                /* copy any -D switch values to all clients */
 
2041
                for (i = 1; i < nclients; i++)
 
2042
                {
 
2043
                        int                     j;
 
2044
 
 
2045
                        state[i].id = i;
 
2046
                        for (j = 0; j < state[0].nvariables; j++)
 
2047
                        {
 
2048
                                if (!putVariable(&state[i], "startup", state[0].variables[j].name, state[0].variables[j].value))
 
2049
                                        exit(1);
 
2050
                        }
 
2051
                }
 
2052
        }
 
2053
 
 
2054
        if (debug)
 
2055
        {
 
2056
                if (duration <= 0)
 
2057
                        printf("pghost: %s pgport: %s nclients: %d nxacts: %d dbName: %s\n",
 
2058
                                   pghost, pgport, nclients, nxacts, dbName);
 
2059
                else
 
2060
                        printf("pghost: %s pgport: %s nclients: %d duration: %d dbName: %s\n",
 
2061
                                   pghost, pgport, nclients, duration, dbName);
 
2062
        }
 
2063
 
 
2064
        /* opening connection... */
 
2065
        con = doConnect();
 
2066
        if (con == NULL)
 
2067
                exit(1);
 
2068
 
 
2069
        if (PQstatus(con) == CONNECTION_BAD)
 
2070
        {
 
2071
                fprintf(stderr, "Connection to database '%s' failed.\n", dbName);
 
2072
                fprintf(stderr, "%s", PQerrorMessage(con));
 
2073
                exit(1);
 
2074
        }
 
2075
 
 
2076
        if (ttype != 3)
 
2077
        {
 
2078
                /*
 
2079
                 * get the scaling factor that should be same as count(*) from
 
2080
                 * pgbench_branches if this is not a custom query
 
2081
                 */
 
2082
                res = PQexec(con, "select count(*) from pgbench_branches");
 
2083
                if (PQresultStatus(res) != PGRES_TUPLES_OK)
 
2084
                {
 
2085
                        fprintf(stderr, "%s", PQerrorMessage(con));
 
2086
                        exit(1);
 
2087
                }
 
2088
                scale = atoi(PQgetvalue(res, 0, 0));
 
2089
                if (scale < 0)
 
2090
                {
 
2091
                        fprintf(stderr, "count(*) from pgbench_branches invalid (%d)\n", scale);
 
2092
                        exit(1);
 
2093
                }
 
2094
                PQclear(res);
 
2095
 
 
2096
                /* warn if we override user-given -s switch */
 
2097
                if (scale_given)
 
2098
                        fprintf(stderr,
 
2099
                        "Scale option ignored, using pgbench_branches table count = %d\n",
 
2100
                                        scale);
 
2101
        }
 
2102
 
 
2103
        /*
 
2104
         * :scale variables normally get -s or database scale, but don't override
 
2105
         * an explicit -D switch
 
2106
         */
 
2107
        if (getVariable(&state[0], "scale") == NULL)
 
2108
        {
 
2109
                snprintf(val, sizeof(val), "%d", scale);
 
2110
                for (i = 0; i < nclients; i++)
 
2111
                {
 
2112
                        if (!putVariable(&state[i], "startup", "scale", val))
 
2113
                                exit(1);
 
2114
                }
 
2115
        }
 
2116
 
 
2117
        if (!is_no_vacuum)
 
2118
        {
 
2119
                fprintf(stderr, "starting vacuum...");
 
2120
                executeStatement(con, "vacuum pgbench_branches");
 
2121
                executeStatement(con, "vacuum pgbench_tellers");
 
2122
                executeStatement(con, "truncate pgbench_history");
 
2123
                fprintf(stderr, "end.\n");
 
2124
 
 
2125
                if (do_vacuum_accounts)
 
2126
                {
 
2127
                        fprintf(stderr, "starting vacuum pgbench_accounts...");
 
2128
                        executeStatement(con, "vacuum analyze pgbench_accounts");
 
2129
                        fprintf(stderr, "end.\n");
 
2130
                }
 
2131
        }
 
2132
        PQfinish(con);
 
2133
 
 
2134
        /* set random seed */
 
2135
        INSTR_TIME_SET_CURRENT(start_time);
 
2136
        srandom((unsigned int) INSTR_TIME_GET_MICROSEC(start_time));
 
2137
 
 
2138
        /* process builtin SQL scripts */
 
2139
        switch (ttype)
 
2140
        {
 
2141
                case 0:
 
2142
                        sql_files[0] = process_builtin(tpc_b);
 
2143
                        num_files = 1;
 
2144
                        break;
 
2145
 
 
2146
                case 1:
 
2147
                        sql_files[0] = process_builtin(select_only);
 
2148
                        num_files = 1;
 
2149
                        break;
 
2150
 
 
2151
                case 2:
 
2152
                        sql_files[0] = process_builtin(simple_update);
 
2153
                        num_files = 1;
 
2154
                        break;
 
2155
 
 
2156
                default:
 
2157
                        break;
 
2158
        }
 
2159
 
 
2160
        /* set up thread data structures */
 
2161
        threads = (TState *) xmalloc(sizeof(TState) * nthreads);
 
2162
        for (i = 0; i < nthreads; i++)
 
2163
        {
 
2164
                TState     *thread = &threads[i];
 
2165
 
 
2166
                thread->tid = i;
 
2167
                thread->state = &state[nclients / nthreads * i];
 
2168
                thread->nstate = nclients / nthreads;
 
2169
 
 
2170
                if (is_latencies)
 
2171
                {
 
2172
                        /* Reserve memory for the thread to store per-command latencies */
 
2173
                        int                     t;
 
2174
 
 
2175
                        thread->exec_elapsed = (instr_time *)
 
2176
                                xmalloc(sizeof(instr_time) * num_commands);
 
2177
                        thread->exec_count = (int *)
 
2178
                                xmalloc(sizeof(int) * num_commands);
 
2179
 
 
2180
                        for (t = 0; t < num_commands; t++)
 
2181
                        {
 
2182
                                INSTR_TIME_SET_ZERO(thread->exec_elapsed[t]);
 
2183
                                thread->exec_count[t] = 0;
 
2184
                        }
 
2185
                }
 
2186
                else
 
2187
                {
 
2188
                        thread->exec_elapsed = NULL;
 
2189
                        thread->exec_count = NULL;
 
2190
                }
 
2191
        }
 
2192
 
 
2193
        /* get start up time */
 
2194
        INSTR_TIME_SET_CURRENT(start_time);
 
2195
 
 
2196
        /* set alarm if duration is specified. */
 
2197
        if (duration > 0)
 
2198
                setalarm(duration);
 
2199
 
 
2200
        /* start threads */
 
2201
        for (i = 0; i < nthreads; i++)
 
2202
        {
 
2203
                TState     *thread = &threads[i];
 
2204
 
 
2205
                INSTR_TIME_SET_CURRENT(thread->start_time);
 
2206
 
 
2207
                /* the first thread (i = 0) is executed by main thread */
 
2208
                if (i > 0)
 
2209
                {
 
2210
                        int                     err = pthread_create(&thread->thread, NULL, threadRun, thread);
 
2211
 
 
2212
                        if (err != 0 || thread->thread == INVALID_THREAD)
 
2213
                        {
 
2214
                                fprintf(stderr, "cannot create thread: %s\n", strerror(err));
 
2215
                                exit(1);
 
2216
                        }
 
2217
                }
 
2218
                else
 
2219
                {
 
2220
                        thread->thread = INVALID_THREAD;
 
2221
                }
 
2222
        }
 
2223
 
 
2224
        /* wait for threads and accumulate results */
 
2225
        total_xacts = 0;
 
2226
        INSTR_TIME_SET_ZERO(conn_total_time);
 
2227
        for (i = 0; i < nthreads; i++)
 
2228
        {
 
2229
                void       *ret = NULL;
 
2230
 
 
2231
                if (threads[i].thread == INVALID_THREAD)
 
2232
                        ret = threadRun(&threads[i]);
 
2233
                else
 
2234
                        pthread_join(threads[i].thread, &ret);
 
2235
 
 
2236
                if (ret != NULL)
 
2237
                {
 
2238
                        TResult    *r = (TResult *) ret;
 
2239
 
 
2240
                        total_xacts += r->xacts;
 
2241
                        INSTR_TIME_ADD(conn_total_time, r->conn_time);
 
2242
                        free(ret);
 
2243
                }
 
2244
        }
 
2245
        disconnect_all(state, nclients);
 
2246
 
 
2247
        /* get end time */
 
2248
        INSTR_TIME_SET_CURRENT(total_time);
 
2249
        INSTR_TIME_SUBTRACT(total_time, start_time);
 
2250
        printResults(ttype, total_xacts, nclients, threads, nthreads,
 
2251
                                 total_time, conn_total_time);
 
2252
 
 
2253
        return 0;
 
2254
}
 
2255
 
 
2256
static void *
 
2257
threadRun(void *arg)
 
2258
{
 
2259
        TState     *thread = (TState *) arg;
 
2260
        CState     *state = thread->state;
 
2261
        TResult    *result;
 
2262
        FILE       *logfile = NULL; /* per-thread log file */
 
2263
        instr_time      start,
 
2264
                                end;
 
2265
        int                     nstate = thread->nstate;
 
2266
        int                     remains = nstate;               /* number of remaining clients */
 
2267
        int                     i;
 
2268
 
 
2269
        result = xmalloc(sizeof(TResult));
 
2270
        INSTR_TIME_SET_ZERO(result->conn_time);
 
2271
 
 
2272
        /* open log file if requested */
 
2273
        if (use_log)
 
2274
        {
 
2275
                char            logpath[64];
 
2276
 
 
2277
                if (thread->tid == 0)
 
2278
                        snprintf(logpath, sizeof(logpath), "pgbench_log.%d", main_pid);
 
2279
                else
 
2280
                        snprintf(logpath, sizeof(logpath), "pgbench_log.%d.%d", main_pid, thread->tid);
 
2281
                logfile = fopen(logpath, "w");
 
2282
 
 
2283
                if (logfile == NULL)
 
2284
                {
 
2285
                        fprintf(stderr, "Couldn't open logfile \"%s\": %s", logpath, strerror(errno));
 
2286
                        goto done;
 
2287
                }
 
2288
        }
 
2289
 
 
2290
        if (!is_connect)
 
2291
        {
 
2292
                /* make connections to the database */
 
2293
                for (i = 0; i < nstate; i++)
 
2294
                {
 
2295
                        if ((state[i].con = doConnect()) == NULL)
 
2296
                                goto done;
 
2297
                }
 
2298
        }
 
2299
 
 
2300
        /* time after thread and connections set up */
 
2301
        INSTR_TIME_SET_CURRENT(result->conn_time);
 
2302
        INSTR_TIME_SUBTRACT(result->conn_time, thread->start_time);
 
2303
 
 
2304
        /* send start up queries in async manner */
 
2305
        for (i = 0; i < nstate; i++)
 
2306
        {
 
2307
                CState     *st = &state[i];
 
2308
                Command   **commands = sql_files[st->use_file];
 
2309
                int                     prev_ecnt = st->ecnt;
 
2310
 
 
2311
                st->use_file = getrand(0, num_files - 1);
 
2312
                if (!doCustom(thread, st, &result->conn_time, logfile))
 
2313
                        remains--;                      /* I've aborted */
 
2314
 
 
2315
                if (st->ecnt > prev_ecnt && commands[st->state]->type == META_COMMAND)
 
2316
                {
 
2317
                        fprintf(stderr, "Client %d aborted in state %d. Execution meta-command failed.\n", i, st->state);
 
2318
                        remains--;                      /* I've aborted */
 
2319
                        PQfinish(st->con);
 
2320
                        st->con = NULL;
 
2321
                }
 
2322
        }
 
2323
 
 
2324
        while (remains > 0)
 
2325
        {
 
2326
                fd_set          input_mask;
 
2327
                int                     maxsock;        /* max socket number to be waited */
 
2328
                int64           now_usec = 0;
 
2329
                int64           min_usec;
 
2330
 
 
2331
                FD_ZERO(&input_mask);
 
2332
 
 
2333
                maxsock = -1;
 
2334
                min_usec = INT64_MAX;
 
2335
                for (i = 0; i < nstate; i++)
 
2336
                {
 
2337
                        CState     *st = &state[i];
 
2338
                        Command   **commands = sql_files[st->use_file];
 
2339
                        int                     sock;
 
2340
 
 
2341
                        if (st->sleeping)
 
2342
                        {
 
2343
                                int                     this_usec;
 
2344
 
 
2345
                                if (min_usec == INT64_MAX)
 
2346
                                {
 
2347
                                        instr_time      now;
 
2348
 
 
2349
                                        INSTR_TIME_SET_CURRENT(now);
 
2350
                                        now_usec = INSTR_TIME_GET_MICROSEC(now);
 
2351
                                }
 
2352
 
 
2353
                                this_usec = st->until - now_usec;
 
2354
                                if (min_usec > this_usec)
 
2355
                                        min_usec = this_usec;
 
2356
                        }
 
2357
                        else if (st->con == NULL)
 
2358
                        {
 
2359
                                continue;
 
2360
                        }
 
2361
                        else if (commands[st->state]->type == META_COMMAND)
 
2362
                        {
 
2363
                                min_usec = 0;   /* the connection is ready to run */
 
2364
                                break;
 
2365
                        }
 
2366
 
 
2367
                        sock = PQsocket(st->con);
 
2368
                        if (sock < 0)
 
2369
                        {
 
2370
                                fprintf(stderr, "bad socket: %s\n", strerror(errno));
 
2371
                                goto done;
 
2372
                        }
 
2373
 
 
2374
                        FD_SET(sock, &input_mask);
 
2375
 
 
2376
                        if (maxsock < sock)
 
2377
                                maxsock = sock;
 
2378
                }
 
2379
 
 
2380
                if (min_usec > 0 && maxsock != -1)
 
2381
                {
 
2382
                        int                     nsocks; /* return from select(2) */
 
2383
 
 
2384
                        if (min_usec != INT64_MAX)
 
2385
                        {
 
2386
                                struct timeval timeout;
 
2387
 
 
2388
                                timeout.tv_sec = min_usec / 1000000;
 
2389
                                timeout.tv_usec = min_usec % 1000000;
 
2390
                                nsocks = select(maxsock + 1, &input_mask, NULL, NULL, &timeout);
 
2391
                        }
 
2392
                        else
 
2393
                                nsocks = select(maxsock + 1, &input_mask, NULL, NULL, NULL);
 
2394
                        if (nsocks < 0)
 
2395
                        {
 
2396
                                if (errno == EINTR)
 
2397
                                        continue;
 
2398
                                /* must be something wrong */
 
2399
                                fprintf(stderr, "select failed: %s\n", strerror(errno));
 
2400
                                goto done;
 
2401
                        }
 
2402
                }
 
2403
 
 
2404
                /* ok, backend returns reply */
 
2405
                for (i = 0; i < nstate; i++)
 
2406
                {
 
2407
                        CState     *st = &state[i];
 
2408
                        Command   **commands = sql_files[st->use_file];
 
2409
                        int                     prev_ecnt = st->ecnt;
 
2410
 
 
2411
                        if (st->con && (FD_ISSET(PQsocket(st->con), &input_mask)
 
2412
                                                        || commands[st->state]->type == META_COMMAND))
 
2413
                        {
 
2414
                                if (!doCustom(thread, st, &result->conn_time, logfile))
 
2415
                                        remains--;      /* I've aborted */
 
2416
                        }
 
2417
 
 
2418
                        if (st->ecnt > prev_ecnt && commands[st->state]->type == META_COMMAND)
 
2419
                        {
 
2420
                                fprintf(stderr, "Client %d aborted in state %d. Execution of meta-command failed.\n", i, st->state);
 
2421
                                remains--;              /* I've aborted */
 
2422
                                PQfinish(st->con);
 
2423
                                st->con = NULL;
 
2424
                        }
 
2425
                }
 
2426
        }
 
2427
 
 
2428
done:
 
2429
        INSTR_TIME_SET_CURRENT(start);
 
2430
        disconnect_all(state, nstate);
 
2431
        result->xacts = 0;
 
2432
        for (i = 0; i < nstate; i++)
 
2433
                result->xacts += state[i].cnt;
 
2434
        INSTR_TIME_SET_CURRENT(end);
 
2435
        INSTR_TIME_ACCUM_DIFF(result->conn_time, end, start);
 
2436
        if (logfile)
 
2437
                fclose(logfile);
 
2438
        return result;
 
2439
}
 
2440
 
 
2441
 
 
2442
/*
 
2443
 * Support for duration option: set timer_exceeded after so many seconds.
 
2444
 */
 
2445
 
 
2446
#ifndef WIN32
 
2447
 
 
2448
static void
 
2449
handle_sig_alarm(SIGNAL_ARGS)
 
2450
{
 
2451
        timer_exceeded = true;
 
2452
}
 
2453
 
 
2454
static void
 
2455
setalarm(int seconds)
 
2456
{
 
2457
        pqsignal(SIGALRM, handle_sig_alarm);
 
2458
        alarm(seconds);
 
2459
}
 
2460
 
 
2461
#ifndef ENABLE_THREAD_SAFETY
 
2462
 
 
2463
/*
 
2464
 * implements pthread using fork.
 
2465
 */
 
2466
 
 
2467
typedef struct fork_pthread
 
2468
{
 
2469
        pid_t           pid;
 
2470
        int                     pipes[2];
 
2471
}       fork_pthread;
 
2472
 
 
2473
static int
 
2474
pthread_create(pthread_t *thread,
 
2475
                           pthread_attr_t * attr,
 
2476
                           void *(*start_routine) (void *),
 
2477
                           void *arg)
 
2478
{
 
2479
        fork_pthread *th;
 
2480
        void       *ret;
 
2481
        instr_time      start_time;
 
2482
 
 
2483
        th = (fork_pthread *) xmalloc(sizeof(fork_pthread));
 
2484
        if (pipe(th->pipes) < 0)
 
2485
        {
 
2486
                free(th);
 
2487
                return errno;
 
2488
        }
 
2489
 
 
2490
        th->pid = fork();
 
2491
        if (th->pid == -1)                      /* error */
 
2492
        {
 
2493
                free(th);
 
2494
                return errno;
 
2495
        }
 
2496
        if (th->pid != 0)                       /* in parent process */
 
2497
        {
 
2498
                close(th->pipes[1]);
 
2499
                *thread = th;
 
2500
                return 0;
 
2501
        }
 
2502
 
 
2503
        /* in child process */
 
2504
        close(th->pipes[0]);
 
2505
 
 
2506
        /* set alarm again because the child does not inherit timers */
 
2507
        if (duration > 0)
 
2508
                setalarm(duration);
 
2509
 
 
2510
        /*
 
2511
         * Set a different random seed in each child process.  Otherwise they all
 
2512
         * inherit the parent's state and generate the same "random" sequence. (In
 
2513
         * the threaded case, the different threads will obtain subsets of the
 
2514
         * output of a single random() sequence, which should be okay for our
 
2515
         * purposes.)
 
2516
         */
 
2517
        INSTR_TIME_SET_CURRENT(start_time);
 
2518
        srandom(((unsigned int) INSTR_TIME_GET_MICROSEC(start_time)) +
 
2519
                        ((unsigned int) getpid()));
 
2520
 
 
2521
        ret = start_routine(arg);
 
2522
        write(th->pipes[1], ret, sizeof(TResult));
 
2523
        close(th->pipes[1]);
 
2524
        free(th);
 
2525
        exit(0);
 
2526
}
 
2527
 
 
2528
static int
 
2529
pthread_join(pthread_t th, void **thread_return)
 
2530
{
 
2531
        int                     status;
 
2532
 
 
2533
        while (waitpid(th->pid, &status, 0) != th->pid)
 
2534
        {
 
2535
                if (errno != EINTR)
 
2536
                        return errno;
 
2537
        }
 
2538
 
 
2539
        if (thread_return != NULL)
 
2540
        {
 
2541
                /* assume result is TResult */
 
2542
                *thread_return = xmalloc(sizeof(TResult));
 
2543
                if (read(th->pipes[0], *thread_return, sizeof(TResult)) != sizeof(TResult))
 
2544
                {
 
2545
                        free(*thread_return);
 
2546
                        *thread_return = NULL;
 
2547
                }
 
2548
        }
 
2549
        close(th->pipes[0]);
 
2550
 
 
2551
        free(th);
 
2552
        return 0;
 
2553
}
 
2554
#endif
 
2555
#else                                                   /* WIN32 */
 
2556
 
 
2557
static VOID CALLBACK
 
2558
win32_timer_callback(PVOID lpParameter, BOOLEAN TimerOrWaitFired)
 
2559
{
 
2560
        timer_exceeded = true;
 
2561
}
 
2562
 
 
2563
static void
 
2564
setalarm(int seconds)
 
2565
{
 
2566
        HANDLE          queue;
 
2567
        HANDLE          timer;
 
2568
 
 
2569
        /* This function will be called at most once, so we can cheat a bit. */
 
2570
        queue = CreateTimerQueue();
 
2571
        if (seconds > ((DWORD) -1) / 1000 ||
 
2572
                !CreateTimerQueueTimer(&timer, queue,
 
2573
                                                           win32_timer_callback, NULL, seconds * 1000, 0,
 
2574
                                                           WT_EXECUTEINTIMERTHREAD | WT_EXECUTEONLYONCE))
 
2575
        {
 
2576
                fprintf(stderr, "Failed to set timer\n");
 
2577
                exit(1);
 
2578
        }
 
2579
}
 
2580
 
 
2581
/* partial pthread implementation for Windows */
 
2582
 
 
2583
typedef struct win32_pthread
 
2584
{
 
2585
        HANDLE          handle;
 
2586
        void       *(*routine) (void *);
 
2587
        void       *arg;
 
2588
        void       *result;
 
2589
} win32_pthread;
 
2590
 
 
2591
static unsigned __stdcall
 
2592
win32_pthread_run(void *arg)
 
2593
{
 
2594
        win32_pthread *th = (win32_pthread *) arg;
 
2595
 
 
2596
        th->result = th->routine(th->arg);
 
2597
 
 
2598
        return 0;
 
2599
}
 
2600
 
 
2601
static int
 
2602
pthread_create(pthread_t *thread,
 
2603
                           pthread_attr_t * attr,
 
2604
                           void *(*start_routine) (void *),
 
2605
                           void *arg)
 
2606
{
 
2607
        int                     save_errno;
 
2608
        win32_pthread *th;
 
2609
 
 
2610
        th = (win32_pthread *) xmalloc(sizeof(win32_pthread));
 
2611
        th->routine = start_routine;
 
2612
        th->arg = arg;
 
2613
        th->result = NULL;
 
2614
 
 
2615
        th->handle = (HANDLE) _beginthreadex(NULL, 0, win32_pthread_run, th, 0, NULL);
 
2616
        if (th->handle == NULL)
 
2617
        {
 
2618
                save_errno = errno;
 
2619
                free(th);
 
2620
                return save_errno;
 
2621
        }
 
2622
 
 
2623
        *thread = th;
 
2624
        return 0;
 
2625
}
 
2626
 
 
2627
static int
 
2628
pthread_join(pthread_t th, void **thread_return)
 
2629
{
 
2630
        if (th == NULL || th->handle == NULL)
 
2631
                return errno = EINVAL;
 
2632
 
 
2633
        if (WaitForSingleObject(th->handle, INFINITE) != WAIT_OBJECT_0)
 
2634
        {
 
2635
                _dosmaperr(GetLastError());
 
2636
                return errno;
 
2637
        }
 
2638
 
 
2639
        if (thread_return)
 
2640
                *thread_return = th->result;
 
2641
 
 
2642
        CloseHandle(th->handle);
 
2643
        free(th);
 
2644
        return 0;
 
2645
}
 
2646
 
 
2647
#endif   /* WIN32 */