Debian Codegraph @

src/bin/pgbench/pgbench.c

raw
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 * src/bin/pgbench/pgbench.c
8 * Copyright (c) 2000-2025, 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 #if defined(WIN32) && FD_SETSIZE < 1024
31 #error FD_SETSIZE needs to have been increased
32 #endif
33
34 #include "postgres_fe.h"
35
36 #include <ctype.h>
37 #include <float.h>
38 #include <limits.h>
39 #include <math.h>
40 #include <signal.h>
41 #include <time.h>
42 #include <sys/time.h>
43 #include <sys/resource.h> /* for getrlimit */
44
45 /* For testing, PGBENCH_USE_SELECT can be defined to force use of that code */
46 #if defined(HAVE_PPOLL) && !defined(PGBENCH_USE_SELECT)
47 #define POLL_USING_PPOLL
48 #ifdef HAVE_POLL_H
49 #include <poll.h>
50 #endif
51 #else /* no ppoll(), so use select() */
52 #define POLL_USING_SELECT
53 #include <sys/select.h>
54 #endif
55
56 #include "catalog/pg_class_d.h"
57 #include "common/int.h"
58 #include "common/logging.h"
59 #include "common/pg_prng.h"
60 #include "common/string.h"
61 #include "common/username.h"
62 #include "fe_utils/cancel.h"
63 #include "fe_utils/conditional.h"
64 #include "fe_utils/option_utils.h"
65 #include "fe_utils/string_utils.h"
66 #include "getopt_long.h"
67 #include "libpq-fe.h"
68 #include "pgbench.h"
69 #include "port/pg_bitutils.h"
70 #include "portability/instr_time.h"
71
72 /* X/Open (XSI) requires <math.h> to provide M_PI, but core POSIX does not */
73 #ifndef M_PI
74 #define M_PI 3.14159265358979323846
75 #endif
76
77 #define ERRCODE_T_R_SERIALIZATION_FAILURE "40001"
78 #define ERRCODE_T_R_DEADLOCK_DETECTED "40P01"
79 #define ERRCODE_UNDEFINED_TABLE "42P01"
80
81 /*
82 * Hashing constants
83 */
84 #define FNV_PRIME UINT64CONST(0x100000001b3)
85 #define FNV_OFFSET_BASIS UINT64CONST(0xcbf29ce484222325)
86 #define MM2_MUL UINT64CONST(0xc6a4a7935bd1e995)
87 #define MM2_MUL_TIMES_8 UINT64CONST(0x35253c9ade8f4ca8)
88 #define MM2_ROT 47
89
90 /*
91 * Multi-platform socket set implementations
92 */
93
94 #ifdef POLL_USING_PPOLL
95 #define SOCKET_WAIT_METHOD "ppoll"
96
97 typedef struct socket_set
98 {
99 int maxfds; /* allocated length of pollfds[] array */
100 int curfds; /* number currently in use */
101 struct pollfd pollfds[FLEXIBLE_ARRAY_MEMBER];
102 } socket_set;
103
104 #endif /* POLL_USING_PPOLL */
105
106 #ifdef POLL_USING_SELECT
107 #define SOCKET_WAIT_METHOD "select"
108
109 typedef struct socket_set
110 {
111 int maxfd; /* largest FD currently set in fds */
112 fd_set fds;
113 } socket_set;
114
115 #endif /* POLL_USING_SELECT */
116
117 /*
118 * Multi-platform thread implementations
119 */
120
121 #ifdef WIN32
122 /* Use Windows threads */
123 #include <windows.h>
124 #define GETERRNO() (_dosmaperr(GetLastError()), errno)
125 #define THREAD_T HANDLE
126 #define THREAD_FUNC_RETURN_TYPE unsigned
127 #define THREAD_FUNC_RETURN return 0
128 #define THREAD_FUNC_CC __stdcall
129 #define THREAD_CREATE(handle, function, arg) \
130 ((*(handle) = (HANDLE) _beginthreadex(NULL, 0, (function), (arg), 0, NULL)) == 0 ? errno : 0)
131 #define THREAD_JOIN(handle) \
132 (WaitForSingleObject(handle, INFINITE) != WAIT_OBJECT_0 ? \
133 GETERRNO() : CloseHandle(handle) ? 0 : GETERRNO())
134 #define THREAD_BARRIER_T SYNCHRONIZATION_BARRIER
135 #define THREAD_BARRIER_INIT(barrier, n) \
136 (InitializeSynchronizationBarrier((barrier), (n), 0) ? 0 : GETERRNO())
137 #define THREAD_BARRIER_WAIT(barrier) \
138 EnterSynchronizationBarrier((barrier), \
139 SYNCHRONIZATION_BARRIER_FLAGS_BLOCK_ONLY)
140 #define THREAD_BARRIER_DESTROY(barrier)
141 #else
142 /* Use POSIX threads */
143 #include "port/pg_pthread.h"
144 #define THREAD_T pthread_t
145 #define THREAD_FUNC_RETURN_TYPE void *
146 #define THREAD_FUNC_RETURN return NULL
147 #define THREAD_FUNC_CC
148 #define THREAD_CREATE(handle, function, arg) \
149 pthread_create((handle), NULL, (function), (arg))
150 #define THREAD_JOIN(handle) \
151 pthread_join((handle), NULL)
152 #define THREAD_BARRIER_T pthread_barrier_t
153 #define THREAD_BARRIER_INIT(barrier, n) \
154 pthread_barrier_init((barrier), NULL, (n))
155 #define THREAD_BARRIER_WAIT(barrier) pthread_barrier_wait((barrier))
156 #define THREAD_BARRIER_DESTROY(barrier) pthread_barrier_destroy((barrier))
157 #endif
158
159
160 /********************************************************************
161 * some configurable parameters */
162
163 #define DEFAULT_INIT_STEPS "dtgvp" /* default -I setting */
164 #define ALL_INIT_STEPS "dtgGvpf" /* all possible steps */
165
166 #define LOG_STEP_SECONDS 5 /* seconds between log messages */
167 #define DEFAULT_NXACTS 10 /* default nxacts */
168
169 #define MIN_GAUSSIAN_PARAM 2.0 /* minimum parameter for gauss */
170
171 #define MIN_ZIPFIAN_PARAM 1.001 /* minimum parameter for zipfian */
172 #define MAX_ZIPFIAN_PARAM 1000.0 /* maximum parameter for zipfian */
173
174 static int nxacts = 0; /* number of transactions per client */
175 static int duration = 0; /* duration in seconds */
176 static int64 end_time = 0; /* when to stop in micro seconds, under -T */
177
178 /*
179 * scaling factor. for example, scale = 10 will make 1000000 tuples in
180 * pgbench_accounts table.
181 */
182 static int scale = 1;
183
184 /*
185 * fillfactor. for example, fillfactor = 90 will use only 90 percent
186 * space during inserts and leave 10 percent free.
187 */
188 static int fillfactor = 100;
189
190 /*
191 * use unlogged tables?
192 */
193 static bool unlogged_tables = false;
194
195 /*
196 * log sampling rate (1.0 = log everything, 0.0 = option not given)
197 */
198 static double sample_rate = 0.0;
199
200 /*
201 * When threads are throttled to a given rate limit, this is the target delay
202 * to reach that rate in usec. 0 is the default and means no throttling.
203 */
204 static double throttle_delay = 0;
205
206 /*
207 * Transactions which take longer than this limit (in usec) are counted as
208 * late, and reported as such, although they are completed anyway. When
209 * throttling is enabled, execution time slots that are more than this late
210 * are skipped altogether, and counted separately.
211 */
212 static int64 latency_limit = 0;
213
214 /*
215 * tablespace selection
216 */
217 static char *tablespace = NULL;
218 static char *index_tablespace = NULL;
219
220 /*
221 * Number of "pgbench_accounts" partitions. 0 is the default and means no
222 * partitioning.
223 */
224 static int partitions = 0;
225
226 /* partitioning strategy for "pgbench_accounts" */
227 typedef enum
228 {
229 PART_NONE, /* no partitioning */
230 PART_RANGE, /* range partitioning */
231 PART_HASH, /* hash partitioning */
232 } partition_method_t;
233
234 static partition_method_t partition_method = PART_NONE;
235 static const char *const PARTITION_METHOD[] = {"none", "range", "hash"};
236
237 /* random seed used to initialize base_random_sequence */
238 static int64 random_seed = -1;
239
240 /*
241 * end of configurable parameters
242 *********************************************************************/
243
244 #define nbranches 1 /* Makes little sense to change this. Change
245 * -s instead */
246 #define ntellers 10
247 #define naccounts 100000
248
249 /*
250 * The scale factor at/beyond which 32bit integers are incapable of storing
251 * 64bit values.
252 *
253 * Although the actual threshold is 21474, we use 20000 because it is easier to
254 * document and remember, and isn't that far away from the real threshold.
255 */
256 #define SCALE_32BIT_THRESHOLD 20000
257
258 static bool use_log; /* log transaction latencies to a file */
259 static bool use_quiet; /* quiet logging onto stderr */
260 static int agg_interval; /* log aggregates instead of individual
261 * transactions */
262 static bool per_script_stats = false; /* whether to collect stats per script */
263 static int progress = 0; /* thread progress report every this seconds */
264 static bool progress_timestamp = false; /* progress report with Unix time */
265 static int nclients = 1; /* number of clients */
266 static int nthreads = 1; /* number of threads */
267 static bool is_connect; /* establish connection for each transaction */
268 static bool report_per_command = false; /* report per-command latencies,
269 * retries after errors and failures
270 * (errors without retrying) */
271 static int main_pid; /* main process id used in log filename */
272
273 /*
274 * There are different types of restrictions for deciding that the current
275 * transaction with a serialization/deadlock error can no longer be retried and
276 * should be reported as failed:
277 * - max_tries (--max-tries) can be used to limit the number of tries;
278 * - latency_limit (-L) can be used to limit the total time of tries;
279 * - duration (-T) can be used to limit the total benchmark time.
280 *
281 * They can be combined together, and you need to use at least one of them to
282 * retry the transactions with serialization/deadlock errors. If none of them is
283 * used, the default value of max_tries is 1 and such transactions will not be
284 * retried.
285 */
286
287 /*
288 * We cannot retry a transaction after the serialization/deadlock error if its
289 * number of tries reaches this maximum; if its value is zero, it is not used.
290 */
291 static uint32 max_tries = 1;
292
293 static bool failures_detailed = false; /* whether to group failures in
294 * reports or logs by basic types */
295
296 static const char *pghost = NULL;
297 static const char *pgport = NULL;
298 static const char *username = NULL;
299 static const char *dbName = NULL;
300 static char *logfile_prefix = NULL;
301 static const char *progname;
302
303 #define WSEP '@' /* weight separator */
304
305 static volatile sig_atomic_t timer_exceeded = false; /* flag from signal
306 * handler */
307
308 /*
309 * We don't want to allocate variables one by one; for efficiency, add a
310 * constant margin each time it overflows.
311 */
312 #define VARIABLES_ALLOC_MARGIN 8
313
314 /*
315 * Variable definitions.
316 *
317 * If a variable only has a string value, "svalue" is that value, and value is
318 * "not set". If the value is known, "value" contains the value (in any
319 * variant).
320 *
321 * In this case "svalue" contains the string equivalent of the value, if we've
322 * had occasion to compute that, or NULL if we haven't.
323 */
324 typedef struct
325 {
326 char *name; /* variable's name */
327 char *svalue; /* its value in string form, if known */
328 PgBenchValue value; /* actual variable's value */
329 } Variable;
330
331 /*
332 * Data structure for client variables.
333 */
334 typedef struct
335 {
336 Variable *vars; /* array of variable definitions */
337 int nvars; /* number of variables */
338
339 /*
340 * The maximum number of variables that we can currently store in 'vars'
341 * without having to reallocate more space. We must always have max_vars
342 * >= nvars.
343 */
344 int max_vars;
345
346 bool vars_sorted; /* are variables sorted by name? */
347 } Variables;
348
349 #define MAX_SCRIPTS 128 /* max number of SQL scripts allowed */
350 #define SHELL_COMMAND_SIZE 256 /* maximum size allowed for shell command */
351
352 /*
353 * Simple data structure to keep stats about something.
354 *
355 * XXX probably the first value should be kept and used as an offset for
356 * better numerical stability...
357 */
358 typedef struct SimpleStats
359 {
360 int64 count; /* how many values were encountered */
361 double min; /* the minimum seen */
362 double max; /* the maximum seen */
363 double sum; /* sum of values */
364 double sum2; /* sum of squared values */
365 } SimpleStats;
366
367 /*
368 * The instr_time type is expensive when dealing with time arithmetic. Define
369 * a type to hold microseconds instead. Type int64 is good enough for about
370 * 584500 years.
371 */
372 typedef int64 pg_time_usec_t;
373
374 /*
375 * Data structure to hold various statistics: per-thread and per-script stats
376 * are maintained and merged together.
377 */
378 typedef struct StatsData
379 {
380 pg_time_usec_t start_time; /* interval start time, for aggregates */
381
382 /*----------
383 * Transactions are counted depending on their execution and outcome.
384 * First a transaction may have started or not: skipped transactions occur
385 * under --rate and --latency-limit when the client is too late to execute
386 * them. Secondly, a started transaction may ultimately succeed or fail,
387 * possibly after some retries when --max-tries is not one. Thus
388 *
389 * the number of all transactions =
390 * 'skipped' (it was too late to execute them) +
391 * 'cnt' (the number of successful transactions) +
392 * 'failed' (the number of failed transactions).
393 *
394 * A successful transaction can have several unsuccessful tries before a
395 * successful run. Thus
396 *
397 * 'cnt' (the number of successful transactions) =
398 * successfully retried transactions (they got a serialization or a
399 * deadlock error(s), but were
400 * successfully retried from the very
401 * beginning) +
402 * directly successful transactions (they were successfully completed on
403 * the first try).
404 *
405 * A failed transaction is defined as unsuccessfully retried transactions.
406 * It can be one of two types:
407 *
408 * failed (the number of failed transactions) =
409 * 'serialization_failures' (they got a serialization error and were not
410 * successfully retried) +
411 * 'deadlock_failures' (they got a deadlock error and were not
412 * successfully retried).
413 *
414 * If the transaction was retried after a serialization or a deadlock
415 * error this does not guarantee that this retry was successful. Thus
416 *
417 * 'retries' (number of retries) =
418 * number of retries in all retried transactions =
419 * number of retries in (successfully retried transactions +
420 * failed transactions);
421 *
422 * 'retried' (number of all retried transactions) =
423 * successfully retried transactions +
424 * failed transactions.
425 *----------
426 */
427 int64 cnt; /* number of successful transactions, not
428 * including 'skipped' */
429 int64 skipped; /* number of transactions skipped under --rate
430 * and --latency-limit */
431 int64 retries; /* number of retries after a serialization or
432 * a deadlock error in all the transactions */
433 int64 retried; /* number of all transactions that were
434 * retried after a serialization or a deadlock
435 * error (perhaps the last try was
436 * unsuccessful) */
437 int64 serialization_failures; /* number of transactions that were
438 * not successfully retried after a
439 * serialization error */
440 int64 deadlock_failures; /* number of transactions that were not
441 * successfully retried after a deadlock
442 * error */
443 SimpleStats latency;
444 SimpleStats lag;
445 } StatsData;
446
447 /*
448 * For displaying Unix epoch timestamps, as some time functions may have
449 * another reference.
450 */
451 static pg_time_usec_t epoch_shift;
452
453 /*
454 * Error status for errors during script execution.
455 */
456 typedef enum EStatus
457 {
458 ESTATUS_NO_ERROR = 0,
459 ESTATUS_META_COMMAND_ERROR,
460
461 /* SQL errors */
462 ESTATUS_SERIALIZATION_ERROR,
463 ESTATUS_DEADLOCK_ERROR,
464 ESTATUS_OTHER_SQL_ERROR,
465 } EStatus;
466
467 /*
468 * Transaction status at the end of a command.
469 */
470 typedef enum TStatus
471 {
472 TSTATUS_IDLE,
473 TSTATUS_IN_BLOCK,
474 TSTATUS_CONN_ERROR,
475 TSTATUS_OTHER_ERROR,
476 } TStatus;
477
478 /* Various random sequences are initialized from this one. */
479 static pg_prng_state base_random_sequence;
480
481 /* Synchronization barrier for start and connection */
482 static THREAD_BARRIER_T barrier;
483
484 /*
485 * Connection state machine states.
486 */
487 typedef enum
488 {
489 /*
490 * The client must first choose a script to execute. Once chosen, it can
491 * either be throttled (state CSTATE_PREPARE_THROTTLE under --rate), start
492 * right away (state CSTATE_START_TX) or not start at all if the timer was
493 * exceeded (state CSTATE_FINISHED).
494 */
495 CSTATE_CHOOSE_SCRIPT,
496
497 /*
498 * CSTATE_START_TX performs start-of-transaction processing. Establishes
499 * a new connection for the transaction in --connect mode, records the
500 * transaction start time, and proceed to the first command.
501 *
502 * Note: once a script is started, it will either error or run till its
503 * end, where it may be interrupted. It is not interrupted while running,
504 * so pgbench --time is to be understood as tx are allowed to start in
505 * that time, and will finish when their work is completed.
506 */
507 CSTATE_START_TX,
508
509 /*
510 * In CSTATE_PREPARE_THROTTLE state, we calculate when to begin the next
511 * transaction, and advance to CSTATE_THROTTLE. CSTATE_THROTTLE state
512 * sleeps until that moment, then advances to CSTATE_START_TX, or
513 * CSTATE_FINISHED if the next transaction would start beyond the end of
514 * the run.
515 */
516 CSTATE_PREPARE_THROTTLE,
517 CSTATE_THROTTLE,
518
519 /*
520 * We loop through these states, to process each command in the script:
521 *
522 * CSTATE_START_COMMAND starts the execution of a command. On a SQL
523 * command, the command is sent to the server, and we move to
524 * CSTATE_WAIT_RESULT state unless in pipeline mode. On a \sleep
525 * meta-command, the timer is set, and we enter the CSTATE_SLEEP state to
526 * wait for it to expire. Other meta-commands are executed immediately. If
527 * the command about to start is actually beyond the end of the script,
528 * advance to CSTATE_END_TX.
529 *
530 * CSTATE_WAIT_RESULT waits until we get a result set back from the server
531 * for the current command.
532 *
533 * CSTATE_SLEEP waits until the end of \sleep.
534 *
535 * CSTATE_END_COMMAND records the end-of-command timestamp, increments the
536 * command counter, and loops back to CSTATE_START_COMMAND state.
537 *
538 * CSTATE_SKIP_COMMAND is used by conditional branches which are not
539 * executed. It quickly skip commands that do not need any evaluation.
540 * This state can move forward several commands, till there is something
541 * to do or the end of the script.
542 */
543 CSTATE_START_COMMAND,
544 CSTATE_WAIT_RESULT,
545 CSTATE_SLEEP,
546 CSTATE_END_COMMAND,
547 CSTATE_SKIP_COMMAND,
548
549 /*
550 * States for failed commands.
551 *
552 * If the SQL/meta command fails, in CSTATE_ERROR clean up after an error:
553 * (1) clear the conditional stack; (2) if we have an unterminated
554 * (possibly failed) transaction block, send the rollback command to the
555 * server and wait for the result in CSTATE_WAIT_ROLLBACK_RESULT. If
556 * something goes wrong with rolling back, go to CSTATE_ABORTED.
557 *
558 * But if everything is ok we are ready for future transactions: if this
559 * is a serialization or deadlock error and we can re-execute the
560 * transaction from the very beginning, go to CSTATE_RETRY; otherwise go
561 * to CSTATE_FAILURE.
562 *
563 * In CSTATE_RETRY report an error, set the same parameters for the
564 * transaction execution as in the previous tries and process the first
565 * transaction command in CSTATE_START_COMMAND.
566 *
567 * In CSTATE_FAILURE report a failure, set the parameters for the
568 * transaction execution as they were before the first run of this
569 * transaction (except for a random state) and go to CSTATE_END_TX to
570 * complete this transaction.
571 */
572 CSTATE_ERROR,
573 CSTATE_WAIT_ROLLBACK_RESULT,
574 CSTATE_RETRY,
575 CSTATE_FAILURE,
576
577 /*
578 * CSTATE_END_TX performs end-of-transaction processing. It calculates
579 * latency, and logs the transaction. In --connect mode, it closes the
580 * current connection.
581 *
582 * Then either starts over in CSTATE_CHOOSE_SCRIPT, or enters
583 * CSTATE_FINISHED if we have no more work to do.
584 */
585 CSTATE_END_TX,
586
587 /*
588 * Final states. CSTATE_ABORTED means that the script execution was
589 * aborted because a command failed, CSTATE_FINISHED means success.
590 */
591 CSTATE_ABORTED,
592 CSTATE_FINISHED,
593 } ConnectionStateEnum;
594
595 /*
596 * Connection state.
597 */
598 typedef struct
599 {
600 PGconn *con; /* connection handle to DB */
601 int id; /* client No. */
602 ConnectionStateEnum state; /* state machine's current state. */
603 ConditionalStack cstack; /* enclosing conditionals state */
604
605 /*
606 * Separate randomness for each client. This is used for random functions
607 * PGBENCH_RANDOM_* during the execution of the script.
608 */
609 pg_prng_state cs_func_rs;
610
611 int use_file; /* index in sql_script for this client */
612 int command; /* command number in script */
613 int num_syncs; /* number of ongoing sync commands */
614
615 /* client variables */
616 Variables variables;
617
618 /* various times about current transaction in microseconds */
619 pg_time_usec_t txn_scheduled; /* scheduled start time of transaction */
620 pg_time_usec_t sleep_until; /* scheduled start time of next cmd */
621 pg_time_usec_t txn_begin; /* used for measuring schedule lag times */
622 pg_time_usec_t stmt_begin; /* used for measuring statement latencies */
623
624 /* whether client prepared each command of each script */
625 bool **prepared;
626
627 /*
628 * For processing failures and repeating transactions with serialization
629 * or deadlock errors:
630 */
631 EStatus estatus; /* the error status of the current transaction
632 * execution; this is ESTATUS_NO_ERROR if
633 * there were no errors */
634 pg_prng_state random_state; /* random state */
635 uint32 tries; /* how many times have we already tried the
636 * current transaction? */
637
638 /* per client collected stats */
639 int64 cnt; /* client transaction count, for -t; skipped
640 * and failed transactions are also counted
641 * here */
642 } CState;
643
644 /*
645 * Thread state
646 */
647 typedef struct
648 {
649 int tid; /* thread id */
650 THREAD_T thread; /* thread handle */
651 CState *state; /* array of CState */
652 int nstate; /* length of state[] */
653
654 /*
655 * Separate randomness for each thread. Each thread option uses its own
656 * random state to make all of them independent of each other and
657 * therefore deterministic at the thread level.
658 */
659 pg_prng_state ts_choose_rs; /* random state for selecting a script */
660 pg_prng_state ts_throttle_rs; /* random state for transaction throttling */
661 pg_prng_state ts_sample_rs; /* random state for log sampling */
662
663 int64 throttle_trigger; /* previous/next throttling (us) */
664 FILE *logfile; /* where to log, or NULL */
665
666 /* per thread collected stats in microseconds */
667 pg_time_usec_t create_time; /* thread creation time */
668 pg_time_usec_t started_time; /* thread is running */
669 pg_time_usec_t bench_start; /* thread is benchmarking */
670 pg_time_usec_t conn_duration; /* cumulated connection and disconnection
671 * delays */
672
673 StatsData stats;
674 int64 latency_late; /* count executed but late transactions */
675 } TState;
676
677 /*
678 * queries read from files
679 */
680 #define SQL_COMMAND 1
681 #define META_COMMAND 2
682
683 /*
684 * max number of backslash command arguments or SQL variables,
685 * including the command or SQL statement itself
686 */
687 #define MAX_ARGS 256
688
689 typedef enum MetaCommand
690 {
691 META_NONE, /* not a known meta-command */
692 META_SET, /* \set */
693 META_SETSHELL, /* \setshell */
694 META_SHELL, /* \shell */
695 META_SLEEP, /* \sleep */
696 META_GSET, /* \gset */
697 META_ASET, /* \aset */
698 META_IF, /* \if */
699 META_ELIF, /* \elif */
700 META_ELSE, /* \else */
701 META_ENDIF, /* \endif */
702 META_STARTPIPELINE, /* \startpipeline */
703 META_SYNCPIPELINE, /* \syncpipeline */
704 META_ENDPIPELINE, /* \endpipeline */
705 } MetaCommand;
706
707 typedef enum QueryMode
708 {
709 QUERY_SIMPLE, /* simple query */
710 QUERY_EXTENDED, /* extended query */
711 QUERY_PREPARED, /* extended query with prepared statements */
712 NUM_QUERYMODE
713 } QueryMode;
714
715 static QueryMode querymode = QUERY_SIMPLE;
716 static const char *const QUERYMODE[] = {"simple", "extended", "prepared"};
717
718 /*
719 * struct Command represents one command in a script.
720 *
721 * lines The raw, possibly multi-line command text. Variable substitution
722 * not applied.
723 * first_line A short, single-line extract of 'lines', for error reporting.
724 * type SQL_COMMAND or META_COMMAND
725 * meta The type of meta-command, with META_NONE/GSET/ASET if command
726 * is SQL.
727 * argc Number of arguments of the command, 0 if not yet processed.
728 * argv Command arguments, the first of which is the command or SQL
729 * string itself. For SQL commands, after post-processing
730 * argv[0] is the same as 'lines' with variables substituted.
731 * prepname The name that this command is prepared under, in prepare mode
732 * varprefix SQL commands terminated with \gset or \aset have this set
733 * to a non NULL value. If nonempty, it's used to prefix the
734 * variable name that receives the value.
735 * aset do gset on all possible queries of a combined query (\;).
736 * expr Parsed expression, if needed.
737 * stats Time spent in this command.
738 * retries Number of retries after a serialization or deadlock error in the
739 * current command.
740 * failures Number of errors in the current command that were not retried.
741 */
742 typedef struct Command
743 {
744 PQExpBufferData lines;
745 char *first_line;
746 int type;
747 MetaCommand meta;
748 int argc;
749 char *argv[MAX_ARGS];
750 char *prepname;
751 char *varprefix;
752 PgBenchExpr *expr;
753 SimpleStats stats;
754 int64 retries;
755 int64 failures;
756 } Command;
757
758 typedef struct ParsedScript
759 {
760 const char *desc; /* script descriptor (eg, file name) */
761 int weight; /* selection weight */
762 Command **commands; /* NULL-terminated array of Commands */
763 StatsData stats; /* total time spent in script */
764 } ParsedScript;
765
766 static ParsedScript sql_script[MAX_SCRIPTS]; /* SQL script files */
767 static int num_scripts; /* number of scripts in sql_script[] */
768 static int64 total_weight = 0;
769
770 static bool verbose_errors = false; /* print verbose messages of all errors */
771
772 static bool exit_on_abort = false; /* exit when any client is aborted */
773
774 /* Builtin test scripts */
775 typedef struct BuiltinScript
776 {
777 const char *name; /* very short name for -b ... */
778 const char *desc; /* short description */
779 const char *script; /* actual pgbench script */
780 } BuiltinScript;
781
782 static const BuiltinScript builtin_script[] =
783 {
784 {
785 "tpcb-like",
786 "<builtin: TPC-B (sort of)>",
787 "\\set aid random(1, " CppAsString2(naccounts) " * :scale)\n"
788 "\\set bid random(1, " CppAsString2(nbranches) " * :scale)\n"
789 "\\set tid random(1, " CppAsString2(ntellers) " * :scale)\n"
790 "\\set delta random(-5000, 5000)\n"
791 "BEGIN;\n"
792 "UPDATE pgbench_accounts SET abalance = abalance + :delta WHERE aid = :aid;\n"
793 "SELECT abalance FROM pgbench_accounts WHERE aid = :aid;\n"
794 "UPDATE pgbench_tellers SET tbalance = tbalance + :delta WHERE tid = :tid;\n"
795 "UPDATE pgbench_branches SET bbalance = bbalance + :delta WHERE bid = :bid;\n"
796 "INSERT INTO pgbench_history (tid, bid, aid, delta, mtime) VALUES (:tid, :bid, :aid, :delta, CURRENT_TIMESTAMP);\n"
797 "END;\n"
798 },
799 {
800 "simple-update",
801 "<builtin: simple update>",
802 "\\set aid random(1, " CppAsString2(naccounts) " * :scale)\n"
803 "\\set bid random(1, " CppAsString2(nbranches) " * :scale)\n"
804 "\\set tid random(1, " CppAsString2(ntellers) " * :scale)\n"
805 "\\set delta random(-5000, 5000)\n"
806 "BEGIN;\n"
807 "UPDATE pgbench_accounts SET abalance = abalance + :delta WHERE aid = :aid;\n"
808 "SELECT abalance FROM pgbench_accounts WHERE aid = :aid;\n"
809 "INSERT INTO pgbench_history (tid, bid, aid, delta, mtime) VALUES (:tid, :bid, :aid, :delta, CURRENT_TIMESTAMP);\n"
810 "END;\n"
811 },
812 {
813 "select-only",
814 "<builtin: select only>",
815 "\\set aid random(1, " CppAsString2(naccounts) " * :scale)\n"
816 "SELECT abalance FROM pgbench_accounts WHERE aid = :aid;\n"
817 }
818 };
819
820
821 /* Function prototypes */
822 static void setNullValue(PgBenchValue *pv);
823 static void setBoolValue(PgBenchValue *pv, bool bval);
824 static void setIntValue(PgBenchValue *pv, int64 ival);
825 static void setDoubleValue(PgBenchValue *pv, double dval);
826 static bool evaluateExpr(CState *st, PgBenchExpr *expr,
827 PgBenchValue *retval);
828 static ConnectionStateEnum executeMetaCommand(CState *st, pg_time_usec_t *now);
829 static void doLog(TState *thread, CState *st,
830 StatsData *agg, bool skipped, double latency, double lag);
831 static void processXactStats(TState *thread, CState *st, pg_time_usec_t *now,
832 bool skipped, StatsData *agg);
833 static void addScript(const ParsedScript *script);
834 static THREAD_FUNC_RETURN_TYPE THREAD_FUNC_CC threadRun(void *arg);
835 static void finishCon(CState *st);
836 static void setalarm(int seconds);
837 static socket_set *alloc_socket_set(int count);
838 static void free_socket_set(socket_set *sa);
839 static void clear_socket_set(socket_set *sa);
840 static void add_socket_to_set(socket_set *sa, int fd, int idx);
841 static int wait_on_socket_set(socket_set *sa, int64 usecs);
842 static bool socket_has_input(socket_set *sa, int fd, int idx);
843
844 /* callback used to build rows for COPY during data loading */
845 typedef void (*initRowMethod) (PQExpBufferData *sql, int64 curr);
846
847 /* callback functions for our flex lexer */
848 static const PsqlScanCallbacks pgbench_callbacks = {
849 NULL, /* don't need get_variable functionality */
850 };
851
852 static char
853 get_table_relkind(PGconn *con, const char *table)
854 {
855 PGresult *res;
856 char *val;
857 char relkind;
858 const char *params[1] = {table};
859 const char *sql =
860 "SELECT relkind FROM pg_catalog.pg_class WHERE oid=$1::pg_catalog.regclass";
861
862 res = PQexecParams(con, sql, 1, NULL, params, NULL, NULL, 0);
863 if (PQresultStatus(res) != PGRES_TUPLES_OK)
864 {
865 pg_log_error("query failed: %s", PQerrorMessage(con));
866 pg_log_error_detail("Query was: %s", sql);
867 exit(1);
868 }
869 val = PQgetvalue(res, 0, 0);
870 Assert(strlen(val) == 1);
871 relkind = val[0];
872 PQclear(res);
873
874 return relkind;
875 }
876
877 static inline pg_time_usec_t
878 pg_time_now(void)
879 {
880 instr_time now;
881
882 INSTR_TIME_SET_CURRENT(now);
883
884 return (pg_time_usec_t) INSTR_TIME_GET_MICROSEC(now);
885 }
886
887 static inline void
888 pg_time_now_lazy(pg_time_usec_t *now)
889 {
890 if ((*now) == 0)
891 (*now) = pg_time_now();
892 }
893
894 #define PG_TIME_GET_DOUBLE(t) (0.000001 * (t))
895
896 static void
897 usage(void)
898 {
899 printf("%s is a benchmarking tool for PostgreSQL.\n\n"
900 "Usage:\n"
901 " %s [OPTION]... [DBNAME]\n"
902 "\nInitialization options:\n"
903 " -i, --initialize invokes initialization mode\n"
904 " -I, --init-steps=[" ALL_INIT_STEPS "]+ (default \"" DEFAULT_INIT_STEPS "\")\n"
905 " run selected initialization steps, in the specified order\n"
906 " d: drop any existing pgbench tables\n"
907 " t: create the tables used by the standard pgbench scenario\n"
908 " g: generate data, client-side\n"
909 " G: generate data, server-side\n"
910 " v: invoke VACUUM on the standard tables\n"
911 " p: create primary key indexes on the standard tables\n"
912 " f: create foreign keys between the standard tables\n"
913 " -F, --fillfactor=NUM set fill factor\n"
914 " -n, --no-vacuum do not run VACUUM during initialization\n"
915 " -q, --quiet quiet logging (one message each 5 seconds)\n"
916 " -s, --scale=NUM scaling factor\n"
917 " --foreign-keys create foreign key constraints between tables\n"
918 " --index-tablespace=TABLESPACE\n"
919 " create indexes in the specified tablespace\n"
920 " --partition-method=(range|hash)\n"
921 " partition pgbench_accounts with this method (default: range)\n"
922 " --partitions=NUM partition pgbench_accounts into NUM parts (default: 0)\n"
923 " --tablespace=TABLESPACE create tables in the specified tablespace\n"
924 " --unlogged-tables create tables as unlogged tables\n"
925 "\nOptions to select what to run:\n"
926 " -b, --builtin=NAME[@W] add builtin script NAME weighted at W (default: 1)\n"
927 " (use \"-b list\" to list available scripts)\n"
928 " -f, --file=FILENAME[@W] add script FILENAME weighted at W (default: 1)\n"
929 " -N, --skip-some-updates skip updates of pgbench_tellers and pgbench_branches\n"
930 " (same as \"-b simple-update\")\n"
931 " -S, --select-only perform SELECT-only transactions\n"
932 " (same as \"-b select-only\")\n"
933 "\nBenchmarking options:\n"
934 " -c, --client=NUM number of concurrent database clients (default: 1)\n"
935 " -C, --connect establish new connection for each transaction\n"
936 " -D, --define=VARNAME=VALUE\n"
937 " define variable for use by custom script\n"
938 " -j, --jobs=NUM number of threads (default: 1)\n"
939 " -l, --log write transaction times to log file\n"
940 " -L, --latency-limit=NUM count transactions lasting more than NUM ms as late\n"
941 " -M, --protocol=simple|extended|prepared\n"
942 " protocol for submitting queries (default: simple)\n"
943 " -n, --no-vacuum do not run VACUUM before tests\n"
944 " -P, --progress=NUM show thread progress report every NUM seconds\n"
945 " -r, --report-per-command report latencies, failures, and retries per command\n"
946 " -R, --rate=NUM target rate in transactions per second\n"
947 " -s, --scale=NUM report this scale factor in output\n"
948 " -t, --transactions=NUM number of transactions each client runs (default: 10)\n"
949 " -T, --time=NUM duration of benchmark test in seconds\n"
950 " -v, --vacuum-all vacuum all four standard tables before tests\n"
951 " --aggregate-interval=NUM aggregate data over NUM seconds\n"
952 " --exit-on-abort exit when any client is aborted\n"
953 " --failures-detailed report the failures grouped by basic types\n"
954 " --log-prefix=PREFIX prefix for transaction time log file\n"
955 " (default: \"pgbench_log\")\n"
956 " --max-tries=NUM max number of tries to run transaction (default: 1)\n"
957 " --progress-timestamp use Unix epoch timestamps for progress\n"
958 " --random-seed=SEED set random seed (\"time\", \"rand\", integer)\n"
959 " --sampling-rate=NUM fraction of transactions to log (e.g., 0.01 for 1%%)\n"
960 " --show-script=NAME show builtin script code, then exit\n"
961 " --verbose-errors print messages of all errors\n"
962 "\nCommon options:\n"
963 " --debug print debugging output\n"
964 " -d, --dbname=DBNAME database name to connect to\n"
965 " -h, --host=HOSTNAME database server host or socket directory\n"
966 " -p, --port=PORT database server port number\n"
967 " -U, --username=USERNAME connect as specified database user\n"
968 " -V, --version output version information, then exit\n"
969 " -?, --help show this help, then exit\n"
970 "\n"
971 "Report bugs to <%s>.\n"
972 "%s home page: <%s>\n",
973 progname, progname, PACKAGE_BUGREPORT, PACKAGE_NAME, PACKAGE_URL);
974 }
975
976 /* return whether str matches "^\s*[-+]?[0-9]+$" */
977 static bool
978 is_an_int(const char *str)
979 {
980 const char *ptr = str;
981
982 /* skip leading spaces; cast is consistent with strtoint64 */
983 while (*ptr && isspace((unsigned char) *ptr))
984 ptr++;
985
986 /* skip sign */
987 if (*ptr == '+' || *ptr == '-')
988 ptr++;
989
990 /* at least one digit */
991 if (*ptr && !isdigit((unsigned char) *ptr))
992 return false;
993
994 /* eat all digits */
995 while (*ptr && isdigit((unsigned char) *ptr))
996 ptr++;
997
998 /* must have reached end of string */
999 return *ptr == '\0';
1000 }
1001
1002
1003 /*
1004 * strtoint64 -- convert a string to 64-bit integer
1005 *
1006 * This function is a slightly modified version of pg_strtoint64() from
1007 * src/backend/utils/adt/numutils.c.
1008 *
1009 * The function returns whether the conversion worked, and if so
1010 * "*result" is set to the result.
1011 *
1012 * If not errorOK, an error message is also printed out on errors.
1013 */
1014 bool
1015 strtoint64(const char *str, bool errorOK, int64 *result)
1016 {
1017 const char *ptr = str;
1018 int64 tmp = 0;
1019 bool neg = false;
1020
1021 /*
1022 * Do our own scan, rather than relying on sscanf which might be broken
1023 * for long long.
1024 *
1025 * As INT64_MIN can't be stored as a positive 64 bit integer, accumulate
1026 * value as a negative number.
1027 */
1028
1029 /* skip leading spaces */
1030 while (*ptr && isspace((unsigned char) *ptr))
1031 ptr++;
1032
1033 /* handle sign */
1034 if (*ptr == '-')
1035 {
1036 ptr++;
1037 neg = true;
1038 }
1039 else if (*ptr == '+')
1040 ptr++;
1041
1042 /* require at least one digit */
1043 if (unlikely(!isdigit((unsigned char) *ptr)))
1044 goto invalid_syntax;
1045
1046 /* process digits */
1047 while (*ptr && isdigit((unsigned char) *ptr))
1048 {
1049 int8 digit = (*ptr++ - '0');
1050
1051 if (unlikely(pg_mul_s64_overflow(tmp, 10, &tmp)) ||
1052 unlikely(pg_sub_s64_overflow(tmp, digit, &tmp)))
1053 goto out_of_range;
1054 }
1055
1056 /* allow trailing whitespace, but not other trailing chars */
1057 while (*ptr != '\0' && isspace((unsigned char) *ptr))
1058 ptr++;
1059
1060 if (unlikely(*ptr != '\0'))
1061 goto invalid_syntax;
1062
1063 if (!neg)
1064 {
1065 if (unlikely(tmp == PG_INT64_MIN))
1066 goto out_of_range;
1067 tmp = -tmp;
1068 }
1069
1070 *result = tmp;
1071 return true;
1072
1073 out_of_range:
1074 if (!errorOK)
1075 pg_log_error("value \"%s\" is out of range for type bigint", str);
1076 return false;
1077
1078 invalid_syntax:
1079 if (!errorOK)
1080 pg_log_error("invalid input syntax for type bigint: \"%s\"", str);
1081 return false;
1082 }
1083
1084 /* convert string to double, detecting overflows/underflows */
1085 bool
1086 strtodouble(const char *str, bool errorOK, double *dv)
1087 {
1088 char *end;
1089
1090 errno = 0;
1091 *dv = strtod(str, &end);
1092
1093 if (unlikely(errno != 0))
1094 {
1095 if (!errorOK)
1096 pg_log_error("value \"%s\" is out of range for type double", str);
1097 return false;
1098 }
1099
1100 if (unlikely(end == str || *end != '\0'))
1101 {
1102 if (!errorOK)
1103 pg_log_error("invalid input syntax for type double: \"%s\"", str);
1104 return false;
1105 }
1106 return true;
1107 }
1108
1109 /*
1110 * Initialize a prng state struct.
1111 *
1112 * We derive the seed from base_random_sequence, which must be set up already.
1113 */
1114 static void
1115 initRandomState(pg_prng_state *state)
1116 {
1117 pg_prng_seed(state, pg_prng_uint64(&base_random_sequence));
1118 }
1119
1120
1121 /*
1122 * random number generator: uniform distribution from min to max inclusive.
1123 *
1124 * Although the limits are expressed as int64, you can't generate the full
1125 * int64 range in one call, because the difference of the limits mustn't
1126 * overflow int64. This is not checked.
1127 */
1128 static int64
1129 getrand(pg_prng_state *state, int64 min, int64 max)
1130 {
1131 return min + (int64) pg_prng_uint64_range(state, 0, max - min);
1132 }
1133
1134 /*
1135 * random number generator: exponential distribution from min to max inclusive.
1136 * the parameter is so that the density of probability for the last cut-off max
1137 * value is exp(-parameter).
1138 */
1139 static int64
1140 getExponentialRand(pg_prng_state *state, int64 min, int64 max,
1141 double parameter)
1142 {
1143 double cut,
1144 uniform,
1145 rand;
1146
1147 /* abort if wrong parameter, but must really be checked beforehand */
1148 Assert(parameter > 0.0);
1149 cut = exp(-parameter);
1150 /* pg_prng_double value in [0, 1), uniform in (0, 1] */
1151 uniform = 1.0 - pg_prng_double(state);
1152
1153 /*
1154 * inner expression in (cut, 1] (if parameter > 0), rand in [0, 1)
1155 */
1156 Assert((1.0 - cut) != 0.0);
1157 rand = -log(cut + (1.0 - cut) * uniform) / parameter;
1158 /* return int64 random number within between min and max */
1159 return min + (int64) ((max - min + 1) * rand);
1160 }
1161
1162 /* random number generator: gaussian distribution from min to max inclusive */
1163 static int64
1164 getGaussianRand(pg_prng_state *state, int64 min, int64 max,
1165 double parameter)
1166 {
1167 double stdev;
1168 double rand;
1169
1170 /* abort if parameter is too low, but must really be checked beforehand */
1171 Assert(parameter >= MIN_GAUSSIAN_PARAM);
1172
1173 /*
1174 * Get normally-distributed random number in the range -parameter <= stdev
1175 * < parameter.
1176 *
1177 * This loop is executed until the number is in the expected range.
1178 *
1179 * As the minimum parameter is 2.0, the probability of looping is low:
1180 * sqrt(-2 ln(r)) <= 2 => r >= e^{-2} ~ 0.135, then when taking the
1181 * average sinus multiplier as 2/pi, we have a 8.6% looping probability in
1182 * the worst case. For a parameter value of 5.0, the looping probability
1183 * is about e^{-5} * 2 / pi ~ 0.43%.
1184 */
1185 do
1186 {
1187 stdev = pg_prng_double_normal(state);
1188 }
1189 while (stdev < -parameter || stdev >= parameter);
1190
1191 /* stdev is in [-parameter, parameter), normalization to [0,1) */
1192 rand = (stdev + parameter) / (parameter * 2.0);
1193
1194 /* return int64 random number within between min and max */
1195 return min + (int64) ((max - min + 1) * rand);
1196 }
1197
1198 /*
1199 * random number generator: generate a value, such that the series of values
1200 * will approximate a Poisson distribution centered on the given value.
1201 *
1202 * Individual results are rounded to integers, though the center value need
1203 * not be one.
1204 */
1205 static int64
1206 getPoissonRand(pg_prng_state *state, double center)
1207 {
1208 /*
1209 * Use inverse transform sampling to generate a value > 0, such that the
1210 * expected (i.e. average) value is the given argument.
1211 */
1212 double uniform;
1213
1214 /* pg_prng_double value in [0, 1), uniform in (0, 1] */
1215 uniform = 1.0 - pg_prng_double(state);
1216
1217 return (int64) (-log(uniform) * center + 0.5);
1218 }
1219
1220 /*
1221 * Computing zipfian using rejection method, based on
1222 * "Non-Uniform Random Variate Generation",
1223 * Luc Devroye, p. 550-551, Springer 1986.
1224 *
1225 * This works for s > 1.0, but may perform badly for s very close to 1.0.
1226 */
1227 static int64
1228 computeIterativeZipfian(pg_prng_state *state, int64 n, double s)
1229 {
1230 double b = pow(2.0, s - 1.0);
1231 double x,
1232 t,
1233 u,
1234 v;
1235
1236 /* Ensure n is sane */
1237 if (n <= 1)
1238 return 1;
1239
1240 while (true)
1241 {
1242 /* random variates */
1243 u = pg_prng_double(state);
1244 v = pg_prng_double(state);
1245
1246 x = floor(pow(u, -1.0 / (s - 1.0)));
1247
1248 t = pow(1.0 + 1.0 / x, s - 1.0);
1249 /* reject if too large or out of bound */
1250 if (v * x * (t - 1.0) / (b - 1.0) <= t / b && x <= n)
1251 break;
1252 }
1253 return (int64) x;
1254 }
1255
1256 /* random number generator: zipfian distribution from min to max inclusive */
1257 static int64
1258 getZipfianRand(pg_prng_state *state, int64 min, int64 max, double s)
1259 {
1260 int64 n = max - min + 1;
1261
1262 /* abort if parameter is invalid */
1263 Assert(MIN_ZIPFIAN_PARAM <= s && s <= MAX_ZIPFIAN_PARAM);
1264
1265 return min - 1 + computeIterativeZipfian(state, n, s);
1266 }
1267
1268 /*
1269 * FNV-1a hash function
1270 */
1271 static int64
1272 getHashFnv1a(int64 val, uint64 seed)
1273 {
1274 int64 result;
1275 int i;
1276
1277 result = FNV_OFFSET_BASIS ^ seed;
1278 for (i = 0; i < 8; ++i)
1279 {
1280 int32 octet = val & 0xff;
1281
1282 val = val >> 8;
1283 result = result ^ octet;
1284 result = result * FNV_PRIME;
1285 }
1286
1287 return result;
1288 }
1289
1290 /*
1291 * Murmur2 hash function
1292 *
1293 * Based on original work of Austin Appleby
1294 * https://github.com/aappleby/smhasher/blob/master/src/MurmurHash2.cpp
1295 */
1296 static int64
1297 getHashMurmur2(int64 val, uint64 seed)
1298 {
1299 uint64 result = seed ^ MM2_MUL_TIMES_8; /* sizeof(int64) */
1300 uint64 k = (uint64) val;
1301
1302 k *= MM2_MUL;
1303 k ^= k >> MM2_ROT;
1304 k *= MM2_MUL;
1305
1306 result ^= k;
1307 result *= MM2_MUL;
1308
1309 result ^= result >> MM2_ROT;
1310 result *= MM2_MUL;
1311 result ^= result >> MM2_ROT;
1312
1313 return (int64) result;
1314 }
1315
1316 /*
1317 * Pseudorandom permutation function
1318 *
1319 * For small sizes, this generates each of the (size!) possible permutations
1320 * of integers in the range [0, size) with roughly equal probability. Once
1321 * the size is larger than 20, the number of possible permutations exceeds the
1322 * number of distinct states of the internal pseudorandom number generator,
1323 * and so not all possible permutations can be generated, but the permutations
1324 * chosen should continue to give the appearance of being random.
1325 *
1326 * THIS FUNCTION IS NOT CRYPTOGRAPHICALLY SECURE.
1327 * DO NOT USE FOR SUCH PURPOSE.
1328 */
1329 static int64
1330 permute(const int64 val, const int64 isize, const int64 seed)
1331 {
1332 /* using a high-end PRNG is probably overkill */
1333 pg_prng_state state;
1334 uint64 size;
1335 uint64 v;
1336 int masklen;
1337 uint64 mask;
1338 int i;
1339
1340 if (isize < 2)
1341 return 0; /* nothing to permute */
1342
1343 /* Initialize prng state using the seed */
1344 pg_prng_seed(&state, (uint64) seed);
1345
1346 /* Computations are performed on unsigned values */
1347 size = (uint64) isize;
1348 v = (uint64) val % size;
1349
1350 /* Mask to work modulo largest power of 2 less than or equal to size */
1351 masklen = pg_leftmost_one_pos64(size);
1352 mask = (((uint64) 1) << masklen) - 1;
1353
1354 /*
1355 * Permute the input value by applying several rounds of pseudorandom
1356 * bijective transformations. The intention here is to distribute each
1357 * input uniformly randomly across the range, and separate adjacent inputs
1358 * approximately uniformly randomly from each other, leading to a fairly
1359 * random overall choice of permutation.
1360 *
1361 * To separate adjacent inputs, we multiply by a random number modulo
1362 * (mask + 1), which is a power of 2. For this to be a bijection, the
1363 * multiplier must be odd. Since this is known to lead to less randomness
1364 * in the lower bits, we also apply a rotation that shifts the topmost bit
1365 * into the least significant bit. In the special cases where size <= 3,
1366 * mask = 1 and each of these operations is actually a no-op, so we also
1367 * XOR the value with a different random number to inject additional
1368 * randomness. Since the size is generally not a power of 2, we apply
1369 * this bijection on overlapping upper and lower halves of the input.
1370 *
1371 * To distribute the inputs uniformly across the range, we then also apply
1372 * a random offset modulo the full range.
1373 *
1374 * Taken together, these operations resemble a modified linear
1375 * congruential generator, as is commonly used in pseudorandom number
1376 * generators. The number of rounds is fairly arbitrary, but six has been
1377 * found empirically to give a fairly good tradeoff between performance
1378 * and uniform randomness. For small sizes it selects each of the (size!)
1379 * possible permutations with roughly equal probability. For larger
1380 * sizes, not all permutations can be generated, but the intended random
1381 * spread is still produced.
1382 */
1383 for (i = 0; i < 6; i++)
1384 {
1385 uint64 m,
1386 r,
1387 t;
1388
1389 /* Random multiply (by an odd number), XOR and rotate of lower half */
1390 m = (pg_prng_uint64(&state) & mask) | 1;
1391 r = pg_prng_uint64(&state) & mask;
1392 if (v <= mask)
1393 {
1394 v = ((v * m) ^ r) & mask;
1395 v = ((v << 1) & mask) | (v >> (masklen - 1));
1396 }
1397
1398 /* Random multiply (by an odd number), XOR and rotate of upper half */
1399 m = (pg_prng_uint64(&state) & mask) | 1;
1400 r = pg_prng_uint64(&state) & mask;
1401 t = size - 1 - v;
1402 if (t <= mask)
1403 {
1404 t = ((t * m) ^ r) & mask;
1405 t = ((t << 1) & mask) | (t >> (masklen - 1));
1406 v = size - 1 - t;
1407 }
1408
1409 /* Random offset */
1410 r = pg_prng_uint64_range(&state, 0, size - 1);
1411 v = (v + r) % size;
1412 }
1413
1414 return (int64) v;
1415 }
1416
1417 /*
1418 * Initialize the given SimpleStats struct to all zeroes
1419 */
1420 static void
1421 initSimpleStats(SimpleStats *ss)
1422 {
1423 memset(ss, 0, sizeof(SimpleStats));
1424 }
1425
1426 /*
1427 * Accumulate one value into a SimpleStats struct.
1428 */
1429 static void
1430 addToSimpleStats(SimpleStats *ss, double val)
1431 {
1432 if (ss->count == 0 || val < ss->min)
1433 ss->min = val;
1434 if (ss->count == 0 || val > ss->max)
1435 ss->max = val;
1436 ss->count++;
1437 ss->sum += val;
1438 ss->sum2 += val * val;
1439 }
1440
1441 /*
1442 * Merge two SimpleStats objects
1443 */
1444 static void
1445 mergeSimpleStats(SimpleStats *acc, SimpleStats *ss)
1446 {
1447 if (acc->count == 0 || ss->min < acc->min)
1448 acc->min = ss->min;
1449 if (acc->count == 0 || ss->max > acc->max)
1450 acc->max = ss->max;
1451 acc->count += ss->count;
1452 acc->sum += ss->sum;
1453 acc->sum2 += ss->sum2;
1454 }
1455
1456 /*
1457 * Initialize a StatsData struct to mostly zeroes, with its start time set to
1458 * the given value.
1459 */
1460 static void
1461 initStats(StatsData *sd, pg_time_usec_t start)
1462 {
1463 sd->start_time = start;
1464 sd->cnt = 0;
1465 sd->skipped = 0;
1466 sd->retries = 0;
1467 sd->retried = 0;
1468 sd->serialization_failures = 0;
1469 sd->deadlock_failures = 0;
1470 initSimpleStats(&sd->latency);
1471 initSimpleStats(&sd->lag);
1472 }
1473
1474 /*
1475 * Accumulate one additional item into the given stats object.
1476 */
1477 static void
1478 accumStats(StatsData *stats, bool skipped, double lat, double lag,
1479 EStatus estatus, int64 tries)
1480 {
1481 /* Record the skipped transaction */
1482 if (skipped)
1483 {
1484 /* no latency to record on skipped transactions */
1485 stats->skipped++;
1486 return;
1487 }
1488
1489 /*
1490 * Record the number of retries regardless of whether the transaction was
1491 * successful or failed.
1492 */
1493 if (tries > 1)
1494 {
1495 stats->retries += (tries - 1);
1496 stats->retried++;
1497 }
1498
1499 switch (estatus)
1500 {
1501 /* Record the successful transaction */
1502 case ESTATUS_NO_ERROR:
1503 stats->cnt++;
1504
1505 addToSimpleStats(&stats->latency, lat);
1506
1507 /* and possibly the same for schedule lag */
1508 if (throttle_delay)
1509 addToSimpleStats(&stats->lag, lag);
1510 break;
1511
1512 /* Record the failed transaction */
1513 case ESTATUS_SERIALIZATION_ERROR:
1514 stats->serialization_failures++;
1515 break;
1516 case ESTATUS_DEADLOCK_ERROR:
1517 stats->deadlock_failures++;
1518 break;
1519 default:
1520 /* internal error which should never occur */
1521 pg_fatal("unexpected error status: %d", estatus);
1522 }
1523 }
1524
1525 /* call PQexec() and exit() on failure */
1526 static void
1527 executeStatement(PGconn *con, const char *sql)
1528 {
1529 PGresult *res;
1530
1531 res = PQexec(con, sql);
1532 if (PQresultStatus(res) != PGRES_COMMAND_OK)
1533 {
1534 pg_log_error("query failed: %s", PQerrorMessage(con));
1535 pg_log_error_detail("Query was: %s", sql);
1536 exit(1);
1537 }
1538 PQclear(res);
1539 }
1540
1541 /* call PQexec() and complain, but without exiting, on failure */
1542 static void
1543 tryExecuteStatement(PGconn *con, const char *sql)
1544 {
1545 PGresult *res;
1546
1547 res = PQexec(con, sql);
1548 if (PQresultStatus(res) != PGRES_COMMAND_OK)
1549 {
1550 pg_log_error("%s", PQerrorMessage(con));
1551 pg_log_error_detail("(ignoring this error and continuing anyway)");
1552 }
1553 PQclear(res);
1554 }
1555
1556 /* set up a connection to the backend */
1557 static PGconn *
1558 doConnect(void)
1559 {
1560 PGconn *conn;
1561 bool new_pass;
1562 static char *password = NULL;
1563
1564 /*
1565 * Start the connection. Loop until we have a password if requested by
1566 * backend.
1567 */
1568 do
1569 {
1570 #define PARAMS_ARRAY_SIZE 7
1571
1572 const char *keywords[PARAMS_ARRAY_SIZE];
1573 const char *values[PARAMS_ARRAY_SIZE];
1574
1575 keywords[0] = "host";
1576 values[0] = pghost;
1577 keywords[1] = "port";
1578 values[1] = pgport;
1579 keywords[2] = "user";
1580 values[2] = username;
1581 keywords[3] = "password";
1582 values[3] = password;
1583 keywords[4] = "dbname";
1584 values[4] = dbName;
1585 keywords[5] = "fallback_application_name";
1586 values[5] = progname;
1587 keywords[6] = NULL;
1588 values[6] = NULL;
1589
1590 new_pass = false;
1591
1592 conn = PQconnectdbParams(keywords, values, true);
1593
1594 if (!conn)
1595 {
1596 pg_log_error("connection to database \"%s\" failed", dbName);
1597 return NULL;
1598 }
1599
1600 if (PQstatus(conn) == CONNECTION_BAD &&
1601 PQconnectionNeedsPassword(conn) &&
1602 !password)
1603 {
1604 PQfinish(conn);
1605 password = simple_prompt("Password: ", false);
1606 new_pass = true;
1607 }
1608 } while (new_pass);
1609
1610 /* check to see that the backend connection was successfully made */
1611 if (PQstatus(conn) == CONNECTION_BAD)
1612 {
1613 pg_log_error("%s", PQerrorMessage(conn));
1614 PQfinish(conn);
1615 return NULL;
1616 }
1617
1618 return conn;
1619 }
1620
1621 /* qsort comparator for Variable array */
1622 static int
1623 compareVariableNames(const void *v1, const void *v2)
1624 {
1625 return strcmp(((const Variable *) v1)->name,
1626 ((const Variable *) v2)->name);
1627 }
1628
1629 /* Locate a variable by name; returns NULL if unknown */
1630 static Variable *
1631 lookupVariable(Variables *variables, char *name)
1632 {
1633 Variable key;
1634
1635 /* On some versions of Solaris, bsearch of zero items dumps core */
1636 if (variables->nvars <= 0)
1637 return NULL;
1638
1639 /* Sort if we have to */
1640 if (!variables->vars_sorted)
1641 {
1642 qsort(variables->vars, variables->nvars, sizeof(Variable),
1643 compareVariableNames);
1644 variables->vars_sorted = true;
1645 }
1646
1647 /* Now we can search */
1648 key.name = name;
1649 return (Variable *) bsearch(&key,
1650 variables->vars,
1651 variables->nvars,
1652 sizeof(Variable),
1653 compareVariableNames);
1654 }
1655
1656 /* Get the value of a variable, in string form; returns NULL if unknown */
1657 static char *
1658 getVariable(Variables *variables, char *name)
1659 {
1660 Variable *var;
1661 char stringform[64];
1662
1663 var = lookupVariable(variables, name);
1664 if (var == NULL)
1665 return NULL; /* not found */
1666
1667 if (var->svalue)
1668 return var->svalue; /* we have it in string form */
1669
1670 /* We need to produce a string equivalent of the value */
1671 Assert(var->value.type != PGBT_NO_VALUE);
1672 if (var->value.type == PGBT_NULL)
1673 snprintf(stringform, sizeof(stringform), "NULL");
1674 else if (var->value.type == PGBT_BOOLEAN)
1675 snprintf(stringform, sizeof(stringform),
1676 "%s", var->value.u.bval ? "true" : "false");
1677 else if (var->value.type == PGBT_INT)
1678 snprintf(stringform, sizeof(stringform),
1679 INT64_FORMAT, var->value.u.ival);
1680 else if (var->value.type == PGBT_DOUBLE)
1681 snprintf(stringform, sizeof(stringform),
1682 "%.*g", DBL_DIG, var->value.u.dval);
1683 else /* internal error, unexpected type */
1684 Assert(0);
1685 var->svalue = pg_strdup(stringform);
1686 return var->svalue;
1687 }
1688
1689 /* Try to convert variable to a value; return false on failure */
1690 static bool
1691 makeVariableValue(Variable *var)
1692 {
1693 size_t slen;
1694
1695 if (var->value.type != PGBT_NO_VALUE)
1696 return true; /* no work */
1697
1698 slen = strlen(var->svalue);
1699
1700 if (slen == 0)
1701 /* what should it do on ""? */
1702 return false;
1703
1704 if (pg_strcasecmp(var->svalue, "null") == 0)
1705 {
1706 setNullValue(&var->value);
1707 }
1708
1709 /*
1710 * accept prefixes such as y, ye, n, no... but not for "o". 0/1 are
1711 * recognized later as an int, which is converted to bool if needed.
1712 */
1713 else if (pg_strncasecmp(var->svalue, "true", slen) == 0 ||
1714 pg_strncasecmp(var->svalue, "yes", slen) == 0 ||
1715 pg_strcasecmp(var->svalue, "on") == 0)
1716 {
1717 setBoolValue(&var->value, true);
1718 }
1719 else if (pg_strncasecmp(var->svalue, "false", slen) == 0 ||
1720 pg_strncasecmp(var->svalue, "no", slen) == 0 ||
1721 pg_strcasecmp(var->svalue, "off") == 0 ||
1722 pg_strcasecmp(var->svalue, "of") == 0)
1723 {
1724 setBoolValue(&var->value, false);
1725 }
1726 else if (is_an_int(var->svalue))
1727 {
1728 /* if it looks like an int, it must be an int without overflow */
1729 int64 iv;
1730
1731 if (!strtoint64(var->svalue, false, &iv))
1732 return false;
1733
1734 setIntValue(&var->value, iv);
1735 }
1736 else /* type should be double */
1737 {
1738 double dv;
1739
1740 if (!strtodouble(var->svalue, true, &dv))
1741 {
1742 pg_log_error("malformed variable \"%s\" value: \"%s\"",
1743 var->name, var->svalue);
1744 return false;
1745 }
1746 setDoubleValue(&var->value, dv);
1747 }
1748 return true;
1749 }
1750
1751 /*
1752 * Check whether a variable's name is allowed.
1753 *
1754 * We allow any non-ASCII character, as well as ASCII letters, digits, and
1755 * underscore.
1756 *
1757 * Keep this in sync with the definitions of variable name characters in
1758 * "src/fe_utils/psqlscan.l", "src/bin/psql/psqlscanslash.l" and
1759 * "src/bin/pgbench/exprscan.l". Also see parseVariable(), below.
1760 *
1761 * Note: this static function is copied from "src/bin/psql/variables.c"
1762 * but changed to disallow variable names starting with a digit.
1763 */
1764 static bool
1765 valid_variable_name(const char *name)
1766 {
1767 const unsigned char *ptr = (const unsigned char *) name;
1768
1769 /* Mustn't be zero-length */
1770 if (*ptr == '\0')
1771 return false;
1772
1773 /* must not start with [0-9] */
1774 if (IS_HIGHBIT_SET(*ptr) ||
1775 strchr("ABCDEFGHIJKLMNOPQRSTUVWXYZ" "abcdefghijklmnopqrstuvwxyz"
1776 "_", *ptr) != NULL)
1777 ptr++;
1778 else
1779 return false;
1780
1781 /* remaining characters can include [0-9] */
1782 while (*ptr)
1783 {
1784 if (IS_HIGHBIT_SET(*ptr) ||
1785 strchr("ABCDEFGHIJKLMNOPQRSTUVWXYZ" "abcdefghijklmnopqrstuvwxyz"
1786 "_0123456789", *ptr) != NULL)
1787 ptr++;
1788 else
1789 return false;
1790 }
1791
1792 return true;
1793 }
1794
1795 /*
1796 * Make sure there is enough space for 'needed' more variable in the variables
1797 * array.
1798 */
1799 static void
1800 enlargeVariables(Variables *variables, int needed)
1801 {
1802 /* total number of variables required now */
1803 needed += variables->nvars;
1804
1805 if (variables->max_vars < needed)
1806 {
1807 variables->max_vars = needed + VARIABLES_ALLOC_MARGIN;
1808 variables->vars = (Variable *)
1809 pg_realloc(variables->vars, variables->max_vars * sizeof(Variable));
1810 }
1811 }
1812
1813 /*
1814 * Lookup a variable by name, creating it if need be.
1815 * Caller is expected to assign a value to the variable.
1816 * Returns NULL on failure (bad name).
1817 */
1818 static Variable *
1819 lookupCreateVariable(Variables *variables, const char *context, char *name)
1820 {
1821 Variable *var;
1822
1823 var = lookupVariable(variables, name);
1824 if (var == NULL)
1825 {
1826 /*
1827 * Check for the name only when declaring a new variable to avoid
1828 * overhead.
1829 */
1830 if (!valid_variable_name(name))
1831 {
1832 pg_log_error("%s: invalid variable name: \"%s\"", context, name);
1833 return NULL;
1834 }
1835
1836 /* Create variable at the end of the array */
1837 enlargeVariables(variables, 1);
1838
1839 var = &(variables->vars[variables->nvars]);
1840
1841 var->name = pg_strdup(name);
1842 var->svalue = NULL;
1843 /* caller is expected to initialize remaining fields */
1844
1845 variables->nvars++;
1846 /* we don't re-sort the array till we have to */
1847 variables->vars_sorted = false;
1848 }
1849
1850 return var;
1851 }
1852
1853 /* Assign a string value to a variable, creating it if need be */
1854 /* Returns false on failure (bad name) */
1855 static bool
1856 putVariable(Variables *variables, const char *context, char *name,
1857 const char *value)
1858 {
1859 Variable *var;
1860 char *val;
1861
1862 var = lookupCreateVariable(variables, context, name);
1863 if (!var)
1864 return false;
1865
1866 /* dup then free, in case value is pointing at this variable */
1867 val = pg_strdup(value);
1868
1869 free(var->svalue);
1870 var->svalue = val;
1871 var->value.type = PGBT_NO_VALUE;
1872
1873 return true;
1874 }
1875
1876 /* Assign a value to a variable, creating it if need be */
1877 /* Returns false on failure (bad name) */
1878 static bool
1879 putVariableValue(Variables *variables, const char *context, char *name,
1880 const PgBenchValue *value)
1881 {
1882 Variable *var;
1883
1884 var = lookupCreateVariable(variables, context, name);
1885 if (!var)
1886 return false;
1887
1888 free(var->svalue);
1889 var->svalue = NULL;
1890 var->value = *value;
1891
1892 return true;
1893 }
1894
1895 /* Assign an integer value to a variable, creating it if need be */
1896 /* Returns false on failure (bad name) */
1897 static bool
1898 putVariableInt(Variables *variables, const char *context, char *name,
1899 int64 value)
1900 {
1901 PgBenchValue val;
1902
1903 setIntValue(&val, value);
1904 return putVariableValue(variables, context, name, &val);
1905 }
1906
1907 /*
1908 * Parse a possible variable reference (:varname).
1909 *
1910 * "sql" points at a colon. If what follows it looks like a valid
1911 * variable name, return a malloc'd string containing the variable name,
1912 * and set *eaten to the number of characters consumed (including the colon).
1913 * Otherwise, return NULL.
1914 */
1915 static char *
1916 parseVariable(const char *sql, int *eaten)
1917 {
1918 int i = 1; /* starting at 1 skips the colon */
1919 char *name;
1920
1921 /* keep this logic in sync with valid_variable_name() */
1922 if (IS_HIGHBIT_SET(sql[i]) ||
1923 strchr("ABCDEFGHIJKLMNOPQRSTUVWXYZ" "abcdefghijklmnopqrstuvwxyz"
1924 "_", sql[i]) != NULL)
1925 i++;
1926 else
1927 return NULL;
1928
1929 while (IS_HIGHBIT_SET(sql[i]) ||
1930 strchr("ABCDEFGHIJKLMNOPQRSTUVWXYZ" "abcdefghijklmnopqrstuvwxyz"
1931 "_0123456789", sql[i]) != NULL)
1932 i++;
1933
1934 name = pg_malloc(i);
1935 memcpy(name, &sql[1], i - 1);
1936 name[i - 1] = '\0';
1937
1938 *eaten = i;
1939 return name;
1940 }
1941
1942 static char *
1943 replaceVariable(char **sql, char *param, int len, char *value)
1944 {
1945 int valueln = strlen(value);
1946
1947 if (valueln > len)
1948 {
1949 size_t offset = param - *sql;
1950
1951 *sql = pg_realloc(*sql, strlen(*sql) - len + valueln + 1);
1952 param = *sql + offset;
1953 }
1954
1955 if (valueln != len)
1956 memmove(param + valueln, param + len, strlen(param + len) + 1);
1957 memcpy(param, value, valueln);
1958
1959 return param + valueln;
1960 }
1961
1962 static char *
1963 assignVariables(Variables *variables, char *sql)
1964 {
1965 char *p,
1966 *name,
1967 *val;
1968
1969 p = sql;
1970 while ((p = strchr(p, ':')) != NULL)
1971 {
1972 int eaten;
1973
1974 name = parseVariable(p, &eaten);
1975 if (name == NULL)
1976 {
1977 while (*p == ':')
1978 {
1979 p++;
1980 }
1981 continue;
1982 }
1983
1984 val = getVariable(variables, name);
1985 free(name);
1986 if (val == NULL)
1987 {
1988 p++;
1989 continue;
1990 }
1991
1992 p = replaceVariable(&sql, p, eaten, val);
1993 }
1994
1995 return sql;
1996 }
1997
1998 static void
1999 getQueryParams(Variables *variables, const Command *command,
2000 const char **params)
2001 {
2002 int i;
2003
2004 for (i = 0; i < command->argc - 1; i++)
2005 params[i] = getVariable(variables, command->argv[i + 1]);
2006 }
2007
2008 static char *
2009 valueTypeName(PgBenchValue *pval)
2010 {
2011 if (pval->type == PGBT_NO_VALUE)
2012 return "none";
2013 else if (pval->type == PGBT_NULL)
2014 return "null";
2015 else if (pval->type == PGBT_INT)
2016 return "int";
2017 else if (pval->type == PGBT_DOUBLE)
2018 return "double";
2019 else if (pval->type == PGBT_BOOLEAN)
2020 return "boolean";
2021 else
2022 {
2023 /* internal error, should never get there */
2024 Assert(false);
2025 return NULL;
2026 }
2027 }
2028
2029 /* get a value as a boolean, or tell if there is a problem */
2030 static bool
2031 coerceToBool(PgBenchValue *pval, bool *bval)
2032 {
2033 if (pval->type == PGBT_BOOLEAN)
2034 {
2035 *bval = pval->u.bval;
2036 return true;
2037 }
2038 else /* NULL, INT or DOUBLE */
2039 {
2040 pg_log_error("cannot coerce %s to boolean", valueTypeName(pval));
2041 *bval = false; /* suppress uninitialized-variable warnings */
2042 return false;
2043 }
2044 }
2045
2046 /*
2047 * Return true or false from an expression for conditional purposes.
2048 * Non zero numerical values are true, zero and NULL are false.
2049 */
2050 static bool
2051 valueTruth(PgBenchValue *pval)
2052 {
2053 switch (pval->type)
2054 {
2055 case PGBT_NULL:
2056 return false;
2057 case PGBT_BOOLEAN:
2058 return pval->u.bval;
2059 case PGBT_INT:
2060 return pval->u.ival != 0;
2061 case PGBT_DOUBLE:
2062 return pval->u.dval != 0.0;
2063 default:
2064 /* internal error, unexpected type */
2065 Assert(0);
2066 return false;
2067 }
2068 }
2069
2070 /* get a value as an int, tell if there is a problem */
2071 static bool
2072 coerceToInt(PgBenchValue *pval, int64 *ival)
2073 {
2074 if (pval->type == PGBT_INT)
2075 {
2076 *ival = pval->u.ival;
2077 return true;
2078 }
2079 else if (pval->type == PGBT_DOUBLE)
2080 {
2081 double dval = rint(pval->u.dval);
2082
2083 if (isnan(dval) || !FLOAT8_FITS_IN_INT64(dval))
2084 {
2085 pg_log_error("double to int overflow for %f", dval);
2086 return false;
2087 }
2088 *ival = (int64) dval;
2089 return true;
2090 }
2091 else /* BOOLEAN or NULL */
2092 {
2093 pg_log_error("cannot coerce %s to int", valueTypeName(pval));
2094 return false;
2095 }
2096 }
2097
2098 /* get a value as a double, or tell if there is a problem */
2099 static bool
2100 coerceToDouble(PgBenchValue *pval, double *dval)
2101 {
2102 if (pval->type == PGBT_DOUBLE)
2103 {
2104 *dval = pval->u.dval;
2105 return true;
2106 }
2107 else if (pval->type == PGBT_INT)
2108 {
2109 *dval = (double) pval->u.ival;
2110 return true;
2111 }
2112 else /* BOOLEAN or NULL */
2113 {
2114 pg_log_error("cannot coerce %s to double", valueTypeName(pval));
2115 return false;
2116 }
2117 }
2118
2119 /* assign a null value */
2120 static void
2121 setNullValue(PgBenchValue *pv)
2122 {
2123 pv->type = PGBT_NULL;
2124 pv->u.ival = 0;
2125 }
2126
2127 /* assign a boolean value */
2128 static void
2129 setBoolValue(PgBenchValue *pv, bool bval)
2130 {
2131 pv->type = PGBT_BOOLEAN;
2132 pv->u.bval = bval;
2133 }
2134
2135 /* assign an integer value */
2136 static void
2137 setIntValue(PgBenchValue *pv, int64 ival)
2138 {
2139 pv->type = PGBT_INT;
2140 pv->u.ival = ival;
2141 }
2142
2143 /* assign a double value */
2144 static void
2145 setDoubleValue(PgBenchValue *pv, double dval)
2146 {
2147 pv->type = PGBT_DOUBLE;
2148 pv->u.dval = dval;
2149 }
2150
2151 static bool
2152 isLazyFunc(PgBenchFunction func)
2153 {
2154 return func == PGBENCH_AND || func == PGBENCH_OR || func == PGBENCH_CASE;
2155 }
2156
2157 /* lazy evaluation of some functions */
2158 static bool
2159 evalLazyFunc(CState *st,
2160 PgBenchFunction func, PgBenchExprLink *args, PgBenchValue *retval)
2161 {
2162 PgBenchValue a1,
2163 a2;
2164 bool ba1,
2165 ba2;
2166
2167 Assert(isLazyFunc(func) && args != NULL && args->next != NULL);
2168
2169 /* args points to first condition */
2170 if (!evaluateExpr(st, args->expr, &a1))
2171 return false;
2172
2173 /* second condition for AND/OR and corresponding branch for CASE */
2174 args = args->next;
2175
2176 switch (func)
2177 {
2178 case PGBENCH_AND:
2179 if (a1.type == PGBT_NULL)
2180 {
2181 setNullValue(retval);
2182 return true;
2183 }
2184
2185 if (!coerceToBool(&a1, &ba1))
2186 return false;
2187
2188 if (!ba1)
2189 {
2190 setBoolValue(retval, false);
2191 return true;
2192 }
2193
2194 if (!evaluateExpr(st, args->expr, &a2))
2195 return false;
2196
2197 if (a2.type == PGBT_NULL)
2198 {
2199 setNullValue(retval);
2200 return true;
2201 }
2202 else if (!coerceToBool(&a2, &ba2))
2203 return false;
2204 else
2205 {
2206 setBoolValue(retval, ba2);
2207 return true;
2208 }
2209
2210 return true;
2211
2212 case PGBENCH_OR:
2213
2214 if (a1.type == PGBT_NULL)
2215 {
2216 setNullValue(retval);
2217 return true;
2218 }
2219
2220 if (!coerceToBool(&a1, &ba1))
2221 return false;
2222
2223 if (ba1)
2224 {
2225 setBoolValue(retval, true);
2226 return true;
2227 }
2228
2229 if (!evaluateExpr(st, args->expr, &a2))
2230 return false;
2231
2232 if (a2.type == PGBT_NULL)
2233 {
2234 setNullValue(retval);
2235 return true;
2236 }
2237 else if (!coerceToBool(&a2, &ba2))
2238 return false;
2239 else
2240 {
2241 setBoolValue(retval, ba2);
2242 return true;
2243 }
2244
2245 case PGBENCH_CASE:
2246 /* when true, execute branch */
2247 if (valueTruth(&a1))
2248 return evaluateExpr(st, args->expr, retval);
2249
2250 /* now args contains next condition or final else expression */
2251 args = args->next;
2252
2253 /* final else case? */
2254 if (args->next == NULL)
2255 return evaluateExpr(st, args->expr, retval);
2256
2257 /* no, another when, proceed */
2258 return evalLazyFunc(st, PGBENCH_CASE, args, retval);
2259
2260 default:
2261 /* internal error, cannot get here */
2262 Assert(0);
2263 break;
2264 }
2265 return false;
2266 }
2267
2268 /* maximum number of function arguments */
2269 #define MAX_FARGS 16
2270
2271 /*
2272 * Recursive evaluation of standard functions,
2273 * which do not require lazy evaluation.
2274 */
2275 static bool
2276 evalStandardFunc(CState *st,
2277 PgBenchFunction func, PgBenchExprLink *args,
2278 PgBenchValue *retval)
2279 {
2280 /* evaluate all function arguments */
2281 int nargs = 0;
2282 PgBenchValue vargs[MAX_FARGS] = {0};
2283 PgBenchExprLink *l = args;
2284 bool has_null = false;
2285
2286 for (nargs = 0; nargs < MAX_FARGS && l != NULL; nargs++, l = l->next)
2287 {
2288 if (!evaluateExpr(st, l->expr, &vargs[nargs]))
2289 return false;
2290 has_null |= vargs[nargs].type == PGBT_NULL;
2291 }
2292
2293 if (l != NULL)
2294 {
2295 pg_log_error("too many function arguments, maximum is %d", MAX_FARGS);
2296 return false;
2297 }
2298
2299 /* NULL arguments */
2300 if (has_null && func != PGBENCH_IS && func != PGBENCH_DEBUG)
2301 {
2302 setNullValue(retval);
2303 return true;
2304 }
2305
2306 /* then evaluate function */
2307 switch (func)
2308 {
2309 /* overloaded operators */
2310 case PGBENCH_ADD:
2311 case PGBENCH_SUB:
2312 case PGBENCH_MUL:
2313 case PGBENCH_DIV:
2314 case PGBENCH_MOD:
2315 case PGBENCH_EQ:
2316 case PGBENCH_NE:
2317 case PGBENCH_LE:
2318 case PGBENCH_LT:
2319 {
2320 PgBenchValue *lval = &vargs[0],
2321 *rval = &vargs[1];
2322
2323 Assert(nargs == 2);
2324
2325 /* overloaded type management, double if some double */
2326 if ((lval->type == PGBT_DOUBLE ||
2327 rval->type == PGBT_DOUBLE) && func != PGBENCH_MOD)
2328 {
2329 double ld,
2330 rd;
2331
2332 if (!coerceToDouble(lval, &ld) ||
2333 !coerceToDouble(rval, &rd))
2334 return false;
2335
2336 switch (func)
2337 {
2338 case PGBENCH_ADD:
2339 setDoubleValue(retval, ld + rd);
2340 return true;
2341
2342 case PGBENCH_SUB:
2343 setDoubleValue(retval, ld - rd);
2344 return true;
2345
2346 case PGBENCH_MUL:
2347 setDoubleValue(retval, ld * rd);
2348 return true;
2349
2350 case PGBENCH_DIV:
2351 setDoubleValue(retval, ld / rd);
2352 return true;
2353
2354 case PGBENCH_EQ:
2355 setBoolValue(retval, ld == rd);
2356 return true;
2357
2358 case PGBENCH_NE:
2359 setBoolValue(retval, ld != rd);
2360 return true;
2361
2362 case PGBENCH_LE:
2363 setBoolValue(retval, ld <= rd);
2364 return true;
2365
2366 case PGBENCH_LT:
2367 setBoolValue(retval, ld < rd);
2368 return true;
2369
2370 default:
2371 /* cannot get here */
2372 Assert(0);
2373 }
2374 }
2375 else /* we have integer operands, or % */
2376 {
2377 int64 li,
2378 ri,
2379 res;
2380
2381 if (!coerceToInt(lval, &li) ||
2382 !coerceToInt(rval, &ri))
2383 return false;
2384
2385 switch (func)
2386 {
2387 case PGBENCH_ADD:
2388 if (pg_add_s64_overflow(li, ri, &res))
2389 {
2390 pg_log_error("bigint add out of range");
2391 return false;
2392 }
2393 setIntValue(retval, res);
2394 return true;
2395
2396 case PGBENCH_SUB:
2397 if (pg_sub_s64_overflow(li, ri, &res))
2398 {
2399 pg_log_error("bigint sub out of range");
2400 return false;
2401 }
2402 setIntValue(retval, res);
2403 return true;
2404
2405 case PGBENCH_MUL:
2406 if (pg_mul_s64_overflow(li, ri, &res))
2407 {
2408 pg_log_error("bigint mul out of range");
2409 return false;
2410 }
2411 setIntValue(retval, res);
2412 return true;
2413
2414 case PGBENCH_EQ:
2415 setBoolValue(retval, li == ri);
2416 return true;
2417
2418 case PGBENCH_NE:
2419 setBoolValue(retval, li != ri);
2420 return true;
2421
2422 case PGBENCH_LE:
2423 setBoolValue(retval, li <= ri);
2424 return true;
2425
2426 case PGBENCH_LT:
2427 setBoolValue(retval, li < ri);
2428 return true;
2429
2430 case PGBENCH_DIV:
2431 case PGBENCH_MOD:
2432 if (ri == 0)
2433 {
2434 pg_log_error("division by zero");
2435 return false;
2436 }
2437 /* special handling of -1 divisor */
2438 if (ri == -1)
2439 {
2440 if (func == PGBENCH_DIV)
2441 {
2442 /* overflow check (needed for INT64_MIN) */
2443 if (li == PG_INT64_MIN)
2444 {
2445 pg_log_error("bigint div out of range");
2446 return false;
2447 }
2448 else
2449 setIntValue(retval, -li);
2450 }
2451 else
2452 setIntValue(retval, 0);
2453 return true;
2454 }
2455 /* else divisor is not -1 */
2456 if (func == PGBENCH_DIV)
2457 setIntValue(retval, li / ri);
2458 else /* func == PGBENCH_MOD */
2459 setIntValue(retval, li % ri);
2460
2461 return true;
2462
2463 default:
2464 /* cannot get here */
2465 Assert(0);
2466 }
2467 }
2468
2469 Assert(0);
2470 return false; /* NOTREACHED */
2471 }
2472
2473 /* integer bitwise operators */
2474 case PGBENCH_BITAND:
2475 case PGBENCH_BITOR:
2476 case PGBENCH_BITXOR:
2477 case PGBENCH_LSHIFT:
2478 case PGBENCH_RSHIFT:
2479 {
2480 int64 li,
2481 ri;
2482
2483 if (!coerceToInt(&vargs[0], &li) || !coerceToInt(&vargs[1], &ri))
2484 return false;
2485
2486 if (func == PGBENCH_BITAND)
2487 setIntValue(retval, li & ri);
2488 else if (func == PGBENCH_BITOR)
2489 setIntValue(retval, li | ri);
2490 else if (func == PGBENCH_BITXOR)
2491 setIntValue(retval, li ^ ri);
2492 else if (func == PGBENCH_LSHIFT)
2493 setIntValue(retval, li << ri);
2494 else if (func == PGBENCH_RSHIFT)
2495 setIntValue(retval, li >> ri);
2496 else /* cannot get here */
2497 Assert(0);
2498
2499 return true;
2500 }
2501
2502 /* logical operators */
2503 case PGBENCH_NOT:
2504 {
2505 bool b;
2506
2507 if (!coerceToBool(&vargs[0], &b))
2508 return false;
2509
2510 setBoolValue(retval, !b);
2511 return true;
2512 }
2513
2514 /* no arguments */
2515 case PGBENCH_PI:
2516 setDoubleValue(retval, M_PI);
2517 return true;
2518
2519 /* 1 overloaded argument */
2520 case PGBENCH_ABS:
2521 {
2522 PgBenchValue *varg = &vargs[0];
2523
2524 Assert(nargs == 1);
2525
2526 if (varg->type == PGBT_INT)
2527 {
2528 int64 i = varg->u.ival;
2529
2530 setIntValue(retval, i < 0 ? -i : i);
2531 }
2532 else
2533 {
2534 double d = varg->u.dval;
2535
2536 Assert(varg->type == PGBT_DOUBLE);
2537 setDoubleValue(retval, d < 0.0 ? -d : d);
2538 }
2539
2540 return true;
2541 }
2542
2543 case PGBENCH_DEBUG:
2544 {
2545 PgBenchValue *varg = &vargs[0];
2546
2547 Assert(nargs == 1);
2548
2549 fprintf(stderr, "debug(script=%d,command=%d): ",
2550 st->use_file, st->command + 1);
2551
2552 if (varg->type == PGBT_NULL)
2553 fprintf(stderr, "null\n");
2554 else if (varg->type == PGBT_BOOLEAN)
2555 fprintf(stderr, "boolean %s\n", varg->u.bval ? "true" : "false");
2556 else if (varg->type == PGBT_INT)
2557 fprintf(stderr, "int " INT64_FORMAT "\n", varg->u.ival);
2558 else if (varg->type == PGBT_DOUBLE)
2559 fprintf(stderr, "double %.*g\n", DBL_DIG, varg->u.dval);
2560 else /* internal error, unexpected type */
2561 Assert(0);
2562
2563 *retval = *varg;
2564
2565 return true;
2566 }
2567
2568 /* 1 double argument */
2569 case PGBENCH_DOUBLE:
2570 case PGBENCH_SQRT:
2571 case PGBENCH_LN:
2572 case PGBENCH_EXP:
2573 {
2574 double dval;
2575
2576 Assert(nargs == 1);
2577
2578 if (!coerceToDouble(&vargs[0], &dval))
2579 return false;
2580
2581 if (func == PGBENCH_SQRT)
2582 dval = sqrt(dval);
2583 else if (func == PGBENCH_LN)
2584 dval = log(dval);
2585 else if (func == PGBENCH_EXP)
2586 dval = exp(dval);
2587 /* else is cast: do nothing */
2588
2589 setDoubleValue(retval, dval);
2590 return true;
2591 }
2592
2593 /* 1 int argument */
2594 case PGBENCH_INT:
2595 {
2596 int64 ival;
2597
2598 Assert(nargs == 1);
2599
2600 if (!coerceToInt(&vargs[0], &ival))
2601 return false;
2602
2603 setIntValue(retval, ival);
2604 return true;
2605 }
2606
2607 /* variable number of arguments */
2608 case PGBENCH_LEAST:
2609 case PGBENCH_GREATEST:
2610 {
2611 bool havedouble;
2612 int i;
2613
2614 Assert(nargs >= 1);
2615
2616 /* need double result if any input is double */
2617 havedouble = false;
2618 for (i = 0; i < nargs; i++)
2619 {
2620 if (vargs[i].type == PGBT_DOUBLE)
2621 {
2622 havedouble = true;
2623 break;
2624 }
2625 }
2626 if (havedouble)
2627 {
2628 double extremum;
2629
2630 if (!coerceToDouble(&vargs[0], &extremum))
2631 return false;
2632 for (i = 1; i < nargs; i++)
2633 {
2634 double dval;
2635
2636 if (!coerceToDouble(&vargs[i], &dval))
2637 return false;
2638 if (func == PGBENCH_LEAST)
2639 extremum = Min(extremum, dval);
2640 else
2641 extremum = Max(extremum, dval);
2642 }
2643 setDoubleValue(retval, extremum);
2644 }
2645 else
2646 {
2647 int64 extremum;
2648
2649 if (!coerceToInt(&vargs[0], &extremum))
2650 return false;
2651 for (i = 1; i < nargs; i++)
2652 {
2653 int64 ival;
2654
2655 if (!coerceToInt(&vargs[i], &ival))
2656 return false;
2657 if (func == PGBENCH_LEAST)
2658 extremum = Min(extremum, ival);
2659 else
2660 extremum = Max(extremum, ival);
2661 }
2662 setIntValue(retval, extremum);
2663 }
2664 return true;
2665 }
2666
2667 /* random functions */
2668 case PGBENCH_RANDOM:
2669 case PGBENCH_RANDOM_EXPONENTIAL:
2670 case PGBENCH_RANDOM_GAUSSIAN:
2671 case PGBENCH_RANDOM_ZIPFIAN:
2672 {
2673 int64 imin,
2674 imax,
2675 delta;
2676
2677 Assert(nargs >= 2);
2678
2679 if (!coerceToInt(&vargs[0], &imin) ||
2680 !coerceToInt(&vargs[1], &imax))
2681 return false;
2682
2683 /* check random range */
2684 if (unlikely(imin > imax))
2685 {
2686 pg_log_error("empty range given to random");
2687 return false;
2688 }
2689 else if (unlikely(pg_sub_s64_overflow(imax, imin, &delta) ||
2690 pg_add_s64_overflow(delta, 1, &delta)))
2691 {
2692 /* prevent int overflows in random functions */
2693 pg_log_error("random range is too large");
2694 return false;
2695 }
2696
2697 if (func == PGBENCH_RANDOM)
2698 {
2699 Assert(nargs == 2);
2700 setIntValue(retval, getrand(&st->cs_func_rs, imin, imax));
2701 }
2702 else /* gaussian & exponential */
2703 {
2704 double param;
2705
2706 Assert(nargs == 3);
2707
2708 if (!coerceToDouble(&vargs[2], &param))
2709 return false;
2710
2711 if (func == PGBENCH_RANDOM_GAUSSIAN)
2712 {
2713 if (param < MIN_GAUSSIAN_PARAM)
2714 {
2715 pg_log_error("gaussian parameter must be at least %f (not %f)",
2716 MIN_GAUSSIAN_PARAM, param);
2717 return false;
2718 }
2719
2720 setIntValue(retval,
2721 getGaussianRand(&st->cs_func_rs,
2722 imin, imax, param));
2723 }
2724 else if (func == PGBENCH_RANDOM_ZIPFIAN)
2725 {
2726 if (param < MIN_ZIPFIAN_PARAM || param > MAX_ZIPFIAN_PARAM)
2727 {
2728 pg_log_error("zipfian parameter must be in range [%.3f, %.0f] (not %f)",
2729 MIN_ZIPFIAN_PARAM, MAX_ZIPFIAN_PARAM, param);
2730 return false;
2731 }
2732
2733 setIntValue(retval,
2734 getZipfianRand(&st->cs_func_rs, imin, imax, param));
2735 }
2736 else /* exponential */
2737 {
2738 if (param <= 0.0)
2739 {
2740 pg_log_error("exponential parameter must be greater than zero (not %f)",
2741 param);
2742 return false;
2743 }
2744
2745 setIntValue(retval,
2746 getExponentialRand(&st->cs_func_rs,
2747 imin, imax, param));
2748 }
2749 }
2750
2751 return true;
2752 }
2753
2754 case PGBENCH_POW:
2755 {
2756 PgBenchValue *lval = &vargs[0];
2757 PgBenchValue *rval = &vargs[1];
2758 double ld,
2759 rd;
2760
2761 Assert(nargs == 2);
2762
2763 if (!coerceToDouble(lval, &ld) ||
2764 !coerceToDouble(rval, &rd))
2765 return false;
2766
2767 setDoubleValue(retval, pow(ld, rd));
2768
2769 return true;
2770 }
2771
2772 case PGBENCH_IS:
2773 {
2774 Assert(nargs == 2);
2775
2776 /*
2777 * note: this simple implementation is more permissive than
2778 * SQL
2779 */
2780 setBoolValue(retval,
2781 vargs[0].type == vargs[1].type &&
2782 vargs[0].u.bval == vargs[1].u.bval);
2783 return true;
2784 }
2785
2786 /* hashing */
2787 case PGBENCH_HASH_FNV1A:
2788 case PGBENCH_HASH_MURMUR2:
2789 {
2790 int64 val,
2791 seed;
2792
2793 Assert(nargs == 2);
2794
2795 if (!coerceToInt(&vargs[0], &val) ||
2796 !coerceToInt(&vargs[1], &seed))
2797 return false;
2798
2799 if (func == PGBENCH_HASH_MURMUR2)
2800 setIntValue(retval, getHashMurmur2(val, seed));
2801 else if (func == PGBENCH_HASH_FNV1A)
2802 setIntValue(retval, getHashFnv1a(val, seed));
2803 else
2804 /* cannot get here */
2805 Assert(0);
2806
2807 return true;
2808 }
2809
2810 case PGBENCH_PERMUTE:
2811 {
2812 int64 val,
2813 size,
2814 seed;
2815
2816 Assert(nargs == 3);
2817
2818 if (!coerceToInt(&vargs[0], &val) ||
2819 !coerceToInt(&vargs[1], &size) ||
2820 !coerceToInt(&vargs[2], &seed))
2821 return false;
2822
2823 if (size <= 0)
2824 {
2825 pg_log_error("permute size parameter must be greater than zero");
2826 return false;
2827 }
2828
2829 setIntValue(retval, permute(val, size, seed));
2830 return true;
2831 }
2832
2833 default:
2834 /* cannot get here */
2835 Assert(0);
2836 /* dead code to avoid a compiler warning */
2837 return false;
2838 }
2839 }
2840
2841 /* evaluate some function */
2842 static bool
2843 evalFunc(CState *st,
2844 PgBenchFunction func, PgBenchExprLink *args, PgBenchValue *retval)
2845 {
2846 if (isLazyFunc(func))
2847 return evalLazyFunc(st, func, args, retval);
2848 else
2849 return evalStandardFunc(st, func, args, retval);
2850 }
2851
2852 /*
2853 * Recursive evaluation of an expression in a pgbench script
2854 * using the current state of variables.
2855 * Returns whether the evaluation was ok,
2856 * the value itself is returned through the retval pointer.
2857 */
2858 static bool
2859 evaluateExpr(CState *st, PgBenchExpr *expr, PgBenchValue *retval)
2860 {
2861 switch (expr->etype)
2862 {
2863 case ENODE_CONSTANT:
2864 {
2865 *retval = expr->u.constant;
2866 return true;
2867 }
2868
2869 case ENODE_VARIABLE:
2870 {
2871 Variable *var;
2872
2873 if ((var = lookupVariable(&st->variables, expr->u.variable.varname)) == NULL)
2874 {
2875 pg_log_error("undefined variable \"%s\"", expr->u.variable.varname);
2876 return false;
2877 }
2878
2879 if (!makeVariableValue(var))
2880 return false;
2881
2882 *retval = var->value;
2883 return true;
2884 }
2885
2886 case ENODE_FUNCTION:
2887 return evalFunc(st,
2888 expr->u.function.function,
2889 expr->u.function.args,
2890 retval);
2891
2892 default:
2893 /* internal error which should never occur */
2894 pg_fatal("unexpected enode type in evaluation: %d", expr->etype);
2895 }
2896 }
2897
2898 /*
2899 * Convert command name to meta-command enum identifier
2900 */
2901 static MetaCommand
2902 getMetaCommand(const char *cmd)
2903 {
2904 MetaCommand mc;
2905
2906 if (cmd == NULL)
2907 mc = META_NONE;
2908 else if (pg_strcasecmp(cmd, "set") == 0)
2909 mc = META_SET;
2910 else if (pg_strcasecmp(cmd, "setshell") == 0)
2911 mc = META_SETSHELL;
2912 else if (pg_strcasecmp(cmd, "shell") == 0)
2913 mc = META_SHELL;
2914 else if (pg_strcasecmp(cmd, "sleep") == 0)
2915 mc = META_SLEEP;
2916 else if (pg_strcasecmp(cmd, "if") == 0)
2917 mc = META_IF;
2918 else if (pg_strcasecmp(cmd, "elif") == 0)
2919 mc = META_ELIF;
2920 else if (pg_strcasecmp(cmd, "else") == 0)
2921 mc = META_ELSE;
2922 else if (pg_strcasecmp(cmd, "endif") == 0)
2923 mc = META_ENDIF;
2924 else if (pg_strcasecmp(cmd, "gset") == 0)
2925 mc = META_GSET;
2926 else if (pg_strcasecmp(cmd, "aset") == 0)
2927 mc = META_ASET;
2928 else if (pg_strcasecmp(cmd, "startpipeline") == 0)
2929 mc = META_STARTPIPELINE;
2930 else if (pg_strcasecmp(cmd, "syncpipeline") == 0)
2931 mc = META_SYNCPIPELINE;
2932 else if (pg_strcasecmp(cmd, "endpipeline") == 0)
2933 mc = META_ENDPIPELINE;
2934 else
2935 mc = META_NONE;
2936 return mc;
2937 }
2938
2939 /*
2940 * Run a shell command. The result is assigned to the variable if not NULL.
2941 * Return true if succeeded, or false on error.
2942 */
2943 static bool
2944 runShellCommand(Variables *variables, char *variable, char **argv, int argc)
2945 {
2946 char command[SHELL_COMMAND_SIZE];
2947 int i,
2948 len = 0;
2949 FILE *fp;
2950 char res[64];
2951 char *endptr;
2952 int retval;
2953
2954 /*----------
2955 * Join arguments with whitespace separators. Arguments starting with
2956 * exactly one colon are treated as variables:
2957 * name - append a string "name"
2958 * :var - append a variable named 'var'
2959 * ::name - append a string ":name"
2960 *----------
2961 */
2962 for (i = 0; i < argc; i++)
2963 {
2964 char *arg;
2965 int arglen;
2966
2967 if (argv[i][0] != ':')
2968 {
2969 arg = argv[i]; /* a string literal */
2970 }
2971 else if (argv[i][1] == ':')
2972 {
2973 arg = argv[i] + 1; /* a string literal starting with colons */
2974 }
2975 else if ((arg = getVariable(variables, argv[i] + 1)) == NULL)
2976 {
2977 pg_log_error("%s: undefined variable \"%s\"", argv[0], argv[i]);
2978 return false;
2979 }
2980
2981 arglen = strlen(arg);
2982 if (len + arglen + (i > 0 ? 1 : 0) >= SHELL_COMMAND_SIZE - 1)
2983 {
2984 pg_log_error("%s: shell command is too long", argv[0]);
2985 return false;
2986 }
2987
2988 if (i > 0)
2989 command[len++] = ' ';
2990 memcpy(command + len, arg, arglen);
2991 len += arglen;
2992 }
2993
2994 command[len] = '\0';
2995
2996 fflush(NULL); /* needed before either system() or popen() */
2997
2998 /* Fast path for non-assignment case */
2999 if (variable == NULL)
3000 {
3001 if (system(command))
3002 {
3003 if (!timer_exceeded)
3004 pg_log_error("%s: could not launch shell command", argv[0]);
3005 return false;
3006 }
3007 return true;
3008 }
3009
3010 /* Execute the command with pipe and read the standard output. */
3011 if ((fp = popen(command, "r")) == NULL)
3012 {
3013 pg_log_error("%s: could not launch shell command", argv[0]);
3014 return false;
3015 }
3016 if (fgets(res, sizeof(res), fp) == NULL)
3017 {
3018 if (!timer_exceeded)
3019 pg_log_error("%s: could not read result of shell command", argv[0]);
3020 (void) pclose(fp);
3021 return false;
3022 }
3023 if (pclose(fp) < 0)
3024 {
3025 pg_log_error("%s: could not run shell command: %m", argv[0]);
3026 return false;
3027 }
3028
3029 /* Check whether the result is an integer and assign it to the variable */
3030 retval = (int) strtol(res, &endptr, 10);
3031 while (*endptr != '\0' && isspace((unsigned char) *endptr))
3032 endptr++;
3033 if (*res == '\0' || *endptr != '\0')
3034 {
3035 pg_log_error("%s: shell command must return an integer (not \"%s\")", argv[0], res);
3036 return false;
3037 }
3038 if (!putVariableInt(variables, "setshell", variable, retval))
3039 return false;
3040
3041 pg_log_debug("%s: shell parameter name: \"%s\", value: \"%s\"", argv[0], argv[1], res);
3042
3043 return true;
3044 }
3045
3046 /*
3047 * Report the abortion of the client when processing SQL commands.
3048 */
3049 static void
3050 commandFailed(CState *st, const char *cmd, const char *message)
3051 {
3052 pg_log_error("client %d aborted in command %d (%s) of script %d; %s",
3053 st->id, st->command, cmd, st->use_file, message);
3054 }
3055
3056 /*
3057 * Report the error in the command while the script is executing.
3058 */
3059 static void
3060 commandError(CState *st, const char *message)
3061 {
3062 /*
3063 * Errors should only be detected during an SQL command or the
3064 * \endpipeline meta command. Any other case triggers an assertion
3065 * failure.
3066 */
3067 Assert(sql_script[st->use_file].commands[st->command]->type == SQL_COMMAND ||
3068 sql_script[st->use_file].commands[st->command]->meta == META_ENDPIPELINE);
3069
3070 pg_log_info("client %d got an error in command %d (SQL) of script %d; %s",
3071 st->id, st->command, st->use_file, message);
3072 }
3073
3074 /* return a script number with a weighted choice. */
3075 static int
3076 chooseScript(TState *thread)
3077 {
3078 int i = 0;
3079 int64 w;
3080
3081 if (num_scripts == 1)
3082 return 0;
3083
3084 w = getrand(&thread->ts_choose_rs, 0, total_weight - 1);
3085 do
3086 {
3087 w -= sql_script[i++].weight;
3088 } while (w >= 0);
3089
3090 return i - 1;
3091 }
3092
3093 /*
3094 * Allocate space for CState->prepared: we need one boolean for each command
3095 * of each script.
3096 */
3097 static void
3098 allocCStatePrepared(CState *st)
3099 {
3100 Assert(st->prepared == NULL);
3101
3102 st->prepared = pg_malloc(sizeof(bool *) * num_scripts);
3103 for (int i = 0; i < num_scripts; i++)
3104 {
3105 ParsedScript *script = &sql_script[i];
3106 int numcmds;
3107
3108 for (numcmds = 0; script->commands[numcmds] != NULL; numcmds++)
3109 ;
3110 st->prepared[i] = pg_malloc0(sizeof(bool) * numcmds);
3111 }
3112 }
3113
3114 /*
3115 * Prepare the SQL command from st->use_file at command_num.
3116 */
3117 static void
3118 prepareCommand(CState *st, int command_num)
3119 {
3120 Command *command = sql_script[st->use_file].commands[command_num];
3121
3122 /* No prepare for non-SQL commands */
3123 if (command->type != SQL_COMMAND)
3124 return;
3125
3126 if (!st->prepared)
3127 allocCStatePrepared(st);
3128
3129 if (!st->prepared[st->use_file][command_num])
3130 {
3131 PGresult *res;
3132
3133 pg_log_debug("client %d preparing %s", st->id, command->prepname);
3134 res = PQprepare(st->con, command->prepname,
3135 command->argv[0], command->argc - 1, NULL);
3136 if (PQresultStatus(res) != PGRES_COMMAND_OK)
3137 pg_log_error("%s", PQerrorMessage(st->con));
3138 PQclear(res);
3139 st->prepared[st->use_file][command_num] = true;
3140 }
3141 }
3142
3143 /*
3144 * Prepare all the commands in the script that come after the \startpipeline
3145 * that's at position st->command, and the first \endpipeline we find.
3146 *
3147 * This sets the ->prepared flag for each relevant command as well as the
3148 * \startpipeline itself, but doesn't move the st->command counter.
3149 */
3150 static void
3151 prepareCommandsInPipeline(CState *st)
3152 {
3153 int j;
3154 Command **commands = sql_script[st->use_file].commands;
3155
3156 Assert(commands[st->command]->type == META_COMMAND &&
3157 commands[st->command]->meta == META_STARTPIPELINE);
3158
3159 if (!st->prepared)
3160 allocCStatePrepared(st);
3161
3162 /*
3163 * We set the 'prepared' flag on the \startpipeline itself to flag that we
3164 * don't need to do this next time without calling prepareCommand(), even
3165 * though we don't actually prepare this command.
3166 */
3167 if (st->prepared[st->use_file][st->command])
3168 return;
3169
3170 for (j = st->command + 1; commands[j] != NULL; j++)
3171 {
3172 if (commands[j]->type == META_COMMAND &&
3173 commands[j]->meta == META_ENDPIPELINE)
3174 break;
3175
3176 prepareCommand(st, j);
3177 }
3178
3179 st->prepared[st->use_file][st->command] = true;
3180 }
3181
3182 /* Send a SQL command, using the chosen querymode */
3183 static bool
3184 sendCommand(CState *st, Command *command)
3185 {
3186 int r;
3187
3188 if (querymode == QUERY_SIMPLE)
3189 {
3190 char *sql;
3191
3192 sql = pg_strdup(command->argv[0]);
3193 sql = assignVariables(&st->variables, sql);
3194
3195 pg_log_debug("client %d sending %s", st->id, sql);
3196 r = PQsendQuery(st->con, sql);
3197 free(sql);
3198 }
3199 else if (querymode == QUERY_EXTENDED)
3200 {
3201 const char *sql = command->argv[0];
3202 const char *params[MAX_ARGS];
3203
3204 getQueryParams(&st->variables, command, params);
3205
3206 pg_log_debug("client %d sending %s", st->id, sql);
3207 r = PQsendQueryParams(st->con, sql, command->argc - 1,
3208 NULL, params, NULL, NULL, 0);
3209 }
3210 else if (querymode == QUERY_PREPARED)
3211 {
3212 const char *params[MAX_ARGS];
3213
3214 prepareCommand(st, st->command);
3215 getQueryParams(&st->variables, command, params);
3216
3217 pg_log_debug("client %d sending %s", st->id, command->prepname);
3218 r = PQsendQueryPrepared(st->con, command->prepname, command->argc - 1,
3219 params, NULL, NULL, 0);
3220 }
3221 else /* unknown sql mode */
3222 r = 0;
3223
3224 if (r == 0)
3225 {
3226 pg_log_debug("client %d could not send %s", st->id, command->argv[0]);
3227 return false;
3228 }
3229 else
3230 return true;
3231 }
3232
3233 /*
3234 * Get the error status from the error code.
3235 */
3236 static EStatus
3237 getSQLErrorStatus(const char *sqlState)
3238 {
3239 if (sqlState != NULL)
3240 {
3241 if (strcmp(sqlState, ERRCODE_T_R_SERIALIZATION_FAILURE) == 0)
3242 return ESTATUS_SERIALIZATION_ERROR;
3243 else if (strcmp(sqlState, ERRCODE_T_R_DEADLOCK_DETECTED) == 0)
3244 return ESTATUS_DEADLOCK_ERROR;
3245 }
3246
3247 return ESTATUS_OTHER_SQL_ERROR;
3248 }
3249
3250 /*
3251 * Returns true if this type of error can be retried.
3252 */
3253 static bool
3254 canRetryError(EStatus estatus)
3255 {
3256 return (estatus == ESTATUS_SERIALIZATION_ERROR ||
3257 estatus == ESTATUS_DEADLOCK_ERROR);
3258 }
3259
3260 /*
3261 * Process query response from the backend.
3262 *
3263 * If varprefix is not NULL, it's the variable name prefix where to store
3264 * the results of the *last* command (META_GSET) or *all* commands
3265 * (META_ASET).
3266 *
3267 * Returns true if everything is A-OK, false if any error occurs.
3268 */
3269 static bool
3270 readCommandResponse(CState *st, MetaCommand meta, char *varprefix)
3271 {
3272 PGresult *res;
3273 PGresult *next_res;
3274 int qrynum = 0;
3275
3276 /*
3277 * varprefix should be set only with \gset or \aset, and \endpipeline and
3278 * SQL commands do not need it.
3279 */
3280 Assert((meta == META_NONE && varprefix == NULL) ||
3281 ((meta == META_ENDPIPELINE) && varprefix == NULL) ||
3282 ((meta == META_GSET || meta == META_ASET) && varprefix != NULL));
3283
3284 res = PQgetResult(st->con);
3285
3286 while (res != NULL)
3287 {
3288 bool is_last;
3289
3290 /* peek at the next result to know whether the current is last */
3291 next_res = PQgetResult(st->con);
3292 is_last = (next_res == NULL);
3293
3294 switch (PQresultStatus(res))
3295 {
3296 case PGRES_COMMAND_OK: /* non-SELECT commands */
3297 case PGRES_EMPTY_QUERY: /* may be used for testing no-op overhead */
3298 if (is_last && meta == META_GSET)
3299 {
3300 pg_log_error("client %d script %d command %d query %d: expected one row, got %d",
3301 st->id, st->use_file, st->command, qrynum, 0);
3302 st->estatus = ESTATUS_META_COMMAND_ERROR;
3303 goto error;
3304 }
3305 break;
3306
3307 case PGRES_TUPLES_OK:
3308 if ((is_last && meta == META_GSET) || meta == META_ASET)
3309 {
3310 int ntuples = PQntuples(res);
3311
3312 if (meta == META_GSET && ntuples != 1)
3313 {
3314 /* under \gset, report the error */
3315 pg_log_error("client %d script %d command %d query %d: expected one row, got %d",
3316 st->id, st->use_file, st->command, qrynum, PQntuples(res));
3317 st->estatus = ESTATUS_META_COMMAND_ERROR;
3318 goto error;
3319 }
3320 else if (meta == META_ASET && ntuples <= 0)
3321 {
3322 /* coldly skip empty result under \aset */
3323 break;
3324 }
3325
3326 /* store results into variables */
3327 for (int fld = 0; fld < PQnfields(res); fld++)
3328 {
3329 char *varname = PQfname(res, fld);
3330
3331 /* allocate varname only if necessary, freed below */
3332 if (*varprefix != '\0')
3333 varname = psprintf("%s%s", varprefix, varname);
3334
3335 /* store last row result as a string */
3336 if (!putVariable(&st->variables, meta == META_ASET ? "aset" : "gset", varname,
3337 PQgetvalue(res, ntuples - 1, fld)))
3338 {
3339 /* internal error */
3340 pg_log_error("client %d script %d command %d query %d: error storing into variable %s",
3341 st->id, st->use_file, st->command, qrynum, varname);
3342 st->estatus = ESTATUS_META_COMMAND_ERROR;
3343 goto error;
3344 }
3345
3346 if (*varprefix != '\0')
3347 pg_free(varname);
3348 }
3349 }
3350 /* otherwise the result is simply thrown away by PQclear below */
3351 break;
3352
3353 case PGRES_PIPELINE_SYNC:
3354 pg_log_debug("client %d pipeline ending, ongoing syncs: %d",
3355 st->id, st->num_syncs);
3356 st->num_syncs--;
3357 if (st->num_syncs == 0 && PQexitPipelineMode(st->con) != 1)
3358 pg_log_error("client %d failed to exit pipeline mode: %s", st->id,
3359 PQresultErrorMessage(res));
3360 break;
3361
3362 case PGRES_COPY_IN:
3363 case PGRES_COPY_OUT:
3364 case PGRES_COPY_BOTH:
3365 pg_log_error("COPY is not supported in pgbench, aborting");
3366
3367 /*
3368 * We need to exit the copy state. Otherwise, PQgetResult()
3369 * will always return an empty PGresult as an effect of
3370 * getCopyResult(), leading to an infinite loop in the error
3371 * cleanup done below.
3372 */
3373 PQendcopy(st->con);
3374 goto error;
3375
3376 case PGRES_NONFATAL_ERROR:
3377 case PGRES_FATAL_ERROR:
3378 st->estatus = getSQLErrorStatus(PQresultErrorField(res,
3379 PG_DIAG_SQLSTATE));
3380 if (canRetryError(st->estatus))
3381 {
3382 if (verbose_errors)
3383 commandError(st, PQresultErrorMessage(res));
3384 goto error;
3385 }
3386 /* fall through */
3387
3388 default:
3389 /* anything else is unexpected */
3390 pg_log_error("client %d script %d aborted in command %d query %d: %s",
3391 st->id, st->use_file, st->command, qrynum,
3392 PQresultErrorMessage(res));
3393 goto error;
3394 }
3395
3396 PQclear(res);
3397 qrynum++;
3398 res = next_res;
3399 }
3400
3401 if (qrynum == 0)
3402 {
3403 pg_log_error("client %d command %d: no results", st->id, st->command);
3404 return false;
3405 }
3406
3407 return true;
3408
3409 error:
3410 PQclear(res);
3411 PQclear(next_res);
3412 do
3413 {
3414 res = PQgetResult(st->con);
3415 PQclear(res);
3416 } while (res);
3417
3418 return false;
3419 }
3420
3421 /*
3422 * Parse the argument to a \sleep command, and return the requested amount
3423 * of delay, in microseconds. Returns true on success, false on error.
3424 */
3425 static bool
3426 evaluateSleep(Variables *variables, int argc, char **argv, int *usecs)
3427 {
3428 char *var;
3429 int usec;
3430
3431 if (*argv[1] == ':')
3432 {
3433 if ((var = getVariable(variables, argv[1] + 1)) == NULL)
3434 {
3435 pg_log_error("%s: undefined variable \"%s\"", argv[0], argv[1] + 1);
3436 return false;
3437 }
3438
3439 usec = atoi(var);
3440
3441 /* Raise an error if the value of a variable is not a number */
3442 if (usec == 0 && !isdigit((unsigned char) *var))
3443 {
3444 pg_log_error("%s: invalid sleep time \"%s\" for variable \"%s\"",
3445 argv[0], var, argv[1] + 1);
3446 return false;
3447 }
3448 }
3449 else
3450 usec = atoi(argv[1]);
3451
3452 if (argc > 2)
3453 {
3454 if (pg_strcasecmp(argv[2], "ms") == 0)
3455 usec *= 1000;
3456 else if (pg_strcasecmp(argv[2], "s") == 0)
3457 usec *= 1000000;
3458 }
3459 else
3460 usec *= 1000000;
3461
3462 *usecs = usec;
3463 return true;
3464 }
3465
3466
3467 /*
3468 * Returns true if the error can be retried.
3469 */
3470 static bool
3471 doRetry(CState *st, pg_time_usec_t *now)
3472 {
3473 Assert(st->estatus != ESTATUS_NO_ERROR);
3474
3475 /* We can only retry serialization or deadlock errors. */
3476 if (!canRetryError(st->estatus))
3477 return false;
3478
3479 /*
3480 * We must have at least one option to limit the retrying of transactions
3481 * that got an error.
3482 */
3483 Assert(max_tries || latency_limit || duration > 0);
3484
3485 /*
3486 * We cannot retry the error if we have reached the maximum number of
3487 * tries.
3488 */
3489 if (max_tries && st->tries >= max_tries)
3490 return false;
3491
3492 /*
3493 * We cannot retry the error if we spent too much time on this
3494 * transaction.
3495 */
3496 if (latency_limit)
3497 {
3498 pg_time_now_lazy(now);
3499 if (*now - st->txn_scheduled > latency_limit)
3500 return false;
3501 }
3502
3503 /*
3504 * We cannot retry the error if the benchmark duration is over.
3505 */
3506 if (timer_exceeded)
3507 return false;
3508
3509 /* OK */
3510 return true;
3511 }
3512
3513 /*
3514 * Read and discard results until the last sync point.
3515 */
3516 static int
3517 discardUntilSync(CState *st)
3518 {
3519 bool received_sync = false;
3520
3521 /*
3522 * Send a Sync message to ensure at least one PGRES_PIPELINE_SYNC is
3523 * received and to avoid an infinite loop, since all earlier ones may have
3524 * already been received.
3525 */
3526 if (!PQpipelineSync(st->con))
3527 {
3528 pg_log_error("client %d aborted: failed to send a pipeline sync",
3529 st->id);
3530 return 0;
3531 }
3532
3533 /*
3534 * Continue reading results until the last sync point, i.e., until
3535 * reaching null just after PGRES_PIPELINE_SYNC.
3536 */
3537 for (;;)
3538 {
3539 PGresult *res = PQgetResult(st->con);
3540
3541 if (PQstatus(st->con) == CONNECTION_BAD)
3542 {
3543 pg_log_error("client %d aborted while rolling back the transaction after an error; perhaps the backend died while processing",
3544 st->id);
3545 PQclear(res);
3546 return 0;
3547 }
3548
3549 if (PQresultStatus(res) == PGRES_PIPELINE_SYNC)
3550 received_sync = true;
3551 else if (received_sync && res == NULL)
3552 {
3553 /*
3554 * Reset ongoing sync count to 0 since all PGRES_PIPELINE_SYNC
3555 * results have been discarded.
3556 */
3557 st->num_syncs = 0;
3558 break;
3559 }
3560 else
3561 {
3562 /*
3563 * If a PGRES_PIPELINE_SYNC is followed by something other than
3564 * PGRES_PIPELINE_SYNC or NULL, another PGRES_PIPELINE_SYNC will
3565 * appear later. Reset received_sync to false to wait for it.
3566 */
3567 received_sync = false;
3568 }
3569 PQclear(res);
3570 }
3571
3572 /* exit pipeline */
3573 if (PQexitPipelineMode(st->con) != 1)
3574 {
3575 pg_log_error("client %d aborted: failed to exit pipeline mode for rolling back the failed transaction",
3576 st->id);
3577 return 0;
3578 }
3579 return 1;
3580 }
3581
3582 /*
3583 * Get the transaction status at the end of a command especially for
3584 * checking if we are in a (failed) transaction block.
3585 */
3586 static TStatus
3587 getTransactionStatus(PGconn *con)
3588 {
3589 PGTransactionStatusType tx_status;
3590
3591 tx_status = PQtransactionStatus(con);
3592 switch (tx_status)
3593 {
3594 case PQTRANS_IDLE:
3595 return TSTATUS_IDLE;
3596 case PQTRANS_INTRANS:
3597 case PQTRANS_INERROR:
3598 return TSTATUS_IN_BLOCK;
3599 case PQTRANS_UNKNOWN:
3600 /* PQTRANS_UNKNOWN is expected given a broken connection */
3601 if (PQstatus(con) == CONNECTION_BAD)
3602 return TSTATUS_CONN_ERROR;
3603 /* fall through */
3604 case PQTRANS_ACTIVE:
3605 default:
3606
3607 /*
3608 * We cannot find out whether we are in a transaction block or
3609 * not. Internal error which should never occur.
3610 */
3611 pg_log_error("unexpected transaction status %d", tx_status);
3612 return TSTATUS_OTHER_ERROR;
3613 }
3614
3615 /* not reached */
3616 Assert(false);
3617 return TSTATUS_OTHER_ERROR;
3618 }
3619
3620 /*
3621 * Print verbose messages of an error
3622 */
3623 static void
3624 printVerboseErrorMessages(CState *st, pg_time_usec_t *now, bool is_retry)
3625 {
3626 PQExpBufferData buf;
3627
3628 initPQExpBuffer(&buf);
3629
3630 printfPQExpBuffer(&buf, "client %d ", st->id);
3631 appendPQExpBufferStr(&buf, (is_retry ?
3632 "repeats the transaction after the error" :
3633 "ends the failed transaction"));
3634 appendPQExpBuffer(&buf, " (try %u", st->tries);
3635
3636 /* Print max_tries if it is not unlimited. */
3637 if (max_tries)
3638 appendPQExpBuffer(&buf, "/%u", max_tries);
3639
3640 /*
3641 * If the latency limit is used, print a percentage of the current
3642 * transaction latency from the latency limit.
3643 */
3644 if (latency_limit)
3645 {
3646 pg_time_now_lazy(now);
3647 appendPQExpBuffer(&buf, ", %.3f%% of the maximum time of tries was used",
3648 (100.0 * (*now - st->txn_scheduled) / latency_limit));
3649 }
3650 appendPQExpBufferStr(&buf, ")\n");
3651
3652 pg_log_info("%s", buf.data);
3653
3654 termPQExpBuffer(&buf);
3655 }
3656
3657 /*
3658 * Advance the state machine of a connection.
3659 */
3660 static void
3661 advanceConnectionState(TState *thread, CState *st, StatsData *agg)
3662 {
3663
3664 /*
3665 * gettimeofday() isn't free, so we get the current timestamp lazily the
3666 * first time it's needed, and reuse the same value throughout this
3667 * function after that. This also ensures that e.g. the calculated
3668 * latency reported in the log file and in the totals are the same. Zero
3669 * means "not set yet". Reset "now" when we execute shell commands or
3670 * expressions, which might take a non-negligible amount of time, though.
3671 */
3672 pg_time_usec_t now = 0;
3673
3674 /*
3675 * Loop in the state machine, until we have to wait for a result from the
3676 * server or have to sleep for throttling or \sleep.
3677 *
3678 * Note: In the switch-statement below, 'break' will loop back here,
3679 * meaning "continue in the state machine". Return is used to return to
3680 * the caller, giving the thread the opportunity to advance another
3681 * client.
3682 */
3683 for (;;)
3684 {
3685 Command *command;
3686
3687 switch (st->state)
3688 {
3689 /* Select transaction (script) to run. */
3690 case CSTATE_CHOOSE_SCRIPT:
3691 st->use_file = chooseScript(thread);
3692 Assert(conditional_stack_empty(st->cstack));
3693
3694 /* reset transaction variables to default values */
3695 st->estatus = ESTATUS_NO_ERROR;
3696 st->tries = 1;
3697
3698 pg_log_debug("client %d executing script \"%s\"",
3699 st->id, sql_script[st->use_file].desc);
3700
3701 /*
3702 * If time is over, we're done; otherwise, get ready to start
3703 * a new transaction, or to get throttled if that's requested.
3704 */
3705 st->state = timer_exceeded ? CSTATE_FINISHED :
3706 throttle_delay > 0 ? CSTATE_PREPARE_THROTTLE : CSTATE_START_TX;
3707 break;
3708
3709 /* Start new transaction (script) */
3710 case CSTATE_START_TX:
3711 pg_time_now_lazy(&now);
3712
3713 /* establish connection if needed, i.e. under --connect */
3714 if (st->con == NULL)
3715 {
3716 pg_time_usec_t start = now;
3717
3718 if ((st->con = doConnect()) == NULL)
3719 {
3720 /*
3721 * as the bench is already running, we do not abort
3722 * the process
3723 */
3724 pg_log_error("client %d aborted while establishing connection", st->id);
3725 st->state = CSTATE_ABORTED;
3726 break;
3727 }
3728
3729 /* reset now after connection */
3730 now = pg_time_now();
3731
3732 thread->conn_duration += now - start;
3733
3734 /* Reset session-local state */
3735 pg_free(st->prepared);
3736 st->prepared = NULL;
3737 }
3738
3739 /*
3740 * It is the first try to run this transaction. Remember the
3741 * random state: maybe it will get an error and we will need
3742 * to run it again.
3743 */
3744 st->random_state = st->cs_func_rs;
3745
3746 /* record transaction start time */
3747 st->txn_begin = now;
3748
3749 /*
3750 * When not throttling, this is also the transaction's
3751 * scheduled start time.
3752 */
3753 if (!throttle_delay)
3754 st->txn_scheduled = now;
3755
3756 /* Begin with the first command */
3757 st->state = CSTATE_START_COMMAND;
3758 st->command = 0;
3759 break;
3760
3761 /*
3762 * Handle throttling once per transaction by sleeping.
3763 */
3764 case CSTATE_PREPARE_THROTTLE:
3765
3766 /*
3767 * Generate a delay such that the series of delays will
3768 * approximate a Poisson distribution centered on the
3769 * throttle_delay time.
3770 *
3771 * If transactions are too slow or a given wait is shorter
3772 * than a transaction, the next transaction will start right
3773 * away.
3774 */
3775 Assert(throttle_delay > 0);
3776
3777 thread->throttle_trigger +=
3778 getPoissonRand(&thread->ts_throttle_rs, throttle_delay);
3779 st->txn_scheduled = thread->throttle_trigger;
3780
3781 /*
3782 * If --latency-limit is used, and this slot is already late
3783 * so that the transaction will miss the latency limit even if
3784 * it completed immediately, skip this time slot and loop to
3785 * reschedule.
3786 */
3787 if (latency_limit)
3788 {
3789 pg_time_now_lazy(&now);
3790
3791 if (thread->throttle_trigger < now - latency_limit)
3792 {
3793 processXactStats(thread, st, &now, true, agg);
3794
3795 /*
3796 * Finish client if -T or -t was exceeded.
3797 *
3798 * Stop counting skipped transactions under -T as soon
3799 * as the timer is exceeded. Because otherwise it can
3800 * take a very long time to count all of them
3801 * especially when quite a lot of them happen with
3802 * unrealistically high rate setting in -R, which
3803 * would prevent pgbench from ending immediately.
3804 * Because of this behavior, note that there is no
3805 * guarantee that all skipped transactions are counted
3806 * under -T though there is under -t. This is OK in
3807 * practice because it's very unlikely to happen with
3808 * realistic setting.
3809 */
3810 if (timer_exceeded || (nxacts > 0 && st->cnt >= nxacts))
3811 st->state = CSTATE_FINISHED;
3812
3813 /* Go back to top of loop with CSTATE_PREPARE_THROTTLE */
3814 break;
3815 }
3816 }
3817
3818 /*
3819 * stop client if next transaction is beyond pgbench end of
3820 * execution; otherwise, throttle it.
3821 */
3822 st->state = end_time > 0 && st->txn_scheduled > end_time ?
3823 CSTATE_FINISHED : CSTATE_THROTTLE;
3824 break;
3825
3826 /*
3827 * Wait until it's time to start next transaction.
3828 */
3829 case CSTATE_THROTTLE:
3830 pg_time_now_lazy(&now);
3831
3832 if (now < st->txn_scheduled)
3833 return; /* still sleeping, nothing to do here */
3834
3835 /* done sleeping, but don't start transaction if we're done */
3836 st->state = timer_exceeded ? CSTATE_FINISHED : CSTATE_START_TX;
3837 break;
3838
3839 /*
3840 * Send a command to server (or execute a meta-command)
3841 */
3842 case CSTATE_START_COMMAND:
3843 command = sql_script[st->use_file].commands[st->command];
3844
3845 /*
3846 * Transition to script end processing if done, but close up
3847 * shop if a pipeline is open at this point.
3848 */
3849 if (command == NULL)
3850 {
3851 if (PQpipelineStatus(st->con) == PQ_PIPELINE_OFF)
3852 st->state = CSTATE_END_TX;
3853 else
3854 {
3855 pg_log_error("client %d aborted: end of script reached with pipeline open",
3856 st->id);
3857 st->state = CSTATE_ABORTED;
3858 }
3859
3860 break;
3861 }
3862
3863 /* record begin time of next command, and initiate it */
3864 if (report_per_command)
3865 {
3866 pg_time_now_lazy(&now);
3867 st->stmt_begin = now;
3868 }
3869
3870 /* Execute the command */
3871 if (command->type == SQL_COMMAND)
3872 {
3873 /* disallow \aset and \gset in pipeline mode */
3874 if (PQpipelineStatus(st->con) != PQ_PIPELINE_OFF)
3875 {
3876 if (command->meta == META_GSET)
3877 {
3878 commandFailed(st, "gset", "\\gset is not allowed in pipeline mode");
3879 st->state = CSTATE_ABORTED;
3880 break;
3881 }
3882 else if (command->meta == META_ASET)
3883 {
3884 commandFailed(st, "aset", "\\aset is not allowed in pipeline mode");
3885 st->state = CSTATE_ABORTED;
3886 break;
3887 }
3888 }
3889
3890 if (!sendCommand(st, command))
3891 {
3892 commandFailed(st, "SQL", "SQL command send failed");
3893 st->state = CSTATE_ABORTED;
3894 }
3895 else
3896 {
3897 /* Wait for results, unless in pipeline mode */
3898 if (PQpipelineStatus(st->con) == PQ_PIPELINE_OFF)
3899 st->state = CSTATE_WAIT_RESULT;
3900 else
3901 st->state = CSTATE_END_COMMAND;
3902 }
3903 }
3904 else if (command->type == META_COMMAND)
3905 {
3906 /*-----
3907 * Possible state changes when executing meta commands:
3908 * - on errors CSTATE_ABORTED
3909 * - on sleep CSTATE_SLEEP
3910 * - else CSTATE_END_COMMAND
3911 */
3912 st->state = executeMetaCommand(st, &now);
3913 if (st->state == CSTATE_ABORTED)
3914 st->estatus = ESTATUS_META_COMMAND_ERROR;
3915 }
3916
3917 /*
3918 * We're now waiting for an SQL command to complete, or
3919 * finished processing a metacommand, or need to sleep, or
3920 * something bad happened.
3921 */
3922 Assert(st->state == CSTATE_WAIT_RESULT ||
3923 st->state == CSTATE_END_COMMAND ||
3924 st->state == CSTATE_SLEEP ||
3925 st->state == CSTATE_ABORTED);
3926 break;
3927
3928 /*
3929 * non executed conditional branch
3930 */
3931 case CSTATE_SKIP_COMMAND:
3932 Assert(!conditional_active(st->cstack));
3933 /* quickly skip commands until something to do... */
3934 while (true)
3935 {
3936 command = sql_script[st->use_file].commands[st->command];
3937
3938 /* cannot reach end of script in that state */
3939 Assert(command != NULL);
3940
3941 /*
3942 * if this is conditional related, update conditional
3943 * state
3944 */
3945 if (command->type == META_COMMAND &&
3946 (command->meta == META_IF ||
3947 command->meta == META_ELIF ||
3948 command->meta == META_ELSE ||
3949 command->meta == META_ENDIF))
3950 {
3951 switch (conditional_stack_peek(st->cstack))
3952 {
3953 case IFSTATE_FALSE:
3954 if (command->meta == META_IF)
3955 {
3956 /* nested if in skipped branch - ignore */
3957 conditional_stack_push(st->cstack,
3958 IFSTATE_IGNORED);
3959 st->command++;
3960 }
3961 else if (command->meta == META_ELIF)
3962 {
3963 /* we must evaluate the condition */
3964 st->state = CSTATE_START_COMMAND;
3965 }
3966 else if (command->meta == META_ELSE)
3967 {
3968 /* we must execute next command */
3969 conditional_stack_poke(st->cstack,
3970 IFSTATE_ELSE_TRUE);
3971 st->state = CSTATE_START_COMMAND;
3972 st->command++;
3973 }
3974 else if (command->meta == META_ENDIF)
3975 {
3976 Assert(!conditional_stack_empty(st->cstack));
3977 conditional_stack_pop(st->cstack);
3978 if (conditional_active(st->cstack))
3979 st->state = CSTATE_START_COMMAND;
3980 /* else state remains CSTATE_SKIP_COMMAND */
3981 st->command++;
3982 }
3983 break;
3984
3985 case IFSTATE_IGNORED:
3986 case IFSTATE_ELSE_FALSE:
3987 if (command->meta == META_IF)
3988 conditional_stack_push(st->cstack,
3989 IFSTATE_IGNORED);
3990 else if (command->meta == META_ENDIF)
3991 {
3992 Assert(!conditional_stack_empty(st->cstack));
3993 conditional_stack_pop(st->cstack);
3994 if (conditional_active(st->cstack))
3995 st->state = CSTATE_START_COMMAND;
3996 }
3997 /* could detect "else" & "elif" after "else" */
3998 st->command++;
3999 break;
4000
4001 case IFSTATE_NONE:
4002 case IFSTATE_TRUE:
4003 case IFSTATE_ELSE_TRUE:
4004 default:
4005
4006 /*
4007 * inconsistent if inactive, unreachable dead
4008 * code
4009 */
4010 Assert(false);
4011 }
4012 }
4013 else
4014 {
4015 /* skip and consider next */
4016 st->command++;
4017 }
4018
4019 if (st->state != CSTATE_SKIP_COMMAND)
4020 /* out of quick skip command loop */
4021 break;
4022 }
4023 break;
4024
4025 /*
4026 * Wait for the current SQL command to complete
4027 */
4028 case CSTATE_WAIT_RESULT:
4029 pg_log_debug("client %d receiving", st->id);
4030
4031 /*
4032 * Only check for new network data if we processed all data
4033 * fetched prior. Otherwise we end up doing a syscall for each
4034 * individual pipelined query, which has a measurable
4035 * performance impact.
4036 */
4037 if (PQisBusy(st->con) && !PQconsumeInput(st->con))
4038 {
4039 /* there's something wrong */
4040 commandFailed(st, "SQL", "perhaps the backend died while processing");
4041 st->state = CSTATE_ABORTED;
4042 break;
4043 }
4044 if (PQisBusy(st->con))
4045 return; /* don't have the whole result yet */
4046
4047 /* store or discard the query results */
4048 if (readCommandResponse(st,
4049 sql_script[st->use_file].commands[st->command]->meta,
4050 sql_script[st->use_file].commands[st->command]->varprefix))
4051 {
4052 /*
4053 * outside of pipeline mode: stop reading results.
4054 * pipeline mode: continue reading results until an
4055 * end-of-pipeline response.
4056 */
4057 if (PQpipelineStatus(st->con) != PQ_PIPELINE_ON)
4058 st->state = CSTATE_END_COMMAND;
4059 }
4060 else if (canRetryError(st->estatus))
4061 st->state = CSTATE_ERROR;
4062 else
4063 st->state = CSTATE_ABORTED;
4064 break;
4065
4066 /*
4067 * Wait until sleep is done. This state is entered after a
4068 * \sleep metacommand. The behavior is similar to
4069 * CSTATE_THROTTLE, but proceeds to CSTATE_START_COMMAND
4070 * instead of CSTATE_START_TX.
4071 */
4072 case CSTATE_SLEEP:
4073 pg_time_now_lazy(&now);
4074 if (now < st->sleep_until)
4075 return; /* still sleeping, nothing to do here */
4076 /* Else done sleeping. */
4077 st->state = CSTATE_END_COMMAND;
4078 break;
4079
4080 /*
4081 * End of command: record stats and proceed to next command.
4082 */
4083 case CSTATE_END_COMMAND:
4084
4085 /*
4086 * command completed: accumulate per-command execution times
4087 * in thread-local data structure, if per-command latencies
4088 * are requested.
4089 */
4090 if (report_per_command)
4091 {
4092 pg_time_now_lazy(&now);
4093
4094 command = sql_script[st->use_file].commands[st->command];
4095 /* XXX could use a mutex here, but we choose not to */
4096 addToSimpleStats(&command->stats,
4097 PG_TIME_GET_DOUBLE(now - st->stmt_begin));
4098 }
4099
4100 /* Go ahead with next command, to be executed or skipped */
4101 st->command++;
4102 st->state = conditional_active(st->cstack) ?
4103 CSTATE_START_COMMAND : CSTATE_SKIP_COMMAND;
4104 break;
4105
4106 /*
4107 * Clean up after an error.
4108 */
4109 case CSTATE_ERROR:
4110 {
4111 TStatus tstatus;
4112
4113 Assert(st->estatus != ESTATUS_NO_ERROR);
4114
4115 /* Clear the conditional stack */
4116 conditional_stack_reset(st->cstack);
4117
4118 /* Read and discard until a sync point in pipeline mode */
4119 if (PQpipelineStatus(st->con) != PQ_PIPELINE_OFF)
4120 {
4121 if (!discardUntilSync(st))
4122 {
4123 st->state = CSTATE_ABORTED;
4124 break;
4125 }
4126 }
4127
4128 /*
4129 * Check if we have a (failed) transaction block or not,
4130 * and roll it back if any.
4131 */
4132 tstatus = getTransactionStatus(st->con);
4133 if (tstatus == TSTATUS_IN_BLOCK)
4134 {
4135 /* Try to rollback a (failed) transaction block. */
4136 if (!PQsendQuery(st->con, "ROLLBACK"))
4137 {
4138 pg_log_error("client %d aborted: failed to send sql command for rolling back the failed transaction",
4139 st->id);
4140 st->state = CSTATE_ABORTED;
4141 }
4142 else
4143 st->state = CSTATE_WAIT_ROLLBACK_RESULT;
4144 }
4145 else if (tstatus == TSTATUS_IDLE)
4146 {
4147 /*
4148 * If time is over, we're done; otherwise, check if we
4149 * can retry the error.
4150 */
4151 st->state = timer_exceeded ? CSTATE_FINISHED :
4152 doRetry(st, &now) ? CSTATE_RETRY : CSTATE_FAILURE;
4153 }
4154 else
4155 {
4156 if (tstatus == TSTATUS_CONN_ERROR)
4157 pg_log_error("perhaps the backend died while processing");
4158
4159 pg_log_error("client %d aborted while receiving the transaction status", st->id);
4160 st->state = CSTATE_ABORTED;
4161 }
4162 break;
4163 }
4164
4165 /*
4166 * Wait for the rollback command to complete
4167 */
4168 case CSTATE_WAIT_ROLLBACK_RESULT:
4169 {
4170 PGresult *res;
4171
4172 pg_log_debug("client %d receiving", st->id);
4173 if (!PQconsumeInput(st->con))
4174 {
4175 pg_log_error("client %d aborted while rolling back the transaction after an error; perhaps the backend died while processing",
4176 st->id);
4177 st->state = CSTATE_ABORTED;
4178 break;
4179 }
4180 if (PQisBusy(st->con))
4181 return; /* don't have the whole result yet */
4182
4183 /*
4184 * Read and discard the query result;
4185 */
4186 res = PQgetResult(st->con);
4187 switch (PQresultStatus(res))
4188 {
4189 case PGRES_COMMAND_OK:
4190 /* OK */
4191 PQclear(res);
4192 /* null must be returned */
4193 res = PQgetResult(st->con);
4194 Assert(res == NULL);
4195
4196 /*
4197 * If time is over, we're done; otherwise, check
4198 * if we can retry the error.
4199 */
4200 st->state = timer_exceeded ? CSTATE_FINISHED :
4201 doRetry(st, &now) ? CSTATE_RETRY : CSTATE_FAILURE;
4202 break;
4203 default:
4204 pg_log_error("client %d aborted while rolling back the transaction after an error; %s",
4205 st->id, PQerrorMessage(st->con));
4206 PQclear(res);
4207 st->state = CSTATE_ABORTED;
4208 break;
4209 }
4210 break;
4211 }
4212
4213 /*
4214 * Retry the transaction after an error.
4215 */
4216 case CSTATE_RETRY:
4217 command = sql_script[st->use_file].commands[st->command];
4218
4219 /*
4220 * Inform that the transaction will be retried after the
4221 * error.
4222 */
4223 if (verbose_errors)
4224 printVerboseErrorMessages(st, &now, true);
4225
4226 /* Count tries and retries */
4227 st->tries++;
4228 command->retries++;
4229
4230 /*
4231 * Reset the random state as they were at the beginning of the
4232 * transaction.
4233 */
4234 st->cs_func_rs = st->random_state;
4235
4236 /* Process the first transaction command. */
4237 st->command = 0;
4238 st->estatus = ESTATUS_NO_ERROR;
4239 st->state = CSTATE_START_COMMAND;
4240 break;
4241
4242 /*
4243 * Record a failed transaction.
4244 */
4245 case CSTATE_FAILURE:
4246 command = sql_script[st->use_file].commands[st->command];
4247
4248 /* Accumulate the failure. */
4249 command->failures++;
4250
4251 /*
4252 * Inform that the failed transaction will not be retried.
4253 */
4254 if (verbose_errors)
4255 printVerboseErrorMessages(st, &now, false);
4256
4257 /* End the failed transaction. */
4258 st->state = CSTATE_END_TX;
4259 break;
4260
4261 /*
4262 * End of transaction (end of script, really).
4263 */
4264 case CSTATE_END_TX:
4265 {
4266 TStatus tstatus;
4267
4268 /* transaction finished: calculate latency and do log */
4269 processXactStats(thread, st, &now, false, agg);
4270
4271 /*
4272 * missing \endif... cannot happen if CheckConditional was
4273 * okay
4274 */
4275 Assert(conditional_stack_empty(st->cstack));
4276
4277 /*
4278 * We must complete all the transaction blocks that were
4279 * started in this script.
4280 */
4281 tstatus = getTransactionStatus(st->con);
4282 if (tstatus == TSTATUS_IN_BLOCK)
4283 {
4284 pg_log_error("client %d aborted: end of script reached without completing the last transaction",
4285 st->id);
4286 st->state = CSTATE_ABORTED;
4287 break;
4288 }
4289 else if (tstatus != TSTATUS_IDLE)
4290 {
4291 if (tstatus == TSTATUS_CONN_ERROR)
4292 pg_log_error("perhaps the backend died while processing");
4293
4294 pg_log_error("client %d aborted while receiving the transaction status", st->id);
4295 st->state = CSTATE_ABORTED;
4296 break;
4297 }
4298
4299 if (is_connect)
4300 {
4301 pg_time_usec_t start = now;
4302
4303 pg_time_now_lazy(&start);
4304 finishCon(st);
4305 now = pg_time_now();
4306 thread->conn_duration += now - start;
4307 }
4308
4309 if ((st->cnt >= nxacts && duration <= 0) || timer_exceeded)
4310 {
4311 /* script completed */
4312 st->state = CSTATE_FINISHED;
4313 break;
4314 }
4315
4316 /* next transaction (script) */
4317 st->state = CSTATE_CHOOSE_SCRIPT;
4318
4319 /*
4320 * Ensure that we always return on this point, so as to
4321 * avoid an infinite loop if the script only contains meta
4322 * commands.
4323 */
4324 return;
4325 }
4326
4327 /*
4328 * Final states. Close the connection if it's still open.
4329 */
4330 case CSTATE_ABORTED:
4331 case CSTATE_FINISHED:
4332
4333 /*
4334 * Don't measure the disconnection delays here even if in
4335 * CSTATE_FINISHED and -C/--connect option is specified.
4336 * Because in this case all the connections that this thread
4337 * established are closed at the end of transactions and the
4338 * disconnection delays should have already been measured at
4339 * that moment.
4340 *
4341 * In CSTATE_ABORTED state, the measurement is no longer
4342 * necessary because we cannot report complete results anyways
4343 * in this case.
4344 */
4345 finishCon(st);
4346 return;
4347 }
4348 }
4349 }
4350
4351 /*
4352 * Subroutine for advanceConnectionState -- initiate or execute the current
4353 * meta command, and return the next state to set.
4354 *
4355 * *now is updated to the current time, unless the command is expected to
4356 * take no time to execute.
4357 */
4358 static ConnectionStateEnum
4359 executeMetaCommand(CState *st, pg_time_usec_t *now)
4360 {
4361 Command *command = sql_script[st->use_file].commands[st->command];
4362 int argc;
4363 char **argv;
4364
4365 Assert(command != NULL && command->type == META_COMMAND);
4366
4367 argc = command->argc;
4368 argv = command->argv;
4369
4370 if (unlikely(__pg_log_level <= PG_LOG_DEBUG))
4371 {
4372 PQExpBufferData buf;
4373
4374 initPQExpBuffer(&buf);
4375
4376 printfPQExpBuffer(&buf, "client %d executing \\%s", st->id, argv[0]);
4377 for (int i = 1; i < argc; i++)
4378 appendPQExpBuffer(&buf, " %s", argv[i]);
4379
4380 pg_log_debug("%s", buf.data);
4381
4382 termPQExpBuffer(&buf);
4383 }
4384
4385 if (command->meta == META_SLEEP)
4386 {
4387 int usec;
4388
4389 /*
4390 * A \sleep doesn't execute anything, we just get the delay from the
4391 * argument, and enter the CSTATE_SLEEP state. (The per-command
4392 * latency will be recorded in CSTATE_SLEEP state, not here, after the
4393 * delay has elapsed.)
4394 */
4395 if (!evaluateSleep(&st->variables, argc, argv, &usec))
4396 {
4397 commandFailed(st, "sleep", "execution of meta-command failed");
4398 return CSTATE_ABORTED;
4399 }
4400
4401 pg_time_now_lazy(now);
4402 st->sleep_until = (*now) + usec;
4403 return CSTATE_SLEEP;
4404 }
4405 else if (command->meta == META_SET)
4406 {
4407 PgBenchExpr *expr = command->expr;
4408 PgBenchValue result;
4409
4410 if (!evaluateExpr(st, expr, &result))
4411 {
4412 commandFailed(st, argv[0], "evaluation of meta-command failed");
4413 return CSTATE_ABORTED;
4414 }
4415
4416 if (!putVariableValue(&st->variables, argv[0], argv[1], &result))
4417 {
4418 commandFailed(st, "set", "assignment of meta-command failed");
4419 return CSTATE_ABORTED;
4420 }
4421 }
4422 else if (command->meta == META_IF)
4423 {
4424 /* backslash commands with an expression to evaluate */
4425 PgBenchExpr *expr = command->expr;
4426 PgBenchValue result;
4427 bool cond;
4428
4429 if (!evaluateExpr(st, expr, &result))
4430 {
4431 commandFailed(st, argv[0], "evaluation of meta-command failed");
4432 return CSTATE_ABORTED;
4433 }
4434
4435 cond = valueTruth(&result);
4436 conditional_stack_push(st->cstack, cond ? IFSTATE_TRUE : IFSTATE_FALSE);
4437 }
4438 else if (command->meta == META_ELIF)
4439 {
4440 /* backslash commands with an expression to evaluate */
4441 PgBenchExpr *expr = command->expr;
4442 PgBenchValue result;
4443 bool cond;
4444
4445 if (conditional_stack_peek(st->cstack) == IFSTATE_TRUE)
4446 {
4447 /* elif after executed block, skip eval and wait for endif. */
4448 conditional_stack_poke(st->cstack, IFSTATE_IGNORED);
4449 return CSTATE_END_COMMAND;
4450 }
4451
4452 if (!evaluateExpr(st, expr, &result))
4453 {
4454 commandFailed(st, argv[0], "evaluation of meta-command failed");
4455 return CSTATE_ABORTED;
4456 }
4457
4458 cond = valueTruth(&result);
4459 Assert(conditional_stack_peek(st->cstack) == IFSTATE_FALSE);
4460 conditional_stack_poke(st->cstack, cond ? IFSTATE_TRUE : IFSTATE_FALSE);
4461 }
4462 else if (command->meta == META_ELSE)
4463 {
4464 switch (conditional_stack_peek(st->cstack))
4465 {
4466 case IFSTATE_TRUE:
4467 conditional_stack_poke(st->cstack, IFSTATE_ELSE_FALSE);
4468 break;
4469 case IFSTATE_FALSE: /* inconsistent if active */
4470 case IFSTATE_IGNORED: /* inconsistent if active */
4471 case IFSTATE_NONE: /* else without if */
4472 case IFSTATE_ELSE_TRUE: /* else after else */
4473 case IFSTATE_ELSE_FALSE: /* else after else */
4474 default:
4475 /* dead code if conditional check is ok */
4476 Assert(false);
4477 }
4478 }
4479 else if (command->meta == META_ENDIF)
4480 {
4481 Assert(!conditional_stack_empty(st->cstack));
4482 conditional_stack_pop(st->cstack);
4483 }
4484 else if (command->meta == META_SETSHELL)
4485 {
4486 if (!runShellCommand(&st->variables, argv[1], argv + 2, argc - 2))
4487 {
4488 commandFailed(st, "setshell", "execution of meta-command failed");
4489 return CSTATE_ABORTED;
4490 }
4491 }
4492 else if (command->meta == META_SHELL)
4493 {
4494 if (!runShellCommand(&st->variables, NULL, argv + 1, argc - 1))
4495 {
4496 commandFailed(st, "shell", "execution of meta-command failed");
4497 return CSTATE_ABORTED;
4498 }
4499 }
4500 else if (command->meta == META_STARTPIPELINE)
4501 {
4502 /*
4503 * In pipeline mode, we use a workflow based on libpq pipeline
4504 * functions.
4505 */
4506 if (querymode == QUERY_SIMPLE)
4507 {
4508 commandFailed(st, "startpipeline", "cannot use pipeline mode with the simple query protocol");
4509 return CSTATE_ABORTED;
4510 }
4511
4512 /*
4513 * If we're in prepared-query mode, we need to prepare all the
4514 * commands that are inside the pipeline before we actually start the
4515 * pipeline itself. This solves the problem that running BEGIN
4516 * ISOLATION LEVEL SERIALIZABLE in a pipeline would fail due to a
4517 * snapshot having been acquired by the prepare within the pipeline.
4518 */
4519 if (querymode == QUERY_PREPARED)
4520 prepareCommandsInPipeline(st);
4521
4522 if (PQpipelineStatus(st->con) != PQ_PIPELINE_OFF)
4523 {
4524 commandFailed(st, "startpipeline", "already in pipeline mode");
4525 return CSTATE_ABORTED;
4526 }
4527 if (PQenterPipelineMode(st->con) == 0)
4528 {
4529 commandFailed(st, "startpipeline", "failed to enter pipeline mode");
4530 return CSTATE_ABORTED;
4531 }
4532 }
4533 else if (command->meta == META_SYNCPIPELINE)
4534 {
4535 if (PQpipelineStatus(st->con) != PQ_PIPELINE_ON)
4536 {
4537 commandFailed(st, "syncpipeline", "not in pipeline mode");
4538 return CSTATE_ABORTED;
4539 }
4540 if (PQsendPipelineSync(st->con) == 0)
4541 {
4542 commandFailed(st, "syncpipeline", "failed to send a pipeline sync");
4543 return CSTATE_ABORTED;
4544 }
4545 st->num_syncs++;
4546 }
4547 else if (command->meta == META_ENDPIPELINE)
4548 {
4549 if (PQpipelineStatus(st->con) != PQ_PIPELINE_ON)
4550 {
4551 commandFailed(st, "endpipeline", "not in pipeline mode");
4552 return CSTATE_ABORTED;
4553 }
4554 if (!PQpipelineSync(st->con))
4555 {
4556 commandFailed(st, "endpipeline", "failed to send a pipeline sync");
4557 return CSTATE_ABORTED;
4558 }
4559 st->num_syncs++;
4560 /* Now wait for the PGRES_PIPELINE_SYNC and exit pipeline mode there */
4561 /* collect pending results before getting out of pipeline mode */
4562 return CSTATE_WAIT_RESULT;
4563 }
4564
4565 /*
4566 * executing the expression or shell command might have taken a
4567 * non-negligible amount of time, so reset 'now'
4568 */
4569 *now = 0;
4570
4571 return CSTATE_END_COMMAND;
4572 }
4573
4574 /*
4575 * Return the number of failed transactions.
4576 */
4577 static int64
4578 getFailures(const StatsData *stats)
4579 {
4580 return (stats->serialization_failures +
4581 stats->deadlock_failures);
4582 }
4583
4584 /*
4585 * Return a string constant representing the result of a transaction
4586 * that is not successfully processed.
4587 */
4588 static const char *
4589 getResultString(bool skipped, EStatus estatus)
4590 {
4591 if (skipped)
4592 return "skipped";
4593 else if (failures_detailed)
4594 {
4595 switch (estatus)
4596 {
4597 case ESTATUS_SERIALIZATION_ERROR:
4598 return "serialization";
4599 case ESTATUS_DEADLOCK_ERROR:
4600 return "deadlock";
4601 default:
4602 /* internal error which should never occur */
4603 pg_fatal("unexpected error status: %d", estatus);
4604 }
4605 }
4606 else
4607 return "failed";
4608 }
4609
4610 /*
4611 * Print log entry after completing one transaction.
4612 *
4613 * We print Unix-epoch timestamps in the log, so that entries can be
4614 * correlated against other logs.
4615 *
4616 * XXX We could obtain the time from the caller and just shift it here, to
4617 * avoid the cost of an extra call to pg_time_now().
4618 */
4619 static void
4620 doLog(TState *thread, CState *st,
4621 StatsData *agg, bool skipped, double latency, double lag)
4622 {
4623 FILE *logfile = thread->logfile;
4624 pg_time_usec_t now = pg_time_now() + epoch_shift;
4625
4626 Assert(use_log);
4627
4628 /*
4629 * Skip the log entry if sampling is enabled and this row doesn't belong
4630 * to the random sample.
4631 */
4632 if (sample_rate != 0.0 &&
4633 pg_prng_double(&thread->ts_sample_rs) > sample_rate)
4634 return;
4635
4636 /* should we aggregate the results or not? */
4637 if (agg_interval > 0)
4638 {
4639 pg_time_usec_t next;
4640
4641 /*
4642 * Loop until we reach the interval of the current moment, and print
4643 * any empty intervals in between (this may happen with very low tps,
4644 * e.g. --rate=0.1).
4645 */
4646
4647 while ((next = agg->start_time + agg_interval * INT64CONST(1000000)) <= now)
4648 {
4649 double lag_sum = 0.0;
4650 double lag_sum2 = 0.0;
4651 double lag_min = 0.0;
4652 double lag_max = 0.0;
4653 int64 skipped = 0;
4654 int64 serialization_failures = 0;
4655 int64 deadlock_failures = 0;
4656 int64 retried = 0;
4657 int64 retries = 0;
4658
4659 /* print aggregated report to logfile */
4660 fprintf(logfile, INT64_FORMAT " " INT64_FORMAT " %.0f %.0f %.0f %.0f",
4661 agg->start_time / 1000000, /* seconds since Unix epoch */
4662 agg->cnt,
4663 agg->latency.sum,
4664 agg->latency.sum2,
4665 agg->latency.min,
4666 agg->latency.max);
4667
4668 if (throttle_delay)
4669 {
4670 lag_sum = agg->lag.sum;
4671 lag_sum2 = agg->lag.sum2;
4672 lag_min = agg->lag.min;
4673 lag_max = agg->lag.max;
4674 }
4675 fprintf(logfile, " %.0f %.0f %.0f %.0f",
4676 lag_sum,
4677 lag_sum2,
4678 lag_min,
4679 lag_max);
4680
4681 if (latency_limit)
4682 skipped = agg->skipped;
4683 fprintf(logfile, " " INT64_FORMAT, skipped);
4684
4685 if (max_tries != 1)
4686 {
4687 retried = agg->retried;
4688 retries = agg->retries;
4689 }
4690 fprintf(logfile, " " INT64_FORMAT " " INT64_FORMAT, retried, retries);
4691
4692 if (failures_detailed)
4693 {
4694 serialization_failures = agg->serialization_failures;
4695 deadlock_failures = agg->deadlock_failures;
4696 }
4697 fprintf(logfile, " " INT64_FORMAT " " INT64_FORMAT,
4698 serialization_failures,
4699 deadlock_failures);
4700
4701 fputc('\n', logfile);
4702
4703 /* reset data and move to next interval */
4704 initStats(agg, next);
4705 }
4706
4707 /* accumulate the current transaction */
4708 accumStats(agg, skipped, latency, lag, st->estatus, st->tries);
4709 }
4710 else
4711 {
4712 /* no, print raw transactions */
4713 if (!skipped && st->estatus == ESTATUS_NO_ERROR)
4714 fprintf(logfile, "%d " INT64_FORMAT " %.0f %d " INT64_FORMAT " "
4715 INT64_FORMAT,
4716 st->id, st->cnt, latency, st->use_file,
4717 now / 1000000, now % 1000000);
4718 else
4719 fprintf(logfile, "%d " INT64_FORMAT " %s %d " INT64_FORMAT " "
4720 INT64_FORMAT,
4721 st->id, st->cnt, getResultString(skipped, st->estatus),
4722 st->use_file, now / 1000000, now % 1000000);
4723
4724 if (throttle_delay)
4725 fprintf(logfile, " %.0f", lag);
4726 if (max_tries != 1)
4727 fprintf(logfile, " %u", st->tries - 1);
4728 fputc('\n', logfile);
4729 }
4730 }
4731
4732 /*
4733 * Accumulate and report statistics at end of a transaction.
4734 *
4735 * (This is also called when a transaction is late and thus skipped.
4736 * Note that even skipped and failed transactions are counted in the CState
4737 * "cnt" field.)
4738 */
4739 static void
4740 processXactStats(TState *thread, CState *st, pg_time_usec_t *now,
4741 bool skipped, StatsData *agg)
4742 {
4743 double latency = 0.0,
4744 lag = 0.0;
4745 bool detailed = progress || throttle_delay || latency_limit ||
4746 use_log || per_script_stats;
4747
4748 if (detailed && !skipped && st->estatus == ESTATUS_NO_ERROR)
4749 {
4750 pg_time_now_lazy(now);
4751
4752 /* compute latency & lag */
4753 latency = (*now) - st->txn_scheduled;
4754 lag = st->txn_begin - st->txn_scheduled;
4755 }
4756
4757 /* keep detailed thread stats */
4758 accumStats(&thread->stats, skipped, latency, lag, st->estatus, st->tries);
4759
4760 /* count transactions over the latency limit, if needed */
4761 if (latency_limit && latency > latency_limit)
4762 thread->latency_late++;
4763
4764 /* client stat is just counting */
4765 st->cnt++;
4766
4767 if (use_log)
4768 doLog(thread, st, agg, skipped, latency, lag);
4769
4770 /* XXX could use a mutex here, but we choose not to */
4771 if (per_script_stats)
4772 accumStats(&sql_script[st->use_file].stats, skipped, latency, lag,
4773 st->estatus, st->tries);
4774 }
4775
4776
4777 /* discard connections */
4778 static void
4779 disconnect_all(CState *state, int length)
4780 {
4781 int i;
4782
4783 for (i = 0; i < length; i++)
4784 finishCon(&state[i]);
4785 }
4786
4787 /*
4788 * Remove old pgbench tables, if any exist
4789 */
4790 static void
4791 initDropTables(PGconn *con)
4792 {
4793 fprintf(stderr, "dropping old tables...\n");
4794
4795 /*
4796 * We drop all the tables in one command, so that whether there are
4797 * foreign key dependencies or not doesn't matter.
4798 */
4799 executeStatement(con, "drop table if exists "
4800 "pgbench_accounts, "
4801 "pgbench_branches, "
4802 "pgbench_history, "
4803 "pgbench_tellers");
4804 }
4805
4806 /*
4807 * Create "pgbench_accounts" partitions if needed.
4808 *
4809 * This is the larger table of pgbench default tpc-b like schema
4810 * with a known size, so we choose to partition it.
4811 */
4812 static void
4813 createPartitions(PGconn *con)
4814 {
4815 PQExpBufferData query;
4816
4817 /* we must have to create some partitions */
4818 Assert(partitions > 0);
4819
4820 fprintf(stderr, "creating %d partitions...\n", partitions);
4821
4822 initPQExpBuffer(&query);
4823
4824 for (int p = 1; p <= partitions; p++)
4825 {
4826 if (partition_method == PART_RANGE)
4827 {
4828 int64 part_size = (naccounts * (int64) scale + partitions - 1) / partitions;
4829
4830 printfPQExpBuffer(&query,
4831 "create%s table pgbench_accounts_%d\n"
4832 " partition of pgbench_accounts\n"
4833 " for values from (",
4834 unlogged_tables ? " unlogged" : "", p);
4835
4836 /*
4837 * For RANGE, we use open-ended partitions at the beginning and
4838 * end to allow any valid value for the primary key. Although the
4839 * actual minimum and maximum values can be derived from the
4840 * scale, it is more generic and the performance is better.
4841 */
4842 if (p == 1)
4843 appendPQExpBufferStr(&query, "minvalue");
4844 else
4845 appendPQExpBuffer(&query, INT64_FORMAT, (p - 1) * part_size + 1);
4846
4847 appendPQExpBufferStr(&query, ") to (");
4848
4849 if (p < partitions)
4850 appendPQExpBuffer(&query, INT64_FORMAT, p * part_size + 1);
4851 else
4852 appendPQExpBufferStr(&query, "maxvalue");
4853
4854 appendPQExpBufferChar(&query, ')');
4855 }
4856 else if (partition_method == PART_HASH)
4857 printfPQExpBuffer(&query,
4858 "create%s table pgbench_accounts_%d\n"
4859 " partition of pgbench_accounts\n"
4860 " for values with (modulus %d, remainder %d)",
4861 unlogged_tables ? " unlogged" : "", p,
4862 partitions, p - 1);
4863 else /* cannot get there */
4864 Assert(0);
4865
4866 /*
4867 * Per ddlinfo in initCreateTables, fillfactor is needed on table
4868 * pgbench_accounts.
4869 */
4870 appendPQExpBuffer(&query, " with (fillfactor=%d)", fillfactor);
4871
4872 executeStatement(con, query.data);
4873 }
4874
4875 termPQExpBuffer(&query);
4876 }
4877
4878 /*
4879 * Create pgbench's standard tables
4880 */
4881 static void
4882 initCreateTables(PGconn *con)
4883 {
4884 /*
4885 * Note: TPC-B requires at least 100 bytes per row, and the "filler"
4886 * fields in these table declarations were intended to comply with that.
4887 * The pgbench_accounts table complies with that because the "filler"
4888 * column is set to blank-padded empty string. But for all other tables
4889 * the columns default to NULL and so don't actually take any space. We
4890 * could fix that by giving them non-null default values. However, that
4891 * would completely break comparability of pgbench results with prior
4892 * versions. Since pgbench has never pretended to be fully TPC-B compliant
4893 * anyway, we stick with the historical behavior.
4894 */
4895 struct ddlinfo
4896 {
4897 const char *table; /* table name */
4898 const char *smcols; /* column decls if accountIDs are 32 bits */
4899 const char *bigcols; /* column decls if accountIDs are 64 bits */
4900 int declare_fillfactor;
4901 };
4902 static const struct ddlinfo DDLs[] = {
4903 {
4904 "pgbench_history",
4905 "tid int,bid int,aid int,delta int,mtime timestamp,filler char(22)",
4906 "tid int,bid int,aid bigint,delta int,mtime timestamp,filler char(22)",
4907 0
4908 },
4909 {
4910 "pgbench_tellers",
4911 "tid int not null,bid int,tbalance int,filler char(84)",
4912 "tid int not null,bid int,tbalance int,filler char(84)",
4913 1
4914 },
4915 {
4916 "pgbench_accounts",
4917 "aid int not null,bid int,abalance int,filler char(84)",
4918 "aid bigint not null,bid int,abalance int,filler char(84)",
4919 1
4920 },
4921 {
4922 "pgbench_branches",
4923 "bid int not null,bbalance int,filler char(88)",
4924 "bid int not null,bbalance int,filler char(88)",
4925 1
4926 }
4927 };
4928 int i;
4929 PQExpBufferData query;
4930
4931 fprintf(stderr, "creating tables...\n");
4932
4933 initPQExpBuffer(&query);
4934
4935 for (i = 0; i < lengthof(DDLs); i++)
4936 {
4937 const struct ddlinfo *ddl = &DDLs[i];
4938
4939 /* Construct new create table statement. */
4940 printfPQExpBuffer(&query, "create%s table %s(%s)",
4941 (unlogged_tables && partition_method == PART_NONE) ? " unlogged" : "",
4942 ddl->table,
4943 (scale >= SCALE_32BIT_THRESHOLD) ? ddl->bigcols : ddl->smcols);
4944
4945 /* Partition pgbench_accounts table */
4946 if (partition_method != PART_NONE && strcmp(ddl->table, "pgbench_accounts") == 0)
4947 appendPQExpBuffer(&query,
4948 " partition by %s (aid)", PARTITION_METHOD[partition_method]);
4949 else if (ddl->declare_fillfactor)
4950 {
4951 /* fillfactor is only expected on actual tables */
4952 appendPQExpBuffer(&query, " with (fillfactor=%d)", fillfactor);
4953 }
4954
4955 if (tablespace != NULL)
4956 {
4957 char *escape_tablespace;
4958
4959 escape_tablespace = PQescapeIdentifier(con, tablespace, strlen(tablespace));
4960 appendPQExpBuffer(&query, " tablespace %s", escape_tablespace);
4961 PQfreemem(escape_tablespace);
4962 }
4963
4964 executeStatement(con, query.data);
4965 }
4966
4967 termPQExpBuffer(&query);
4968
4969 if (partition_method != PART_NONE)
4970 createPartitions(con);
4971 }
4972
4973 /*
4974 * Truncate away any old data, in one command in case there are foreign keys
4975 */
4976 static void
4977 initTruncateTables(PGconn *con)
4978 {
4979 executeStatement(con, "truncate table "
4980 "pgbench_accounts, "
4981 "pgbench_branches, "
4982 "pgbench_history, "
4983 "pgbench_tellers");
4984 }
4985
4986 static void
4987 initBranch(PQExpBufferData *sql, int64 curr)
4988 {
4989 /* "filler" column uses NULL */
4990 printfPQExpBuffer(sql,
4991 INT64_FORMAT "\t0\t\\N\n",
4992 curr + 1);
4993 }
4994
4995 static void
4996 initTeller(PQExpBufferData *sql, int64 curr)
4997 {
4998 /* "filler" column uses NULL */
4999 printfPQExpBuffer(sql,
5000 INT64_FORMAT "\t" INT64_FORMAT "\t0\t\\N\n",
5001 curr + 1, curr / ntellers + 1);
5002 }
5003
5004 static void
5005 initAccount(PQExpBufferData *sql, int64 curr)
5006 {
5007 /* "filler" column defaults to blank padded empty string */
5008 printfPQExpBuffer(sql,
5009 INT64_FORMAT "\t" INT64_FORMAT "\t0\t\n",
5010 curr + 1, curr / naccounts + 1);
5011 }
5012
5013 static void
5014 initPopulateTable(PGconn *con, const char *table, int64 base,
5015 initRowMethod init_row)
5016 {
5017 int n;
5018 int64 k;
5019 int chars = 0;
5020 int prev_chars = 0;
5021 PGresult *res;
5022 PQExpBufferData sql;
5023 char copy_statement[256];
5024 const char *copy_statement_fmt = "copy %s from stdin";
5025 int64 total = base * scale;
5026
5027 /* used to track elapsed time and estimate of the remaining time */
5028 pg_time_usec_t start;
5029 int log_interval = 1;
5030
5031 /* Stay on the same line if reporting to a terminal */
5032 char eol = isatty(fileno(stderr)) ? '\r' : '\n';
5033
5034 initPQExpBuffer(&sql);
5035
5036 /* Use COPY with FREEZE on v14 and later for all ordinary tables */
5037 if ((PQserverVersion(con) >= 140000) &&
5038 get_table_relkind(con, table) == RELKIND_RELATION)
5039 copy_statement_fmt = "copy %s from stdin with (freeze on)";
5040
5041
5042 n = pg_snprintf(copy_statement, sizeof(copy_statement), copy_statement_fmt, table);
5043 if (n >= sizeof(copy_statement))
5044 pg_fatal("invalid buffer size: must be at least %d characters long", n);
5045 else if (n == -1)
5046 pg_fatal("invalid format string");
5047
5048 res = PQexec(con, copy_statement);
5049
5050 if (PQresultStatus(res) != PGRES_COPY_IN)
5051 pg_fatal("unexpected copy in result: %s", PQerrorMessage(con));
5052 PQclear(res);
5053
5054 start = pg_time_now();
5055
5056 for (k = 0; k < total; k++)
5057 {
5058 int64 j = k + 1;
5059
5060 init_row(&sql, k);
5061 if (PQputline(con, sql.data))
5062 pg_fatal("PQputline failed");
5063
5064 if (CancelRequested)
5065 break;
5066
5067 /*
5068 * If we want to stick with the original logging, print a message each
5069 * 100k inserted rows.
5070 */
5071 if ((!use_quiet) && (j % 100000 == 0))
5072 {
5073 double elapsed_sec = PG_TIME_GET_DOUBLE(pg_time_now() - start);
5074 double remaining_sec = ((double) total - j) * elapsed_sec / j;
5075
5076 chars = fprintf(stderr, INT64_FORMAT " of " INT64_FORMAT " tuples (%d%%) of %s done (elapsed %.2f s, remaining %.2f s)",
5077 j, total,
5078 (int) ((j * 100) / total),
5079 table, elapsed_sec, remaining_sec);
5080
5081 /*
5082 * If the previous progress message is longer than the current
5083 * one, add spaces to the current line to fully overwrite any
5084 * remaining characters from the previous message.
5085 */
5086 if (prev_chars > chars)
5087 fprintf(stderr, "%*c", prev_chars - chars, ' ');
5088 fputc(eol, stderr);
5089 prev_chars = chars;
5090 }
5091 /* let's not call the timing for each row, but only each 100 rows */
5092 else if (use_quiet && (j % 100 == 0))
5093 {
5094 double elapsed_sec = PG_TIME_GET_DOUBLE(pg_time_now() - start);
5095 double remaining_sec = ((double) total - j) * elapsed_sec / j;
5096
5097 /* have we reached the next interval (or end)? */
5098 if ((j == total) || (elapsed_sec >= log_interval * LOG_STEP_SECONDS))
5099 {
5100 chars = fprintf(stderr, INT64_FORMAT " of " INT64_FORMAT " tuples (%d%%) of %s done (elapsed %.2f s, remaining %.2f s)",
5101 j, total,
5102 (int) ((j * 100) / total),
5103 table, elapsed_sec, remaining_sec);
5104
5105 /*
5106 * If the previous progress message is longer than the current
5107 * one, add spaces to the current line to fully overwrite any
5108 * remaining characters from the previous message.
5109 */
5110 if (prev_chars > chars)
5111 fprintf(stderr, "%*c", prev_chars - chars, ' ');
5112 fputc(eol, stderr);
5113 prev_chars = chars;
5114
5115 /* skip to the next interval */
5116 log_interval = (int) ceil(elapsed_sec / LOG_STEP_SECONDS);
5117 }
5118 }
5119 }
5120
5121 if (chars != 0 && eol != '\n')
5122 fprintf(stderr, "%*c\r", chars, ' '); /* Clear the current line */
5123
5124 if (PQputline(con, "\\.\n"))
5125 pg_fatal("very last PQputline failed");
5126 if (PQendcopy(con))
5127 pg_fatal("PQendcopy failed");
5128
5129 termPQExpBuffer(&sql);
5130 }
5131
5132 /*
5133 * Fill the standard tables with some data generated and sent from the client.
5134 *
5135 * The filler column is NULL in pgbench_branches and pgbench_tellers, and is
5136 * a blank-padded string in pgbench_accounts.
5137 */
5138 static void
5139 initGenerateDataClientSide(PGconn *con)
5140 {
5141 fprintf(stderr, "generating data (client-side)...\n");
5142
5143 /*
5144 * we do all of this in one transaction to enable the backend's
5145 * data-loading optimizations
5146 */
5147 executeStatement(con, "begin");
5148
5149 /* truncate away any old data */
5150 initTruncateTables(con);
5151
5152 /*
5153 * fill branches, tellers, accounts in that order in case foreign keys
5154 * already exist
5155 */
5156 initPopulateTable(con, "pgbench_branches", nbranches, initBranch);
5157 initPopulateTable(con, "pgbench_tellers", ntellers, initTeller);
5158 initPopulateTable(con, "pgbench_accounts", naccounts, initAccount);
5159
5160 executeStatement(con, "commit");
5161 }
5162
5163 /*
5164 * Fill the standard tables with some data generated on the server
5165 *
5166 * As already the case with the client-side data generation, the filler
5167 * column defaults to NULL in pgbench_branches and pgbench_tellers,
5168 * and is a blank-padded string in pgbench_accounts.
5169 */
5170 static void
5171 initGenerateDataServerSide(PGconn *con)
5172 {
5173 PQExpBufferData sql;
5174
5175 fprintf(stderr, "generating data (server-side)...\n");
5176
5177 /*
5178 * we do all of this in one transaction to enable the backend's
5179 * data-loading optimizations
5180 */
5181 executeStatement(con, "begin");
5182
5183 /* truncate away any old data */
5184 initTruncateTables(con);
5185
5186 initPQExpBuffer(&sql);
5187
5188 printfPQExpBuffer(&sql,
5189 "insert into pgbench_branches(bid,bbalance) "
5190 "select bid, 0 "
5191 "from generate_series(1, %d) as bid", nbranches * scale);
5192 executeStatement(con, sql.data);
5193
5194 printfPQExpBuffer(&sql,
5195 "insert into pgbench_tellers(tid,bid,tbalance) "
5196 "select tid, (tid - 1) / %d + 1, 0 "
5197 "from generate_series(1, %d) as tid", ntellers, ntellers * scale);
5198 executeStatement(con, sql.data);
5199
5200 printfPQExpBuffer(&sql,
5201 "insert into pgbench_accounts(aid,bid,abalance,filler) "
5202 "select aid, (aid - 1) / %d + 1, 0, '' "
5203 "from generate_series(1, " INT64_FORMAT ") as aid",
5204 naccounts, (int64) naccounts * scale);
5205 executeStatement(con, sql.data);
5206
5207 termPQExpBuffer(&sql);
5208
5209 executeStatement(con, "commit");
5210 }
5211
5212 /*
5213 * Invoke vacuum on the standard tables
5214 */
5215 static void
5216 initVacuum(PGconn *con)
5217 {
5218 fprintf(stderr, "vacuuming...\n");
5219 executeStatement(con, "vacuum analyze pgbench_branches");
5220 executeStatement(con, "vacuum analyze pgbench_tellers");
5221 executeStatement(con, "vacuum analyze pgbench_accounts");
5222 executeStatement(con, "vacuum analyze pgbench_history");
5223 }
5224
5225 /*
5226 * Create primary keys on the standard tables
5227 */
5228 static void
5229 initCreatePKeys(PGconn *con)
5230 {
5231 static const char *const DDLINDEXes[] = {
5232 "alter table pgbench_branches add primary key (bid)",
5233 "alter table pgbench_tellers add primary key (tid)",
5234 "alter table pgbench_accounts add primary key (aid)"
5235 };
5236 int i;
5237 PQExpBufferData query;
5238
5239 fprintf(stderr, "creating primary keys...\n");
5240 initPQExpBuffer(&query);
5241
5242 for (i = 0; i < lengthof(DDLINDEXes); i++)
5243 {
5244 resetPQExpBuffer(&query);
5245 appendPQExpBufferStr(&query, DDLINDEXes[i]);
5246
5247 if (index_tablespace != NULL)
5248 {
5249 char *escape_tablespace;
5250
5251 escape_tablespace = PQescapeIdentifier(con, index_tablespace,
5252 strlen(index_tablespace));
5253 appendPQExpBuffer(&query, " using index tablespace %s", escape_tablespace);
5254 PQfreemem(escape_tablespace);
5255 }
5256
5257 executeStatement(con, query.data);
5258 }
5259
5260 termPQExpBuffer(&query);
5261 }
5262
5263 /*
5264 * Create foreign key constraints between the standard tables
5265 */
5266 static void
5267 initCreateFKeys(PGconn *con)
5268 {
5269 static const char *const DDLKEYs[] = {
5270 "alter table pgbench_tellers add constraint pgbench_tellers_bid_fkey foreign key (bid) references pgbench_branches",
5271 "alter table pgbench_accounts add constraint pgbench_accounts_bid_fkey foreign key (bid) references pgbench_branches",
5272 "alter table pgbench_history add constraint pgbench_history_bid_fkey foreign key (bid) references pgbench_branches",
5273 "alter table pgbench_history add constraint pgbench_history_tid_fkey foreign key (tid) references pgbench_tellers",
5274 "alter table pgbench_history add constraint pgbench_history_aid_fkey foreign key (aid) references pgbench_accounts"
5275 };
5276 int i;
5277
5278 fprintf(stderr, "creating foreign keys...\n");
5279 for (i = 0; i < lengthof(DDLKEYs); i++)
5280 {
5281 executeStatement(con, DDLKEYs[i]);
5282 }
5283 }
5284
5285 /*
5286 * Validate an initialization-steps string
5287 *
5288 * (We could just leave it to runInitSteps() to fail if there are wrong
5289 * characters, but since initialization can take awhile, it seems friendlier
5290 * to check during option parsing.)
5291 */
5292 static void
5293 checkInitSteps(const char *initialize_steps)
5294 {
5295 if (initialize_steps[0] == '\0')
5296 pg_fatal("no initialization steps specified");
5297
5298 for (const char *step = initialize_steps; *step != '\0'; step++)
5299 {
5300 if (strchr(ALL_INIT_STEPS " ", *step) == NULL)
5301 {
5302 pg_log_error("unrecognized initialization step \"%c\"", *step);
5303 pg_log_error_detail("Allowed step characters are: \"" ALL_INIT_STEPS "\".");
5304 exit(1);
5305 }
5306 }
5307 }
5308
5309 /*
5310 * Invoke each initialization step in the given string
5311 */
5312 static void
5313 runInitSteps(const char *initialize_steps)
5314 {
5315 PQExpBufferData stats;
5316 PGconn *con;
5317 const char *step;
5318 double run_time = 0.0;
5319 bool first = true;
5320
5321 initPQExpBuffer(&stats);
5322
5323 if ((con = doConnect()) == NULL)
5324 pg_fatal("could not create connection for initialization");
5325
5326 setup_cancel_handler(NULL);
5327 SetCancelConn(con);
5328
5329 for (step = initialize_steps; *step != '\0'; step++)
5330 {
5331 char *op = NULL;
5332 pg_time_usec_t start = pg_time_now();
5333
5334 switch (*step)
5335 {
5336 case 'd':
5337 op = "drop tables";
5338 initDropTables(con);
5339 break;
5340 case 't':
5341 op = "create tables";
5342 initCreateTables(con);
5343 break;
5344 case 'g':
5345 op = "client-side generate";
5346 initGenerateDataClientSide(con);
5347 break;
5348 case 'G':
5349 op = "server-side generate";
5350 initGenerateDataServerSide(con);
5351 break;
5352 case 'v':
5353 op = "vacuum";
5354 initVacuum(con);
5355 break;
5356 case 'p':
5357 op = "primary keys";
5358 initCreatePKeys(con);
5359 break;
5360 case 'f':
5361 op = "foreign keys";
5362 initCreateFKeys(con);
5363 break;
5364 case ' ':
5365 break; /* ignore */
5366 default:
5367 pg_log_error("unrecognized initialization step \"%c\"", *step);
5368 PQfinish(con);
5369 exit(1);
5370 }
5371
5372 if (op != NULL)
5373 {
5374 double elapsed_sec = PG_TIME_GET_DOUBLE(pg_time_now() - start);
5375
5376 if (!first)
5377 appendPQExpBufferStr(&stats, ", ");
5378 else
5379 first = false;
5380
5381 appendPQExpBuffer(&stats, "%s %.2f s", op, elapsed_sec);
5382
5383 run_time += elapsed_sec;
5384 }
5385 }
5386
5387 fprintf(stderr, "done in %.2f s (%s).\n", run_time, stats.data);
5388 ResetCancelConn();
5389 PQfinish(con);
5390 termPQExpBuffer(&stats);
5391 }
5392
5393 /*
5394 * Extract pgbench table information into global variables scale,
5395 * partition_method and partitions.
5396 */
5397 static void
5398 GetTableInfo(PGconn *con, bool scale_given)
5399 {
5400 PGresult *res;
5401
5402 /*
5403 * get the scaling factor that should be same as count(*) from
5404 * pgbench_branches if this is not a custom query
5405 */
5406 res = PQexec(con, "select count(*) from pgbench_branches");
5407 if (PQresultStatus(res) != PGRES_TUPLES_OK)
5408 {
5409 char *sqlState = PQresultErrorField(res, PG_DIAG_SQLSTATE);
5410
5411 pg_log_error("could not count number of branches: %s", PQerrorMessage(con));
5412
5413 if (sqlState && strcmp(sqlState, ERRCODE_UNDEFINED_TABLE) == 0)
5414 pg_log_error_hint("Perhaps you need to do initialization (\"pgbench -i\") in database \"%s\".",
5415 PQdb(con));
5416
5417 exit(1);
5418 }
5419 scale = atoi(PQgetvalue(res, 0, 0));
5420 if (scale < 0)
5421 pg_fatal("invalid count(*) from pgbench_branches: \"%s\"",
5422 PQgetvalue(res, 0, 0));
5423 PQclear(res);
5424
5425 /* warn if we override user-given -s switch */
5426 if (scale_given)
5427 pg_log_warning("scale option ignored, using count from pgbench_branches table (%d)",
5428 scale);
5429
5430 /*
5431 * Get the partition information for the first "pgbench_accounts" table
5432 * found in search_path.
5433 *
5434 * The result is empty if no "pgbench_accounts" is found.
5435 *
5436 * Otherwise, it always returns one row even if the table is not
5437 * partitioned (in which case the partition strategy is NULL).
5438 *
5439 * The number of partitions can be 0 even for partitioned tables, if no
5440 * partition is attached.
5441 *
5442 * We assume no partitioning on any failure, so as to avoid failing on an
5443 * old version without "pg_partitioned_table".
5444 */
5445 res = PQexec(con,
5446 "select o.n, p.partstrat, pg_catalog.count(i.inhparent) "
5447 "from pg_catalog.pg_class as c "
5448 "join pg_catalog.pg_namespace as n on (n.oid = c.relnamespace) "
5449 "cross join lateral (select pg_catalog.array_position(pg_catalog.current_schemas(true), n.nspname)) as o(n) "
5450 "left join pg_catalog.pg_partitioned_table as p on (p.partrelid = c.oid) "
5451 "left join pg_catalog.pg_inherits as i on (c.oid = i.inhparent) "
5452 "where c.relname = 'pgbench_accounts' and o.n is not null "
5453 "group by 1, 2 "
5454 "order by 1 asc "
5455 "limit 1");
5456
5457 if (PQresultStatus(res) != PGRES_TUPLES_OK)
5458 {
5459 /* probably an older version, coldly assume no partitioning */
5460 partition_method = PART_NONE;
5461 partitions = 0;
5462 }
5463 else if (PQntuples(res) == 0)
5464 {
5465 /*
5466 * This case is unlikely as pgbench already found "pgbench_branches"
5467 * above to compute the scale.
5468 */
5469 pg_log_error("no pgbench_accounts table found in \"search_path\"");
5470 pg_log_error_hint("Perhaps you need to do initialization (\"pgbench -i\") in database \"%s\".", PQdb(con));
5471 exit(1);
5472 }
5473 else /* PQntuples(res) == 1 */
5474 {
5475 /* normal case, extract partition information */
5476 if (PQgetisnull(res, 0, 1))
5477 partition_method = PART_NONE;
5478 else
5479 {
5480 char *ps = PQgetvalue(res, 0, 1);
5481
5482 /* column must be there */
5483 Assert(ps != NULL);
5484
5485 if (strcmp(ps, "r") == 0)
5486 partition_method = PART_RANGE;
5487 else if (strcmp(ps, "h") == 0)
5488 partition_method = PART_HASH;
5489 else
5490 {
5491 /* possibly a newer version with new partition method */
5492 pg_fatal("unexpected partition method: \"%s\"", ps);
5493 }
5494 }
5495
5496 partitions = atoi(PQgetvalue(res, 0, 2));
5497 }
5498
5499 PQclear(res);
5500 }
5501
5502 /*
5503 * Replace :param with $n throughout the command's SQL text, which
5504 * is a modifiable string in cmd->lines.
5505 */
5506 static bool
5507 parseQuery(Command *cmd)
5508 {
5509 char *sql,
5510 *p;
5511
5512 cmd->argc = 1;
5513
5514 p = sql = pg_strdup(cmd->lines.data);
5515 while ((p = strchr(p, ':')) != NULL)
5516 {
5517 char var[13];
5518 char *name;
5519 int eaten;
5520
5521 name = parseVariable(p, &eaten);
5522 if (name == NULL)
5523 {
5524 while (*p == ':')
5525 {
5526 p++;
5527 }
5528 continue;
5529 }
5530
5531 /*
5532 * cmd->argv[0] is the SQL statement itself, so the max number of
5533 * arguments is one less than MAX_ARGS
5534 */
5535 if (cmd->argc >= MAX_ARGS)
5536 {
5537 pg_log_error("statement has too many arguments (maximum is %d): %s",
5538 MAX_ARGS - 1, cmd->lines.data);
5539 pg_free(name);
5540 return false;
5541 }
5542
5543 sprintf(var, "$%d", cmd->argc);
5544 p = replaceVariable(&sql, p, eaten, var);
5545
5546 cmd->argv[cmd->argc] = name;
5547 cmd->argc++;
5548 }
5549
5550 Assert(cmd->argv[0] == NULL);
5551 cmd->argv[0] = sql;
5552 return true;
5553 }
5554
5555 /*
5556 * syntax error while parsing a script (in practice, while parsing a
5557 * backslash command, because we don't detect syntax errors in SQL)
5558 *
5559 * source: source of script (filename or builtin-script ID)
5560 * lineno: line number within script (count from 1)
5561 * line: whole line of backslash command, if available
5562 * command: backslash command name, if available
5563 * msg: the actual error message
5564 * more: optional extra message
5565 * column: zero-based column number, or -1 if unknown
5566 */
5567 void
5568 syntax_error(const char *source, int lineno,
5569 const char *line, const char *command,
5570 const char *msg, const char *more, int column)
5571 {
5572 PQExpBufferData buf;
5573
5574 initPQExpBuffer(&buf);
5575
5576 printfPQExpBuffer(&buf, "%s:%d: %s", source, lineno, msg);
5577 if (more != NULL)
5578 appendPQExpBuffer(&buf, " (%s)", more);
5579 if (column >= 0 && line == NULL)
5580 appendPQExpBuffer(&buf, " at column %d", column + 1);
5581 if (command != NULL)
5582 appendPQExpBuffer(&buf, " in command \"%s\"", command);
5583
5584 pg_log_error("%s", buf.data);
5585
5586 termPQExpBuffer(&buf);
5587
5588 if (line != NULL)
5589 {
5590 fprintf(stderr, "%s\n", line);
5591 if (column >= 0)
5592 fprintf(stderr, "%*c error found here\n", column + 1, '^');
5593 }
5594
5595 exit(1);
5596 }
5597
5598 /*
5599 * Return a pointer to the start of the SQL command, after skipping over
5600 * whitespace and "--" comments.
5601 * If the end of the string is reached, return NULL.
5602 */
5603 static char *
5604 skip_sql_comments(char *sql_command)
5605 {
5606 char *p = sql_command;
5607
5608 /* Skip any leading whitespace, as well as "--" style comments */
5609 for (;;)
5610 {
5611 if (isspace((unsigned char) *p))
5612 p++;
5613 else if (strncmp(p, "--", 2) == 0)
5614 {
5615 p = strchr(p, '\n');
5616 if (p == NULL)
5617 return NULL;
5618 p++;
5619 }
5620 else
5621 break;
5622 }
5623
5624 /* NULL if there's nothing but whitespace and comments */
5625 if (*p == '\0')
5626 return NULL;
5627
5628 return p;
5629 }
5630
5631 /*
5632 * Parse a SQL command; return a Command struct, or NULL if it's a comment
5633 *
5634 * On entry, psqlscan.l has collected the command into "buf", so we don't
5635 * really need to do much here except check for comments and set up a Command
5636 * struct.
5637 */
5638 static Command *
5639 create_sql_command(PQExpBuffer buf, const char *source)
5640 {
5641 Command *my_command;
5642 char *p = skip_sql_comments(buf->data);
5643
5644 if (p == NULL)
5645 return NULL;
5646
5647 /* Allocate and initialize Command structure */
5648 my_command = (Command *) pg_malloc(sizeof(Command));
5649 initPQExpBuffer(&my_command->lines);
5650 appendPQExpBufferStr(&my_command->lines, p);
5651 my_command->first_line = NULL; /* this is set later */
5652 my_command->type = SQL_COMMAND;
5653 my_command->meta = META_NONE;
5654 my_command->argc = 0;
5655 my_command->retries = 0;
5656 my_command->failures = 0;
5657 memset(my_command->argv, 0, sizeof(my_command->argv));
5658 my_command->varprefix = NULL; /* allocated later, if needed */
5659 my_command->expr = NULL;
5660 initSimpleStats(&my_command->stats);
5661 my_command->prepname = NULL; /* set later, if needed */
5662
5663 return my_command;
5664 }
5665
5666 /* Free a Command structure and associated data */
5667 static void
5668 free_command(Command *command)
5669 {
5670 termPQExpBuffer(&command->lines);
5671 pg_free(command->first_line);
5672 for (int i = 0; i < command->argc; i++)
5673 pg_free(command->argv[i]);
5674 pg_free(command->varprefix);
5675
5676 /*
5677 * It should also free expr recursively, but this is currently not needed
5678 * as only gset commands (which do not have an expression) are freed.
5679 */
5680 pg_free(command);
5681 }
5682
5683 /*
5684 * Once an SQL command is fully parsed, possibly by accumulating several
5685 * parts, complete other fields of the Command structure.
5686 */
5687 static void
5688 postprocess_sql_command(Command *my_command)
5689 {
5690 char buffer[128];
5691 static int prepnum = 0;
5692
5693 Assert(my_command->type == SQL_COMMAND);
5694
5695 /* Save the first line for error display. */
5696 strlcpy(buffer, my_command->lines.data, sizeof(buffer));
5697 buffer[strcspn(buffer, "\n\r")] = '\0';
5698 my_command->first_line = pg_strdup(buffer);
5699
5700 /* Parse query and generate prepared statement name, if necessary */
5701 switch (querymode)
5702 {
5703 case QUERY_SIMPLE:
5704 my_command->argv[0] = my_command->lines.data;
5705 my_command->argc++;
5706 break;
5707 case QUERY_PREPARED:
5708 my_command->prepname = psprintf("P_%d", prepnum++);
5709 /* fall through */
5710 case QUERY_EXTENDED:
5711 if (!parseQuery(my_command))
5712 exit(1);
5713 break;
5714 default:
5715 exit(1);
5716 }
5717 }
5718
5719 /*
5720 * Parse a backslash command; return a Command struct, or NULL if comment
5721 *
5722 * At call, we have scanned only the initial backslash.
5723 */
5724 static Command *
5725 process_backslash_command(PsqlScanState sstate, const char *source,
5726 int lineno, int start_offset)
5727 {
5728 Command *my_command;
5729 PQExpBufferData word_buf;
5730 int word_offset;
5731 int offsets[MAX_ARGS]; /* offsets of argument words */
5732 int j;
5733
5734 initPQExpBuffer(&word_buf);
5735
5736 /* Collect first word of command */
5737 if (!expr_lex_one_word(sstate, &word_buf, &word_offset))
5738 {
5739 termPQExpBuffer(&word_buf);
5740 return NULL;
5741 }
5742
5743 /* Allocate and initialize Command structure */
5744 my_command = (Command *) pg_malloc0(sizeof(Command));
5745 my_command->type = META_COMMAND;
5746 my_command->argc = 0;
5747 initSimpleStats(&my_command->stats);
5748
5749 /* Save first word (command name) */
5750 j = 0;
5751 offsets[j] = word_offset;
5752 my_command->argv[j++] = pg_strdup(word_buf.data);
5753 my_command->argc++;
5754
5755 /* ... and convert it to enum form */
5756 my_command->meta = getMetaCommand(my_command->argv[0]);
5757
5758 if (my_command->meta == META_SET ||
5759 my_command->meta == META_IF ||
5760 my_command->meta == META_ELIF)
5761 {
5762 yyscan_t yyscanner;
5763
5764 /* For \set, collect var name */
5765 if (my_command->meta == META_SET)
5766 {
5767 if (!expr_lex_one_word(sstate, &word_buf, &word_offset))
5768 syntax_error(source, lineno, my_command->first_line, my_command->argv[0],
5769 "missing argument", NULL, -1);
5770
5771 offsets[j] = word_offset;
5772 my_command->argv[j++] = pg_strdup(word_buf.data);
5773 my_command->argc++;
5774 }
5775
5776 /* then for all parse the expression */
5777 yyscanner = expr_scanner_init(sstate, source, lineno, start_offset,
5778 my_command->argv[0]);
5779
5780 if (expr_yyparse(&my_command->expr, yyscanner) != 0)
5781 {
5782 /* dead code: exit done from syntax_error called by yyerror */
5783 exit(1);
5784 }
5785
5786 /* Save line, trimming any trailing newline */
5787 my_command->first_line =
5788 expr_scanner_get_substring(sstate,
5789 start_offset,
5790 true);
5791
5792 expr_scanner_finish(yyscanner);
5793
5794 termPQExpBuffer(&word_buf);
5795
5796 return my_command;
5797 }
5798
5799 /* For all other commands, collect remaining words. */
5800 while (expr_lex_one_word(sstate, &word_buf, &word_offset))
5801 {
5802 /*
5803 * my_command->argv[0] is the command itself, so the max number of
5804 * arguments is one less than MAX_ARGS
5805 */
5806 if (j >= MAX_ARGS)
5807 syntax_error(source, lineno, my_command->first_line, my_command->argv[0],
5808 "too many arguments", NULL, -1);
5809
5810 offsets[j] = word_offset;
5811 my_command->argv[j++] = pg_strdup(word_buf.data);
5812 my_command->argc++;
5813 }
5814
5815 /* Save line, trimming any trailing newline */
5816 my_command->first_line =
5817 expr_scanner_get_substring(sstate,
5818 start_offset,
5819 true);
5820
5821 if (my_command->meta == META_SLEEP)
5822 {
5823 if (my_command->argc < 2)
5824 syntax_error(source, lineno, my_command->first_line, my_command->argv[0],
5825 "missing argument", NULL, -1);
5826
5827 if (my_command->argc > 3)
5828 syntax_error(source, lineno, my_command->first_line, my_command->argv[0],
5829 "too many arguments", NULL,
5830 offsets[3] - start_offset);
5831
5832 /*
5833 * Split argument into number and unit to allow "sleep 1ms" etc. We
5834 * don't have to terminate the number argument with null because it
5835 * will be parsed with atoi, which ignores trailing non-digit
5836 * characters.
5837 */
5838 if (my_command->argv[1][0] != ':')
5839 {
5840 char *c = my_command->argv[1];
5841 bool have_digit = false;
5842
5843 /* Skip sign */
5844 if (*c == '+' || *c == '-')
5845 c++;
5846
5847 /* Require at least one digit */
5848 if (*c && isdigit((unsigned char) *c))
5849 have_digit = true;
5850
5851 /* Eat all digits */
5852 while (*c && isdigit((unsigned char) *c))
5853 c++;
5854
5855 if (*c)
5856 {
5857 if (my_command->argc == 2 && have_digit)
5858 {
5859 my_command->argv[2] = c;
5860 offsets[2] = offsets[1] + (c - my_command->argv[1]);
5861 my_command->argc = 3;
5862 }
5863 else
5864 {
5865 /*
5866 * Raise an error if argument starts with non-digit
5867 * character (after sign).
5868 */
5869 syntax_error(source, lineno, my_command->first_line, my_command->argv[0],
5870 "invalid sleep time, must be an integer",
5871 my_command->argv[1], offsets[1] - start_offset);
5872 }
5873 }
5874 }
5875
5876 if (my_command->argc == 3)
5877 {
5878 if (pg_strcasecmp(my_command->argv[2], "us") != 0 &&
5879 pg_strcasecmp(my_command->argv[2], "ms") != 0 &&
5880 pg_strcasecmp(my_command->argv[2], "s") != 0)
5881 syntax_error(source, lineno, my_command->first_line, my_command->argv[0],
5882 "unrecognized time unit, must be us, ms or s",
5883 my_command->argv[2], offsets[2] - start_offset);
5884 }
5885 }
5886 else if (my_command->meta == META_SETSHELL)
5887 {
5888 if (my_command->argc < 3)
5889 syntax_error(source, lineno, my_command->first_line, my_command->argv[0],
5890 "missing argument", NULL, -1);
5891 }
5892 else if (my_command->meta == META_SHELL)
5893 {
5894 if (my_command->argc < 2)
5895 syntax_error(source, lineno, my_command->first_line, my_command->argv[0],
5896 "missing command", NULL, -1);
5897 }
5898 else if (my_command->meta == META_ELSE || my_command->meta == META_ENDIF ||
5899 my_command->meta == META_STARTPIPELINE ||
5900 my_command->meta == META_ENDPIPELINE ||
5901 my_command->meta == META_SYNCPIPELINE)
5902 {
5903 if (my_command->argc != 1)
5904 syntax_error(source, lineno, my_command->first_line, my_command->argv[0],
5905 "unexpected argument", NULL, -1);
5906 }
5907 else if (my_command->meta == META_GSET || my_command->meta == META_ASET)
5908 {
5909 if (my_command->argc > 2)
5910 syntax_error(source, lineno, my_command->first_line, my_command->argv[0],
5911 "too many arguments", NULL, -1);
5912 }
5913 else
5914 {
5915 /* my_command->meta == META_NONE */
5916 syntax_error(source, lineno, my_command->first_line, my_command->argv[0],
5917 "invalid command", NULL, -1);
5918 }
5919
5920 termPQExpBuffer(&word_buf);
5921
5922 return my_command;
5923 }
5924
5925 static void
5926 ConditionError(const char *desc, int cmdn, const char *msg)
5927 {
5928 pg_fatal("condition error in script \"%s\" command %d: %s",
5929 desc, cmdn, msg);
5930 }
5931
5932 /*
5933 * Partial evaluation of conditionals before recording and running the script.
5934 */
5935 static void
5936 CheckConditional(const ParsedScript *ps)
5937 {
5938 /* statically check conditional structure */
5939 ConditionalStack cs = conditional_stack_create();
5940 int i;
5941
5942 for (i = 0; ps->commands[i] != NULL; i++)
5943 {
5944 Command *cmd = ps->commands[i];
5945
5946 if (cmd->type == META_COMMAND)
5947 {
5948 switch (cmd->meta)
5949 {
5950 case META_IF:
5951 conditional_stack_push(cs, IFSTATE_FALSE);
5952 break;
5953 case META_ELIF:
5954 if (conditional_stack_empty(cs))
5955 ConditionError(ps->desc, i + 1, "\\elif without matching \\if");
5956 if (conditional_stack_peek(cs) == IFSTATE_ELSE_FALSE)
5957 ConditionError(ps->desc, i + 1, "\\elif after \\else");
5958 break;
5959 case META_ELSE:
5960 if (conditional_stack_empty(cs))
5961 ConditionError(ps->desc, i + 1, "\\else without matching \\if");
5962 if (conditional_stack_peek(cs) == IFSTATE_ELSE_FALSE)
5963 ConditionError(ps->desc, i + 1, "\\else after \\else");
5964 conditional_stack_poke(cs, IFSTATE_ELSE_FALSE);
5965 break;
5966 case META_ENDIF:
5967 if (!conditional_stack_pop(cs))
5968 ConditionError(ps->desc, i + 1, "\\endif without matching \\if");
5969 break;
5970 default:
5971 /* ignore anything else... */
5972 break;
5973 }
5974 }
5975 }
5976 if (!conditional_stack_empty(cs))
5977 ConditionError(ps->desc, i + 1, "\\if without matching \\endif");
5978 conditional_stack_destroy(cs);
5979 }
5980
5981 /*
5982 * Parse a script (either the contents of a file, or a built-in script)
5983 * and add it to the list of scripts.
5984 */
5985 static void
5986 ParseScript(const char *script, const char *desc, int weight)
5987 {
5988 ParsedScript ps;
5989 PsqlScanState sstate;
5990 PQExpBufferData line_buf;
5991 int alloc_num;
5992 int index;
5993
5994 #define COMMANDS_ALLOC_NUM 128
5995 alloc_num = COMMANDS_ALLOC_NUM;
5996
5997 /* Initialize all fields of ps */
5998 ps.desc = desc;
5999 ps.weight = weight;
6000 ps.commands = (Command **) pg_malloc(sizeof(Command *) * alloc_num);
6001 initStats(&ps.stats, 0);
6002
6003 /* Prepare to parse script */
6004 sstate = psql_scan_create(&pgbench_callbacks);
6005
6006 /*
6007 * Ideally, we'd scan scripts using the encoding and stdstrings settings
6008 * we get from a DB connection. However, without major rearrangement of
6009 * pgbench's argument parsing, we can't have a DB connection at the time
6010 * we parse scripts. Using SQL_ASCII (encoding 0) should work well enough
6011 * with any backend-safe encoding, though conceivably we could be fooled
6012 * if a script file uses a client-only encoding. We also assume that
6013 * stdstrings should be true, which is a bit riskier.
6014 */
6015 psql_scan_setup(sstate, script, strlen(script), 0, true);
6016
6017 initPQExpBuffer(&line_buf);
6018
6019 index = 0;
6020
6021 for (;;)
6022 {
6023 PsqlScanResult sr;
6024 promptStatus_t prompt;
6025 Command *command = NULL;
6026
6027 resetPQExpBuffer(&line_buf);
6028
6029 sr = psql_scan(sstate, &line_buf, &prompt);
6030
6031 /* If we collected a new SQL command, process that */
6032 command = create_sql_command(&line_buf, desc);
6033
6034 /* store new command */
6035 if (command)
6036 ps.commands[index++] = command;
6037
6038 /* If we reached a backslash, process that */
6039 if (sr == PSCAN_BACKSLASH)
6040 {
6041 int lineno;
6042 int start_offset;
6043
6044 /* Capture location of the backslash */
6045 psql_scan_get_location(sstate, &lineno, &start_offset);
6046 start_offset--;
6047
6048 command = process_backslash_command(sstate, desc,
6049 lineno, start_offset);
6050
6051 if (command)
6052 {
6053 /*
6054 * If this is gset or aset, merge into the preceding command.
6055 * (We don't use a command slot in this case).
6056 */
6057 if (command->meta == META_GSET || command->meta == META_ASET)
6058 {
6059 Command *cmd;
6060
6061 if (index == 0)
6062 syntax_error(desc, lineno, NULL, NULL,
6063 "\\gset must follow an SQL command",
6064 NULL, -1);
6065
6066 cmd = ps.commands[index - 1];
6067
6068 if (cmd->type != SQL_COMMAND ||
6069 cmd->varprefix != NULL)
6070 syntax_error(desc, lineno, NULL, NULL,
6071 "\\gset must follow an SQL command",
6072 cmd->first_line, -1);
6073
6074 /* get variable prefix */
6075 if (command->argc <= 1 || command->argv[1][0] == '\0')
6076 cmd->varprefix = pg_strdup("");
6077 else
6078 cmd->varprefix = pg_strdup(command->argv[1]);
6079
6080 /* update the sql command meta */
6081 cmd->meta = command->meta;
6082
6083 /* cleanup unused command */
6084 free_command(command);
6085
6086 continue;
6087 }
6088
6089 /* Attach any other backslash command as a new command */
6090 ps.commands[index++] = command;
6091 }
6092 }
6093
6094 /*
6095 * Since we used a command slot, allocate more if needed. Note we
6096 * always allocate one more in order to accommodate the NULL
6097 * terminator below.
6098 */
6099 if (index >= alloc_num)
6100 {
6101 alloc_num += COMMANDS_ALLOC_NUM;
6102 ps.commands = (Command **)
6103 pg_realloc(ps.commands, sizeof(Command *) * alloc_num);
6104 }
6105
6106 /* Done if we reached EOF */
6107 if (sr == PSCAN_INCOMPLETE || sr == PSCAN_EOL)
6108 break;
6109 }
6110
6111 ps.commands[index] = NULL;
6112
6113 addScript(&ps);
6114
6115 termPQExpBuffer(&line_buf);
6116 psql_scan_finish(sstate);
6117 psql_scan_destroy(sstate);
6118 }
6119
6120 /*
6121 * Read the entire contents of file fd, and return it in a malloc'd buffer.
6122 *
6123 * The buffer will typically be larger than necessary, but we don't care
6124 * in this program, because we'll free it as soon as we've parsed the script.
6125 */
6126 static char *
6127 read_file_contents(FILE *fd)
6128 {
6129 char *buf;
6130 size_t buflen = BUFSIZ;
6131 size_t used = 0;
6132
6133 buf = (char *) pg_malloc(buflen);
6134
6135 for (;;)
6136 {
6137 size_t nread;
6138
6139 nread = fread(buf + used, 1, BUFSIZ, fd);
6140 used += nread;
6141 /* If fread() read less than requested, must be EOF or error */
6142 if (nread < BUFSIZ)
6143 break;
6144 /* Enlarge buf so we can read some more */
6145 buflen += BUFSIZ;
6146 buf = (char *) pg_realloc(buf, buflen);
6147 }
6148 /* There is surely room for a terminator */
6149 buf[used] = '\0';
6150
6151 return buf;
6152 }
6153
6154 /*
6155 * Given a file name, read it and add its script to the list.
6156 * "-" means to read stdin.
6157 * NB: filename must be storage that won't disappear.
6158 */
6159 static void
6160 process_file(const char *filename, int weight)
6161 {
6162 FILE *fd;
6163 char *buf;
6164
6165 /* Slurp the file contents into "buf" */
6166 if (strcmp(filename, "-") == 0)
6167 fd = stdin;
6168 else if ((fd = fopen(filename, "r")) == NULL)
6169 pg_fatal("could not open file \"%s\": %m", filename);
6170
6171 buf = read_file_contents(fd);
6172
6173 if (ferror(fd))
6174 pg_fatal("could not read file \"%s\": %m", filename);
6175
6176 if (fd != stdin)
6177 fclose(fd);
6178
6179 ParseScript(buf, filename, weight);
6180
6181 free(buf);
6182 }
6183
6184 /* Parse the given builtin script and add it to the list. */
6185 static void
6186 process_builtin(const BuiltinScript *bi, int weight)
6187 {
6188 ParseScript(bi->script, bi->desc, weight);
6189 }
6190
6191 /* show available builtin scripts */
6192 static void
6193 listAvailableScripts(void)
6194 {
6195 int i;
6196
6197 fprintf(stderr, "Available builtin scripts:\n");
6198 for (i = 0; i < lengthof(builtin_script); i++)
6199 fprintf(stderr, " %13s: %s\n", builtin_script[i].name, builtin_script[i].desc);
6200 fprintf(stderr, "\n");
6201 }
6202
6203 /* return builtin script "name" if unambiguous, fails if not found */
6204 static const BuiltinScript *
6205 findBuiltin(const char *name)
6206 {
6207 int i,
6208 found = 0,
6209 len = strlen(name);
6210 const BuiltinScript *result = NULL;
6211
6212 for (i = 0; i < lengthof(builtin_script); i++)
6213 {
6214 if (strncmp(builtin_script[i].name, name, len) == 0)
6215 {
6216 result = &builtin_script[i];
6217 found++;
6218 }
6219 }
6220
6221 /* ok, unambiguous result */
6222 if (found == 1)
6223 return result;
6224
6225 /* error cases */
6226 if (found == 0)
6227 pg_log_error("no builtin script found for name \"%s\"", name);
6228 else /* found > 1 */
6229 pg_log_error("ambiguous builtin name: %d builtin scripts found for prefix \"%s\"", found, name);
6230
6231 listAvailableScripts();
6232 exit(1);
6233 }
6234
6235 /*
6236 * Determine the weight specification from a script option (-b, -f), if any,
6237 * and return it as an integer (1 is returned if there's no weight). The
6238 * script name is returned in *script as a malloc'd string.
6239 */
6240 static int
6241 parseScriptWeight(const char *option, char **script)
6242 {
6243 const char *sep;
6244 int weight;
6245
6246 if ((sep = strrchr(option, WSEP)))
6247 {
6248 int namelen = sep - option;
6249 long wtmp;
6250 char *badp;
6251
6252 /* generate the script name */
6253 *script = pg_malloc(namelen + 1);
6254 strncpy(*script, option, namelen);
6255 (*script)[namelen] = '\0';
6256
6257 /* process digits of the weight spec */
6258 errno = 0;
6259 wtmp = strtol(sep + 1, &badp, 10);
6260 if (errno != 0 || badp == sep + 1 || *badp != '\0')
6261 pg_fatal("invalid weight specification: %s", sep);
6262 if (wtmp > INT_MAX || wtmp < 0)
6263 pg_fatal("weight specification out of range (0 .. %d): %lld",
6264 INT_MAX, (long long) wtmp);
6265 weight = wtmp;
6266 }
6267 else
6268 {
6269 *script = pg_strdup(option);
6270 weight = 1;
6271 }
6272
6273 return weight;
6274 }
6275
6276 /* append a script to the list of scripts to process */
6277 static void
6278 addScript(const ParsedScript *script)
6279 {
6280 if (script->commands == NULL || script->commands[0] == NULL)
6281 pg_fatal("empty command list for script \"%s\"", script->desc);
6282
6283 if (num_scripts >= MAX_SCRIPTS)
6284 pg_fatal("at most %d SQL scripts are allowed", MAX_SCRIPTS);
6285
6286 CheckConditional(script);
6287
6288 sql_script[num_scripts] = *script;
6289 num_scripts++;
6290 }
6291
6292 /*
6293 * Print progress report.
6294 *
6295 * On entry, *last and *last_report contain the statistics and time of last
6296 * progress report. On exit, they are updated with the new stats.
6297 */
6298 static void
6299 printProgressReport(TState *threads, int64 test_start, pg_time_usec_t now,
6300 StatsData *last, int64 *last_report)
6301 {
6302 /* generate and show report */
6303 pg_time_usec_t run = now - *last_report;
6304 int64 cnt,
6305 failures,
6306 retried;
6307 double tps,
6308 total_run,
6309 latency,
6310 sqlat,
6311 lag,
6312 stdev;
6313 char tbuf[315];
6314 StatsData cur;
6315
6316 /*
6317 * Add up the statistics of all threads.
6318 *
6319 * XXX: No locking. There is no guarantee that we get an atomic snapshot
6320 * of the transaction count and latencies, so these figures can well be
6321 * off by a small amount. The progress report's purpose is to give a
6322 * quick overview of how the test is going, so that shouldn't matter too
6323 * much. (If a read from a 64-bit integer is not atomic, you might get a
6324 * "torn" read and completely bogus latencies though!)
6325 */
6326 initStats(&cur, 0);
6327 for (int i = 0; i < nthreads; i++)
6328 {
6329 mergeSimpleStats(&cur.latency, &threads[i].stats.latency);
6330 mergeSimpleStats(&cur.lag, &threads[i].stats.lag);
6331 cur.cnt += threads[i].stats.cnt;
6332 cur.skipped += threads[i].stats.skipped;
6333 cur.retries += threads[i].stats.retries;
6334 cur.retried += threads[i].stats.retried;
6335 cur.serialization_failures +=
6336 threads[i].stats.serialization_failures;
6337 cur.deadlock_failures += threads[i].stats.deadlock_failures;
6338 }
6339
6340 /* we count only actually executed transactions */
6341 cnt = cur.cnt - last->cnt;
6342 total_run = (now - test_start) / 1000000.0;
6343 tps = 1000000.0 * cnt / run;
6344 if (cnt > 0)
6345 {
6346 latency = 0.001 * (cur.latency.sum - last->latency.sum) / cnt;
6347 sqlat = 1.0 * (cur.latency.sum2 - last->latency.sum2) / cnt;
6348 stdev = 0.001 * sqrt(sqlat - 1000000.0 * latency * latency);
6349 lag = 0.001 * (cur.lag.sum - last->lag.sum) / cnt;
6350 }
6351 else
6352 {
6353 latency = sqlat = stdev = lag = 0;
6354 }
6355 failures = getFailures(&cur) - getFailures(last);
6356 retried = cur.retried - last->retried;
6357
6358 if (progress_timestamp)
6359 {
6360 snprintf(tbuf, sizeof(tbuf), "%.3f s",
6361 PG_TIME_GET_DOUBLE(now + epoch_shift));
6362 }
6363 else
6364 {
6365 /* round seconds are expected, but the thread may be late */
6366 snprintf(tbuf, sizeof(tbuf), "%.1f s", total_run);
6367 }
6368
6369 fprintf(stderr,
6370 "progress: %s, %.1f tps, lat %.3f ms stddev %.3f, " INT64_FORMAT " failed",
6371 tbuf, tps, latency, stdev, failures);
6372
6373 if (throttle_delay)
6374 {
6375 fprintf(stderr, ", lag %.3f ms", lag);
6376 if (latency_limit)
6377 fprintf(stderr, ", " INT64_FORMAT " skipped",
6378 cur.skipped - last->skipped);
6379 }
6380
6381 /* it can be non-zero only if max_tries is not equal to one */
6382 if (max_tries != 1)
6383 fprintf(stderr,
6384 ", " INT64_FORMAT " retried, " INT64_FORMAT " retries",
6385 retried, cur.retries - last->retries);
6386 fprintf(stderr, "\n");
6387
6388 *last = cur;
6389 *last_report = now;
6390 }
6391
6392 static void
6393 printSimpleStats(const char *prefix, SimpleStats *ss)
6394 {
6395 if (ss->count > 0)
6396 {
6397 double latency = ss->sum / ss->count;
6398 double stddev = sqrt(ss->sum2 / ss->count - latency * latency);
6399
6400 printf("%s average = %.3f ms\n", prefix, 0.001 * latency);
6401 printf("%s stddev = %.3f ms\n", prefix, 0.001 * stddev);
6402 }
6403 }
6404
6405 /* print version banner */
6406 static void
6407 printVersion(PGconn *con)
6408 {
6409 int server_ver = PQserverVersion(con);
6410 int client_ver = PG_VERSION_NUM;
6411
6412 if (server_ver != client_ver)
6413 {
6414 const char *server_version;
6415 char sverbuf[32];
6416
6417 /* Try to get full text form, might include "devel" etc */
6418 server_version = PQparameterStatus(con, "server_version");
6419 /* Otherwise fall back on server_ver */
6420 if (!server_version)
6421 {
6422 formatPGVersionNumber(server_ver, true,
6423 sverbuf, sizeof(sverbuf));
6424 server_version = sverbuf;
6425 }
6426
6427 printf(_("%s (%s, server %s)\n"),
6428 "pgbench", PG_VERSION, server_version);
6429 }
6430 /* For version match, only print pgbench version */
6431 else
6432 printf("%s (%s)\n", "pgbench", PG_VERSION);
6433 fflush(stdout);
6434 }
6435
6436 /* print out results */
6437 static void
6438 printResults(StatsData *total,
6439 pg_time_usec_t total_duration, /* benchmarking time */
6440 pg_time_usec_t conn_total_duration, /* is_connect */
6441 pg_time_usec_t conn_elapsed_duration, /* !is_connect */
6442 int64 latency_late)
6443 {
6444 /* tps is about actually executed transactions during benchmarking */
6445 int64 failures = getFailures(total);
6446 int64 total_cnt = total->cnt + total->skipped + failures;
6447 double bench_duration = PG_TIME_GET_DOUBLE(total_duration);
6448 double tps = total->cnt / bench_duration;
6449
6450 /* Report test parameters. */
6451 printf("transaction type: %s\n",
6452 num_scripts == 1 ? sql_script[0].desc : "multiple scripts");
6453 printf("scaling factor: %d\n", scale);
6454 /* only print partitioning information if some partitioning was detected */
6455 if (partition_method != PART_NONE)
6456 printf("partition method: %s\npartitions: %d\n",
6457 PARTITION_METHOD[partition_method], partitions);
6458 printf("query mode: %s\n", QUERYMODE[querymode]);
6459 printf("number of clients: %d\n", nclients);
6460 printf("number of threads: %d\n", nthreads);
6461
6462 if (max_tries)
6463 printf("maximum number of tries: %u\n", max_tries);
6464
6465 if (duration <= 0)
6466 {
6467 printf("number of transactions per client: %d\n", nxacts);
6468 printf("number of transactions actually processed: " INT64_FORMAT "/%d\n",
6469 total->cnt, nxacts * nclients);
6470 }
6471 else
6472 {
6473 printf("duration: %d s\n", duration);
6474 printf("number of transactions actually processed: " INT64_FORMAT "\n",
6475 total->cnt);
6476 }
6477
6478 /*
6479 * Remaining stats are nonsensical if we failed to execute any xacts due
6480 * to others than serialization or deadlock errors
6481 */
6482 if (total_cnt <= 0)
6483 return;
6484
6485 printf("number of failed transactions: " INT64_FORMAT " (%.3f%%)\n",
6486 failures, 100.0 * failures / total_cnt);
6487
6488 if (failures_detailed)
6489 {
6490 printf("number of serialization failures: " INT64_FORMAT " (%.3f%%)\n",
6491 total->serialization_failures,
6492 100.0 * total->serialization_failures / total_cnt);
6493 printf("number of deadlock failures: " INT64_FORMAT " (%.3f%%)\n",
6494 total->deadlock_failures,
6495 100.0 * total->deadlock_failures / total_cnt);
6496 }
6497
6498 /* it can be non-zero only if max_tries is not equal to one */
6499 if (max_tries != 1)
6500 {
6501 printf("number of transactions retried: " INT64_FORMAT " (%.3f%%)\n",
6502 total->retried, 100.0 * total->retried / total_cnt);
6503 printf("total number of retries: " INT64_FORMAT "\n", total->retries);
6504 }
6505
6506 if (throttle_delay && latency_limit)
6507 printf("number of transactions skipped: " INT64_FORMAT " (%.3f%%)\n",
6508 total->skipped, 100.0 * total->skipped / total_cnt);
6509
6510 if (latency_limit)
6511 printf("number of transactions above the %.1f ms latency limit: " INT64_FORMAT "/" INT64_FORMAT " (%.3f%%)\n",
6512 latency_limit / 1000.0, latency_late, total->cnt,
6513 (total->cnt > 0) ? 100.0 * latency_late / total->cnt : 0.0);
6514
6515 if (throttle_delay || progress || latency_limit)
6516 printSimpleStats("latency", &total->latency);
6517 else
6518 {
6519 /* no measurement, show average latency computed from run time */
6520 printf("latency average = %.3f ms%s\n",
6521 0.001 * total_duration * nclients / total_cnt,
6522 failures > 0 ? " (including failures)" : "");
6523 }
6524
6525 if (throttle_delay)
6526 {
6527 /*
6528 * Report average transaction lag under rate limit throttling. This
6529 * is the delay between scheduled and actual start times for the
6530 * transaction. The measured lag may be caused by thread/client load,
6531 * the database load, or the Poisson throttling process.
6532 */
6533 printf("rate limit schedule lag: avg %.3f (max %.3f) ms\n",
6534 0.001 * total->lag.sum / total->cnt, 0.001 * total->lag.max);
6535 }
6536
6537 /*
6538 * Under -C/--connect, each transaction incurs a significant connection
6539 * cost, it would not make much sense to ignore it in tps, and it would
6540 * not be tps anyway.
6541 *
6542 * Otherwise connections are made just once at the beginning of the run
6543 * and should not impact performance but for very short run, so they are
6544 * (right)fully ignored in tps.
6545 */
6546 if (is_connect)
6547 {
6548 printf("average connection time = %.3f ms\n", 0.001 * conn_total_duration / (total->cnt + failures));
6549 printf("tps = %f (including reconnection times)\n", tps);
6550 }
6551 else
6552 {
6553 printf("initial connection time = %.3f ms\n", 0.001 * conn_elapsed_duration);
6554 printf("tps = %f (without initial connection time)\n", tps);
6555 }
6556
6557 /* Report per-script/command statistics */
6558 if (per_script_stats || report_per_command)
6559 {
6560 int i;
6561
6562 for (i = 0; i < num_scripts; i++)
6563 {
6564 if (per_script_stats)
6565 {
6566 StatsData *sstats = &sql_script[i].stats;
6567 int64 script_failures = getFailures(sstats);
6568 int64 script_total_cnt =
6569 sstats->cnt + sstats->skipped + script_failures;
6570
6571 printf("SQL script %d: %s\n"
6572 " - weight: %d (targets %.1f%% of total)\n"
6573 " - " INT64_FORMAT " transactions (%.1f%% of total)\n",
6574 i + 1, sql_script[i].desc,
6575 sql_script[i].weight,
6576 100.0 * sql_script[i].weight / total_weight,
6577 script_total_cnt,
6578 100.0 * script_total_cnt / total_cnt);
6579
6580 if (script_total_cnt > 0)
6581 {
6582 printf(" - number of transactions actually processed: " INT64_FORMAT " (tps = %f)\n",
6583 sstats->cnt, sstats->cnt / bench_duration);
6584
6585 printf(" - number of failed transactions: " INT64_FORMAT " (%.3f%%)\n",
6586 script_failures,
6587 100.0 * script_failures / script_total_cnt);
6588
6589 if (failures_detailed)
6590 {
6591 printf(" - number of serialization failures: " INT64_FORMAT " (%.3f%%)\n",
6592 sstats->serialization_failures,
6593 (100.0 * sstats->serialization_failures /
6594 script_total_cnt));
6595 printf(" - number of deadlock failures: " INT64_FORMAT " (%.3f%%)\n",
6596 sstats->deadlock_failures,
6597 (100.0 * sstats->deadlock_failures /
6598 script_total_cnt));
6599 }
6600
6601 /*
6602 * it can be non-zero only if max_tries is not equal to
6603 * one
6604 */
6605 if (max_tries != 1)
6606 {
6607 printf(" - number of transactions retried: " INT64_FORMAT " (%.3f%%)\n",
6608 sstats->retried,
6609 100.0 * sstats->retried / script_total_cnt);
6610 printf(" - total number of retries: " INT64_FORMAT "\n",
6611 sstats->retries);
6612 }
6613
6614 if (throttle_delay && latency_limit)
6615 printf(" - number of transactions skipped: " INT64_FORMAT " (%.3f%%)\n",
6616 sstats->skipped,
6617 100.0 * sstats->skipped / script_total_cnt);
6618
6619 }
6620 printSimpleStats(" - latency", &sstats->latency);
6621 }
6622
6623 /*
6624 * Report per-command statistics: latencies, retries after errors,
6625 * failures (errors without retrying).
6626 */
6627 if (report_per_command)
6628 {
6629 Command **commands;
6630
6631 printf("%sstatement latencies in milliseconds%s:\n",
6632 per_script_stats ? " - " : "",
6633 (max_tries == 1 ?
6634 " and failures" :
6635 ", failures and retries"));
6636
6637 for (commands = sql_script[i].commands;
6638 *commands != NULL;
6639 commands++)
6640 {
6641 SimpleStats *cstats = &(*commands)->stats;
6642
6643 if (max_tries == 1)
6644 printf(" %11.3f %10" PRId64 " %s\n",
6645 (cstats->count > 0) ?
6646 1000.0 * cstats->sum / cstats->count : 0.0,
6647 (*commands)->failures,
6648 (*commands)->first_line);
6649 else
6650 printf(" %11.3f %10" PRId64 " %10" PRId64 " %s\n",
6651 (cstats->count > 0) ?
6652 1000.0 * cstats->sum / cstats->count : 0.0,
6653 (*commands)->failures,
6654 (*commands)->retries,
6655 (*commands)->first_line);
6656 }
6657 }
6658 }
6659 }
6660 }
6661
6662 /*
6663 * Set up a random seed according to seed parameter (NULL means default),
6664 * and initialize base_random_sequence for use in initializing other sequences.
6665 */
6666 static bool
6667 set_random_seed(const char *seed)
6668 {
6669 uint64 iseed;
6670
6671 if (seed == NULL || strcmp(seed, "time") == 0)
6672 {
6673 /* rely on current time */
6674 iseed = pg_time_now();
6675 }
6676 else if (strcmp(seed, "rand") == 0)
6677 {
6678 /* use some "strong" random source */
6679 if (!pg_strong_random(&iseed, sizeof(iseed)))
6680 {
6681 pg_log_error("could not generate random seed");
6682 return false;
6683 }
6684 }
6685 else
6686 {
6687 char garbage;
6688
6689 if (sscanf(seed, "%" SCNu64 "%c", &iseed, &garbage) != 1)
6690 {
6691 pg_log_error("unrecognized random seed option \"%s\"", seed);
6692 pg_log_error_detail("Expecting an unsigned integer, \"time\" or \"rand\".");
6693 return false;
6694 }
6695 }
6696
6697 if (seed != NULL)
6698 pg_log_info("setting random seed to %" PRIu64, iseed);
6699
6700 random_seed = iseed;
6701
6702 /* Initialize base_random_sequence using seed */
6703 pg_prng_seed(&base_random_sequence, iseed);
6704
6705 return true;
6706 }
6707
6708 int
6709 main(int argc, char **argv)
6710 {
6711 static struct option long_options[] = {
6712 /* systematic long/short named options */
6713 {"builtin", required_argument, NULL, 'b'},
6714 {"client", required_argument, NULL, 'c'},
6715 {"connect", no_argument, NULL, 'C'},
6716 {"dbname", required_argument, NULL, 'd'},
6717 {"define", required_argument, NULL, 'D'},
6718 {"file", required_argument, NULL, 'f'},
6719 {"fillfactor", required_argument, NULL, 'F'},
6720 {"host", required_argument, NULL, 'h'},
6721 {"initialize", no_argument, NULL, 'i'},
6722 {"init-steps", required_argument, NULL, 'I'},
6723 {"jobs", required_argument, NULL, 'j'},
6724 {"log", no_argument, NULL, 'l'},
6725 {"latency-limit", required_argument, NULL, 'L'},
6726 {"no-vacuum", no_argument, NULL, 'n'},
6727 {"port", required_argument, NULL, 'p'},
6728 {"progress", required_argument, NULL, 'P'},
6729 {"protocol", required_argument, NULL, 'M'},
6730 {"quiet", no_argument, NULL, 'q'},
6731 {"report-per-command", no_argument, NULL, 'r'},
6732 {"rate", required_argument, NULL, 'R'},
6733 {"scale", required_argument, NULL, 's'},
6734 {"select-only", no_argument, NULL, 'S'},
6735 {"skip-some-updates", no_argument, NULL, 'N'},
6736 {"time", required_argument, NULL, 'T'},
6737 {"transactions", required_argument, NULL, 't'},
6738 {"username", required_argument, NULL, 'U'},
6739 {"vacuum-all", no_argument, NULL, 'v'},
6740 /* long-named only options */
6741 {"unlogged-tables", no_argument, NULL, 1},
6742 {"tablespace", required_argument, NULL, 2},
6743 {"index-tablespace", required_argument, NULL, 3},
6744 {"sampling-rate", required_argument, NULL, 4},
6745 {"aggregate-interval", required_argument, NULL, 5},
6746 {"progress-timestamp", no_argument, NULL, 6},
6747 {"log-prefix", required_argument, NULL, 7},
6748 {"foreign-keys", no_argument, NULL, 8},
6749 {"random-seed", required_argument, NULL, 9},
6750 {"show-script", required_argument, NULL, 10},
6751 {"partitions", required_argument, NULL, 11},
6752 {"partition-method", required_argument, NULL, 12},
6753 {"failures-detailed", no_argument, NULL, 13},
6754 {"max-tries", required_argument, NULL, 14},
6755 {"verbose-errors", no_argument, NULL, 15},
6756 {"exit-on-abort", no_argument, NULL, 16},
6757 {"debug", no_argument, NULL, 17},
6758 {NULL, 0, NULL, 0}
6759 };
6760
6761 int c;
6762 bool is_init_mode = false; /* initialize mode? */
6763 char *initialize_steps = NULL;
6764 bool foreign_keys = false;
6765 bool is_no_vacuum = false;
6766 bool do_vacuum_accounts = false; /* vacuum accounts table? */
6767 int optindex;
6768 bool scale_given = false;
6769
6770 bool benchmarking_option_set = false;
6771 bool initialization_option_set = false;
6772 bool internal_script_used = false;
6773
6774 CState *state; /* status of clients */
6775 TState *threads; /* array of thread */
6776
6777 pg_time_usec_t
6778 start_time, /* start up time */
6779 bench_start = 0, /* first recorded benchmarking time */
6780 conn_total_duration; /* cumulated connection time in
6781 * threads */
6782 int64 latency_late = 0;
6783 StatsData stats;
6784 int weight;
6785
6786 int i;
6787 int nclients_dealt;
6788
6789 #ifdef HAVE_GETRLIMIT
6790 struct rlimit rlim;
6791 #endif
6792
6793 PGconn *con;
6794 char *env;
6795
6796 int exit_code = 0;
6797 struct timeval tv;
6798
6799 /*
6800 * Record difference between Unix time and instr_time time. We'll use
6801 * this for logging and aggregation.
6802 */
6803 gettimeofday(&tv, NULL);
6804 epoch_shift = tv.tv_sec * INT64CONST(1000000) + tv.tv_usec - pg_time_now();
6805
6806 pg_logging_init(argv[0]);
6807 progname = get_progname(argv[0]);
6808
6809 if (argc > 1)
6810 {
6811 if (strcmp(argv[1], "--help") == 0 || strcmp(argv[1], "-?") == 0)
6812 {
6813 usage();
6814 exit(0);
6815 }
6816 if (strcmp(argv[1], "--version") == 0 || strcmp(argv[1], "-V") == 0)
6817 {
6818 puts("pgbench (PostgreSQL) " PG_VERSION);
6819 exit(0);
6820 }
6821 }
6822
6823 state = (CState *) pg_malloc0(sizeof(CState));
6824
6825 /* set random seed early, because it may be used while parsing scripts. */
6826 if (!set_random_seed(getenv("PGBENCH_RANDOM_SEED")))
6827 pg_fatal("error while setting random seed from PGBENCH_RANDOM_SEED environment variable");
6828
6829 while ((c = getopt_long(argc, argv, "b:c:Cd:D:f:F:h:iI:j:lL:M:nNp:P:qrR:s:St:T:U:v", long_options, &optindex)) != -1)
6830 {
6831 char *script;
6832
6833 switch (c)
6834 {
6835 case 'b':
6836 if (strcmp(optarg, "list") == 0)
6837 {
6838 listAvailableScripts();
6839 exit(0);
6840 }
6841 weight = parseScriptWeight(optarg, &script);
6842 process_builtin(findBuiltin(script), weight);
6843 benchmarking_option_set = true;
6844 internal_script_used = true;
6845 break;
6846 case 'c':
6847 benchmarking_option_set = true;
6848 if (!option_parse_int(optarg, "-c/--client", 1, INT_MAX,
6849 &nclients))
6850 {
6851 exit(1);
6852 }
6853 #ifdef HAVE_GETRLIMIT
6854 if (getrlimit(RLIMIT_NOFILE, &rlim) == -1)
6855 pg_fatal("getrlimit failed: %m");
6856
6857 if (rlim.rlim_max < nclients + 3)
6858 {
6859 pg_log_error("need at least %d open files, but system limit is %ld",
6860 nclients + 3, (long) rlim.rlim_max);
6861 pg_log_error_hint("Reduce number of clients, or use limit/ulimit to increase the system limit.");
6862 exit(1);
6863 }
6864
6865 if (rlim.rlim_cur < nclients + 3)
6866 {
6867 rlim.rlim_cur = nclients + 3;
6868 if (setrlimit(RLIMIT_NOFILE, &rlim) == -1)
6869 {
6870 pg_log_error("need at least %d open files, but couldn't raise the limit: %m",
6871 nclients + 3);
6872 pg_log_error_hint("Reduce number of clients, or use limit/ulimit to increase the system limit.");
6873 exit(1);
6874 }
6875 }
6876 #endif /* HAVE_GETRLIMIT */
6877 break;
6878 case 'C':
6879 benchmarking_option_set = true;
6880 is_connect = true;
6881 break;
6882 case 'd':
6883 dbName = pg_strdup(optarg);
6884 break;
6885 case 'D':
6886 {
6887 char *p;
6888
6889 benchmarking_option_set = true;
6890
6891 if ((p = strchr(optarg, '=')) == NULL || p == optarg || *(p + 1) == '\0')
6892 pg_fatal("invalid variable definition: \"%s\"", optarg);
6893
6894 *p++ = '\0';
6895 if (!putVariable(&state[0].variables, "option", optarg, p))
6896 exit(1);
6897 }
6898 break;
6899 case 'f':
6900 weight = parseScriptWeight(optarg, &script);
6901 process_file(script, weight);
6902 benchmarking_option_set = true;
6903 break;
6904 case 'F':
6905 initialization_option_set = true;
6906 if (!option_parse_int(optarg, "-F/--fillfactor", 10, 100,
6907 &fillfactor))
6908 exit(1);
6909 break;
6910 case 'h':
6911 pghost = pg_strdup(optarg);
6912 break;
6913 case 'i':
6914 is_init_mode = true;
6915 break;
6916 case 'I':
6917 pg_free(initialize_steps);
6918 initialize_steps = pg_strdup(optarg);
6919 checkInitSteps(initialize_steps);
6920 initialization_option_set = true;
6921 break;
6922 case 'j': /* jobs */
6923 benchmarking_option_set = true;
6924 if (!option_parse_int(optarg, "-j/--jobs", 1, INT_MAX,
6925 &nthreads))
6926 {
6927 exit(1);
6928 }
6929 break;
6930 case 'l':
6931 benchmarking_option_set = true;
6932 use_log = true;
6933 break;
6934 case 'L':
6935 {
6936 double limit_ms = atof(optarg);
6937
6938 if (limit_ms <= 0.0)
6939 pg_fatal("invalid latency limit: \"%s\"", optarg);
6940 benchmarking_option_set = true;
6941 latency_limit = (int64) (limit_ms * 1000);
6942 }
6943 break;
6944 case 'M':
6945 benchmarking_option_set = true;
6946 for (querymode = 0; querymode < NUM_QUERYMODE; querymode++)
6947 if (strcmp(optarg, QUERYMODE[querymode]) == 0)
6948 break;
6949 if (querymode >= NUM_QUERYMODE)
6950 pg_fatal("invalid query mode (-M): \"%s\"", optarg);
6951 break;
6952 case 'n':
6953 is_no_vacuum = true;
6954 break;
6955 case 'N':
6956 process_builtin(findBuiltin("simple-update"), 1);
6957 benchmarking_option_set = true;
6958 internal_script_used = true;
6959 break;
6960 case 'p':
6961 pgport = pg_strdup(optarg);
6962 break;
6963 case 'P':
6964 benchmarking_option_set = true;
6965 if (!option_parse_int(optarg, "-P/--progress", 1, INT_MAX,
6966 &progress))
6967 exit(1);
6968 break;
6969 case 'q':
6970 initialization_option_set = true;
6971 use_quiet = true;
6972 break;
6973 case 'r':
6974 benchmarking_option_set = true;
6975 report_per_command = true;
6976 break;
6977 case 'R':
6978 {
6979 /* get a double from the beginning of option value */
6980 double throttle_value = atof(optarg);
6981
6982 benchmarking_option_set = true;
6983
6984 if (throttle_value <= 0.0)
6985 pg_fatal("invalid rate limit: \"%s\"", optarg);
6986 /* Invert rate limit into per-transaction delay in usec */
6987 throttle_delay = 1000000.0 / throttle_value;
6988 }
6989 break;
6990 case 's':
6991 scale_given = true;
6992 if (!option_parse_int(optarg, "-s/--scale", 1, INT_MAX,
6993 &scale))
6994 exit(1);
6995 break;
6996 case 'S':
6997 process_builtin(findBuiltin("select-only"), 1);
6998 benchmarking_option_set = true;
6999 internal_script_used = true;
7000 break;
7001 case 't':
7002 benchmarking_option_set = true;
7003 if (!option_parse_int(optarg, "-t/--transactions", 1, INT_MAX,
7004 &nxacts))
7005 exit(1);
7006 break;
7007 case 'T':
7008 benchmarking_option_set = true;
7009 if (!option_parse_int(optarg, "-T/--time", 1, INT_MAX,
7010 &duration))
7011 exit(1);
7012 break;
7013 case 'U':
7014 username = pg_strdup(optarg);
7015 break;
7016 case 'v':
7017 benchmarking_option_set = true;
7018 do_vacuum_accounts = true;
7019 break;
7020 case 1: /* unlogged-tables */
7021 initialization_option_set = true;
7022 unlogged_tables = true;
7023 break;
7024 case 2: /* tablespace */
7025 initialization_option_set = true;
7026 tablespace = pg_strdup(optarg);
7027 break;
7028 case 3: /* index-tablespace */
7029 initialization_option_set = true;
7030 index_tablespace = pg_strdup(optarg);
7031 break;
7032 case 4: /* sampling-rate */
7033 benchmarking_option_set = true;
7034 sample_rate = atof(optarg);
7035 if (sample_rate <= 0.0 || sample_rate > 1.0)
7036 pg_fatal("invalid sampling rate: \"%s\"", optarg);
7037 break;
7038 case 5: /* aggregate-interval */
7039 benchmarking_option_set = true;
7040 if (!option_parse_int(optarg, "--aggregate-interval", 1, INT_MAX,
7041 &agg_interval))
7042 exit(1);
7043 break;
7044 case 6: /* progress-timestamp */
7045 progress_timestamp = true;
7046 benchmarking_option_set = true;
7047 break;
7048 case 7: /* log-prefix */
7049 benchmarking_option_set = true;
7050 logfile_prefix = pg_strdup(optarg);
7051 break;
7052 case 8: /* foreign-keys */
7053 initialization_option_set = true;
7054 foreign_keys = true;
7055 break;
7056 case 9: /* random-seed */
7057 benchmarking_option_set = true;
7058 if (!set_random_seed(optarg))
7059 pg_fatal("error while setting random seed from --random-seed option");
7060 break;
7061 case 10: /* list */
7062 {
7063 const BuiltinScript *s = findBuiltin(optarg);
7064
7065 fprintf(stderr, "-- %s: %s\n%s\n", s->name, s->desc, s->script);
7066 exit(0);
7067 }
7068 break;
7069 case 11: /* partitions */
7070 initialization_option_set = true;
7071 if (!option_parse_int(optarg, "--partitions", 0, INT_MAX,
7072 &partitions))
7073 exit(1);
7074 break;
7075 case 12: /* partition-method */
7076 initialization_option_set = true;
7077 if (pg_strcasecmp(optarg, "range") == 0)
7078 partition_method = PART_RANGE;
7079 else if (pg_strcasecmp(optarg, "hash") == 0)
7080 partition_method = PART_HASH;
7081 else
7082 pg_fatal("invalid partition method, expecting \"range\" or \"hash\", got: \"%s\"",
7083 optarg);
7084 break;
7085 case 13: /* failures-detailed */
7086 benchmarking_option_set = true;
7087 failures_detailed = true;
7088 break;
7089 case 14: /* max-tries */
7090 {
7091 int32 max_tries_arg = atoi(optarg);
7092
7093 if (max_tries_arg < 0)
7094 pg_fatal("invalid number of maximum tries: \"%s\"", optarg);
7095
7096 benchmarking_option_set = true;
7097 max_tries = (uint32) max_tries_arg;
7098 }
7099 break;
7100 case 15: /* verbose-errors */
7101 benchmarking_option_set = true;
7102 verbose_errors = true;
7103 break;
7104 case 16: /* exit-on-abort */
7105 benchmarking_option_set = true;
7106 exit_on_abort = true;
7107 break;
7108 case 17: /* debug */
7109 pg_logging_increase_verbosity();
7110 break;
7111 default:
7112 /* getopt_long already emitted a complaint */
7113 pg_log_error_hint("Try \"%s --help\" for more information.", progname);
7114 exit(1);
7115 }
7116 }
7117
7118 /* set default script if none */
7119 if (num_scripts == 0 && !is_init_mode)
7120 {
7121 process_builtin(findBuiltin("tpcb-like"), 1);
7122 benchmarking_option_set = true;
7123 internal_script_used = true;
7124 }
7125
7126 /* complete SQL command initialization and compute total weight */
7127 for (i = 0; i < num_scripts; i++)
7128 {
7129 Command **commands = sql_script[i].commands;
7130
7131 for (int j = 0; commands[j] != NULL; j++)
7132 if (commands[j]->type == SQL_COMMAND)
7133 postprocess_sql_command(commands[j]);
7134
7135 /* cannot overflow: weight is 32b, total_weight 64b */
7136 total_weight += sql_script[i].weight;
7137 }
7138
7139 if (total_weight == 0 && !is_init_mode)
7140 pg_fatal("total script weight must not be zero");
7141
7142 /* show per script stats if several scripts are used */
7143 if (num_scripts > 1)
7144 per_script_stats = true;
7145
7146 /*
7147 * Don't need more threads than there are clients. (This is not merely an
7148 * optimization; throttle_delay is calculated incorrectly below if some
7149 * threads have no clients assigned to them.)
7150 */
7151 if (nthreads > nclients)
7152 nthreads = nclients;
7153
7154 /*
7155 * Convert throttle_delay to a per-thread delay time. Note that this
7156 * might be a fractional number of usec, but that's OK, since it's just
7157 * the center of a Poisson distribution of delays.
7158 */
7159 throttle_delay *= nthreads;
7160
7161 if (dbName == NULL)
7162 {
7163 if (argc > optind)
7164 dbName = argv[optind++];
7165 else
7166 {
7167 if ((env = getenv("PGDATABASE")) != NULL && *env != '\0')
7168 dbName = env;
7169 else if ((env = getenv("PGUSER")) != NULL && *env != '\0')
7170 dbName = env;
7171 else
7172 dbName = get_user_name_or_exit(progname);
7173 }
7174 }
7175
7176 if (optind < argc)
7177 {
7178 pg_log_error("too many command-line arguments (first is \"%s\")",
7179 argv[optind]);
7180 pg_log_error_hint("Try \"%s --help\" for more information.", progname);
7181 exit(1);
7182 }
7183
7184 if (is_init_mode)
7185 {
7186 if (benchmarking_option_set)
7187 pg_fatal("some of the specified options cannot be used in initialization (-i) mode");
7188
7189 if (partitions == 0 && partition_method != PART_NONE)
7190 pg_fatal("--partition-method requires greater than zero --partitions");
7191
7192 /* set default method */
7193 if (partitions > 0 && partition_method == PART_NONE)
7194 partition_method = PART_RANGE;
7195
7196 if (initialize_steps == NULL)
7197 initialize_steps = pg_strdup(DEFAULT_INIT_STEPS);
7198
7199 if (is_no_vacuum)
7200 {
7201 /* Remove any vacuum step in initialize_steps */
7202 char *p;
7203
7204 while ((p = strchr(initialize_steps, 'v')) != NULL)
7205 *p = ' ';
7206 }
7207
7208 if (foreign_keys)
7209 {
7210 /* Add 'f' to end of initialize_steps, if not already there */
7211 if (strchr(initialize_steps, 'f') == NULL)
7212 {
7213 initialize_steps = (char *)
7214 pg_realloc(initialize_steps,
7215 strlen(initialize_steps) + 2);
7216 strcat(initialize_steps, "f");
7217 }
7218 }
7219
7220 runInitSteps(initialize_steps);
7221 exit(0);
7222 }
7223 else
7224 {
7225 if (initialization_option_set)
7226 pg_fatal("some of the specified options cannot be used in benchmarking mode");
7227 }
7228
7229 if (nxacts > 0 && duration > 0)
7230 pg_fatal("specify either a number of transactions (-t) or a duration (-T), not both");
7231
7232 /* Use DEFAULT_NXACTS if neither nxacts nor duration is specified. */
7233 if (nxacts <= 0 && duration <= 0)
7234 nxacts = DEFAULT_NXACTS;
7235
7236 /* --sampling-rate may be used only with -l */
7237 if (sample_rate > 0.0 && !use_log)
7238 pg_fatal("log sampling (--sampling-rate) is allowed only when logging transactions (-l)");
7239
7240 /* --sampling-rate may not be used with --aggregate-interval */
7241 if (sample_rate > 0.0 && agg_interval > 0)
7242 pg_fatal("log sampling (--sampling-rate) and aggregation (--aggregate-interval) cannot be used at the same time");
7243
7244 if (agg_interval > 0 && !use_log)
7245 pg_fatal("log aggregation is allowed only when actually logging transactions");
7246
7247 if (!use_log && logfile_prefix)
7248 pg_fatal("log file prefix (--log-prefix) is allowed only when logging transactions (-l)");
7249
7250 if (duration > 0 && agg_interval > duration)
7251 pg_fatal("number of seconds for aggregation (%d) must not be higher than test duration (%d)", agg_interval, duration);
7252
7253 if (duration > 0 && agg_interval > 0 && duration % agg_interval != 0)
7254 pg_fatal("duration (%d) must be a multiple of aggregation interval (%d)", duration, agg_interval);
7255
7256 if (progress_timestamp && progress == 0)
7257 pg_fatal("--progress-timestamp is allowed only under --progress");
7258
7259 if (!max_tries)
7260 {
7261 if (!latency_limit && duration <= 0)
7262 pg_fatal("an unlimited number of transaction tries can only be used with --latency-limit or a duration (-T)");
7263 }
7264
7265 /*
7266 * save main process id in the global variable because process id will be
7267 * changed after fork.
7268 */
7269 main_pid = (int) getpid();
7270
7271 if (nclients > 1)
7272 {
7273 state = (CState *) pg_realloc(state, sizeof(CState) * nclients);
7274 memset(state + 1, 0, sizeof(CState) * (nclients - 1));
7275
7276 /* copy any -D switch values to all clients */
7277 for (i = 1; i < nclients; i++)
7278 {
7279 int j;
7280
7281 state[i].id = i;
7282 for (j = 0; j < state[0].variables.nvars; j++)
7283 {
7284 Variable *var = &state[0].variables.vars[j];
7285
7286 if (var->value.type != PGBT_NO_VALUE)
7287 {
7288 if (!putVariableValue(&state[i].variables, "startup",
7289 var->name, &var->value))
7290 exit(1);
7291 }
7292 else
7293 {
7294 if (!putVariable(&state[i].variables, "startup",
7295 var->name, var->svalue))
7296 exit(1);
7297 }
7298 }
7299 }
7300 }
7301
7302 /* other CState initializations */
7303 for (i = 0; i < nclients; i++)
7304 {
7305 state[i].cstack = conditional_stack_create();
7306 initRandomState(&state[i].cs_func_rs);
7307 }
7308
7309 /* opening connection... */
7310 con = doConnect();
7311 if (con == NULL)
7312 pg_fatal("could not create connection for setup");
7313
7314 /* report pgbench and server versions */
7315 printVersion(con);
7316
7317 pg_log_debug("pghost: %s pgport: %s nclients: %d %s: %d dbName: %s",
7318 PQhost(con), PQport(con), nclients,
7319 duration <= 0 ? "nxacts" : "duration",
7320 duration <= 0 ? nxacts : duration, PQdb(con));
7321
7322 if (internal_script_used)
7323 GetTableInfo(con, scale_given);
7324
7325 /*
7326 * :scale variables normally get -s or database scale, but don't override
7327 * an explicit -D switch
7328 */
7329 if (lookupVariable(&state[0].variables, "scale") == NULL)
7330 {
7331 for (i = 0; i < nclients; i++)
7332 {
7333 if (!putVariableInt(&state[i].variables, "startup", "scale", scale))
7334 exit(1);
7335 }
7336 }
7337
7338 /*
7339 * Define a :client_id variable that is unique per connection. But don't
7340 * override an explicit -D switch.
7341 */
7342 if (lookupVariable(&state[0].variables, "client_id") == NULL)
7343 {
7344 for (i = 0; i < nclients; i++)
7345 if (!putVariableInt(&state[i].variables, "startup", "client_id", i))
7346 exit(1);
7347 }
7348
7349 /* set default seed for hash functions */
7350 if (lookupVariable(&state[0].variables, "default_seed") == NULL)
7351 {
7352 uint64 seed = pg_prng_uint64(&base_random_sequence);
7353
7354 for (i = 0; i < nclients; i++)
7355 if (!putVariableInt(&state[i].variables, "startup", "default_seed",
7356 (int64) seed))
7357 exit(1);
7358 }
7359
7360 /* set random seed unless overwritten */
7361 if (lookupVariable(&state[0].variables, "random_seed") == NULL)
7362 {
7363 for (i = 0; i < nclients; i++)
7364 if (!putVariableInt(&state[i].variables, "startup", "random_seed",
7365 random_seed))
7366 exit(1);
7367 }
7368
7369 if (!is_no_vacuum)
7370 {
7371 fprintf(stderr, "starting vacuum...");
7372 tryExecuteStatement(con, "vacuum pgbench_branches");
7373 tryExecuteStatement(con, "vacuum pgbench_tellers");
7374 tryExecuteStatement(con, "truncate pgbench_history");
7375 fprintf(stderr, "end.\n");
7376
7377 if (do_vacuum_accounts)
7378 {
7379 fprintf(stderr, "starting vacuum pgbench_accounts...");
7380 tryExecuteStatement(con, "vacuum analyze pgbench_accounts");
7381 fprintf(stderr, "end.\n");
7382 }
7383 }
7384 PQfinish(con);
7385
7386 /* set up thread data structures */
7387 threads = (TState *) pg_malloc(sizeof(TState) * nthreads);
7388 nclients_dealt = 0;
7389
7390 for (i = 0; i < nthreads; i++)
7391 {
7392 TState *thread = &threads[i];
7393
7394 thread->tid = i;
7395 thread->state = &state[nclients_dealt];
7396 thread->nstate =
7397 (nclients - nclients_dealt + nthreads - i - 1) / (nthreads - i);
7398 initRandomState(&thread->ts_choose_rs);
7399 initRandomState(&thread->ts_throttle_rs);
7400 initRandomState(&thread->ts_sample_rs);
7401 thread->logfile = NULL; /* filled in later */
7402 thread->latency_late = 0;
7403 initStats(&thread->stats, 0);
7404
7405 nclients_dealt += thread->nstate;
7406 }
7407
7408 /* all clients must be assigned to a thread */
7409 Assert(nclients_dealt == nclients);
7410
7411 /* get start up time for the whole computation */
7412 start_time = pg_time_now();
7413
7414 /* set alarm if duration is specified. */
7415 if (duration > 0)
7416 setalarm(duration);
7417
7418 errno = THREAD_BARRIER_INIT(&barrier, nthreads);
7419 if (errno != 0)
7420 pg_fatal("could not initialize barrier: %m");
7421
7422 /* start all threads but thread 0 which is executed directly later */
7423 for (i = 1; i < nthreads; i++)
7424 {
7425 TState *thread = &threads[i];
7426
7427 thread->create_time = pg_time_now();
7428 errno = THREAD_CREATE(&thread->thread, threadRun, thread);
7429
7430 if (errno != 0)
7431 pg_fatal("could not create thread: %m");
7432 }
7433
7434 /* compute when to stop */
7435 threads[0].create_time = pg_time_now();
7436 if (duration > 0)
7437 end_time = threads[0].create_time + (int64) 1000000 * duration;
7438
7439 /* run thread 0 directly */
7440 (void) threadRun(&threads[0]);
7441
7442 /* wait for other threads and accumulate results */
7443 initStats(&stats, 0);
7444 conn_total_duration = 0;
7445
7446 for (i = 0; i < nthreads; i++)
7447 {
7448 TState *thread = &threads[i];
7449
7450 if (i > 0)
7451 THREAD_JOIN(thread->thread);
7452
7453 for (int j = 0; j < thread->nstate; j++)
7454 if (thread->state[j].state != CSTATE_FINISHED)
7455 exit_code = 2;
7456
7457 /* aggregate thread level stats */
7458 mergeSimpleStats(&stats.latency, &thread->stats.latency);
7459 mergeSimpleStats(&stats.lag, &thread->stats.lag);
7460 stats.cnt += thread->stats.cnt;
7461 stats.skipped += thread->stats.skipped;
7462 stats.retries += thread->stats.retries;
7463 stats.retried += thread->stats.retried;
7464 stats.serialization_failures += thread->stats.serialization_failures;
7465 stats.deadlock_failures += thread->stats.deadlock_failures;
7466 latency_late += thread->latency_late;
7467 conn_total_duration += thread->conn_duration;
7468
7469 /* first recorded benchmarking start time */
7470 if (bench_start == 0 || thread->bench_start < bench_start)
7471 bench_start = thread->bench_start;
7472 }
7473
7474 /*
7475 * All connections should be already closed in threadRun(), so this
7476 * disconnect_all() will be a no-op, but clean up the connections just to
7477 * be sure. We don't need to measure the disconnection delays here.
7478 */
7479 disconnect_all(state, nclients);
7480
7481 /*
7482 * Beware that performance of short benchmarks with many threads and
7483 * possibly long transactions can be deceptive because threads do not
7484 * start and finish at the exact same time. The total duration computed
7485 * here encompasses all transactions so that tps shown is somehow slightly
7486 * underestimated.
7487 */
7488 printResults(&stats, pg_time_now() - bench_start, conn_total_duration,
7489 bench_start - start_time, latency_late);
7490
7491 THREAD_BARRIER_DESTROY(&barrier);
7492
7493 if (exit_code != 0)
7494 pg_log_error("Run was aborted; the above results are incomplete.");
7495
7496 return exit_code;
7497 }
7498
7499 static THREAD_FUNC_RETURN_TYPE THREAD_FUNC_CC
7500 threadRun(void *arg)
7501 {
7502 TState *thread = (TState *) arg;
7503 CState *state = thread->state;
7504 pg_time_usec_t start;
7505 int nstate = thread->nstate;
7506 int remains = nstate; /* number of remaining clients */
7507 socket_set *sockets = alloc_socket_set(nstate);
7508 int64 thread_start,
7509 last_report,
7510 next_report;
7511 StatsData last,
7512 aggs;
7513
7514 /* open log file if requested */
7515 if (use_log)
7516 {
7517 char logpath[MAXPGPATH];
7518 char *prefix = logfile_prefix ? logfile_prefix : "pgbench_log";
7519
7520 if (thread->tid == 0)
7521 snprintf(logpath, sizeof(logpath), "%s.%d", prefix, main_pid);
7522 else
7523 snprintf(logpath, sizeof(logpath), "%s.%d.%d", prefix, main_pid, thread->tid);
7524
7525 thread->logfile = fopen(logpath, "w");
7526
7527 if (thread->logfile == NULL)
7528 pg_fatal("could not open logfile \"%s\": %m", logpath);
7529 }
7530
7531 /* explicitly initialize the state machines */
7532 for (int i = 0; i < nstate; i++)
7533 state[i].state = CSTATE_CHOOSE_SCRIPT;
7534
7535 /* READY */
7536 THREAD_BARRIER_WAIT(&barrier);
7537
7538 thread_start = pg_time_now();
7539 thread->started_time = thread_start;
7540 thread->conn_duration = 0;
7541 last_report = thread_start;
7542 next_report = last_report + (int64) 1000000 * progress;
7543
7544 /* STEADY */
7545 if (!is_connect)
7546 {
7547 /* make connections to the database before starting */
7548 for (int i = 0; i < nstate; i++)
7549 {
7550 if ((state[i].con = doConnect()) == NULL)
7551 {
7552 /* coldly abort on initial connection failure */
7553 pg_fatal("could not create connection for client %d",
7554 state[i].id);
7555 }
7556 }
7557 }
7558
7559 /* GO */
7560 THREAD_BARRIER_WAIT(&barrier);
7561
7562 start = pg_time_now();
7563 thread->bench_start = start;
7564 thread->throttle_trigger = start;
7565
7566 /*
7567 * The log format currently has Unix epoch timestamps with whole numbers
7568 * of seconds. Round the first aggregate's start time down to the nearest
7569 * Unix epoch second (the very first aggregate might really have started a
7570 * fraction of a second later, but later aggregates are measured from the
7571 * whole number time that is actually logged).
7572 */
7573 initStats(&aggs, (start + epoch_shift) / 1000000 * 1000000);
7574 last = aggs;
7575
7576 /* loop till all clients have terminated */
7577 while (remains > 0)
7578 {
7579 int nsocks; /* number of sockets to be waited for */
7580 pg_time_usec_t min_usec;
7581 pg_time_usec_t now = 0; /* set this only if needed */
7582
7583 /*
7584 * identify which client sockets should be checked for input, and
7585 * compute the nearest time (if any) at which we need to wake up.
7586 */
7587 clear_socket_set(sockets);
7588 nsocks = 0;
7589 min_usec = PG_INT64_MAX;
7590 for (int i = 0; i < nstate; i++)
7591 {
7592 CState *st = &state[i];
7593
7594 if (st->state == CSTATE_SLEEP || st->state == CSTATE_THROTTLE)
7595 {
7596 /* a nap from the script, or under throttling */
7597 pg_time_usec_t this_usec;
7598
7599 /* get current time if needed */
7600 pg_time_now_lazy(&now);
7601
7602 /* min_usec should be the minimum delay across all clients */
7603 this_usec = (st->state == CSTATE_SLEEP ?
7604 st->sleep_until : st->txn_scheduled) - now;
7605 if (min_usec > this_usec)
7606 min_usec = this_usec;
7607 }
7608 else if (st->state == CSTATE_WAIT_RESULT ||
7609 st->state == CSTATE_WAIT_ROLLBACK_RESULT)
7610 {
7611 /*
7612 * waiting for result from server - nothing to do unless the
7613 * socket is readable
7614 */
7615 int sock = PQsocket(st->con);
7616
7617 if (sock < 0)
7618 {
7619 pg_log_error("invalid socket: %s", PQerrorMessage(st->con));
7620 goto done;
7621 }
7622
7623 add_socket_to_set(sockets, sock, nsocks++);
7624 }
7625 else if (st->state != CSTATE_ABORTED &&
7626 st->state != CSTATE_FINISHED)
7627 {
7628 /*
7629 * This client thread is ready to do something, so we don't
7630 * want to wait. No need to examine additional clients.
7631 */
7632 min_usec = 0;
7633 break;
7634 }
7635 }
7636
7637 /* also wake up to print the next progress report on time */
7638 if (progress && min_usec > 0 && thread->tid == 0)
7639 {
7640 pg_time_now_lazy(&now);
7641
7642 if (now >= next_report)
7643 min_usec = 0;
7644 else if ((next_report - now) < min_usec)
7645 min_usec = next_report - now;
7646 }
7647
7648 /*
7649 * If no clients are ready to execute actions, sleep until we receive
7650 * data on some client socket or the timeout (if any) elapses.
7651 */
7652 if (min_usec > 0)
7653 {
7654 int rc = 0;
7655
7656 if (min_usec != PG_INT64_MAX)
7657 {
7658 if (nsocks > 0)
7659 {
7660 rc = wait_on_socket_set(sockets, min_usec);
7661 }
7662 else /* nothing active, simple sleep */
7663 {
7664 pg_usleep(min_usec);
7665 }
7666 }
7667 else /* no explicit delay, wait without timeout */
7668 {
7669 rc = wait_on_socket_set(sockets, 0);
7670 }
7671
7672 if (rc < 0)
7673 {
7674 if (errno == EINTR)
7675 {
7676 /* On EINTR, go back to top of loop */
7677 continue;
7678 }
7679 /* must be something wrong */
7680 pg_log_error("%s() failed: %m", SOCKET_WAIT_METHOD);
7681 goto done;
7682 }
7683 }
7684 else
7685 {
7686 /* min_usec <= 0, i.e. something needs to be executed now */
7687
7688 /* If we didn't wait, don't try to read any data */
7689 clear_socket_set(sockets);
7690 }
7691
7692 /* ok, advance the state machine of each connection */
7693 nsocks = 0;
7694 for (int i = 0; i < nstate; i++)
7695 {
7696 CState *st = &state[i];
7697
7698 if (st->state == CSTATE_WAIT_RESULT ||
7699 st->state == CSTATE_WAIT_ROLLBACK_RESULT)
7700 {
7701 /* don't call advanceConnectionState unless data is available */
7702 int sock = PQsocket(st->con);
7703
7704 if (sock < 0)
7705 {
7706 pg_log_error("invalid socket: %s", PQerrorMessage(st->con));
7707 goto done;
7708 }
7709
7710 if (!socket_has_input(sockets, sock, nsocks++))
7711 continue;
7712 }
7713 else if (st->state == CSTATE_FINISHED ||
7714 st->state == CSTATE_ABORTED)
7715 {
7716 /* this client is done, no need to consider it anymore */
7717 continue;
7718 }
7719
7720 advanceConnectionState(thread, st, &aggs);
7721
7722 /*
7723 * If --exit-on-abort is used, the program is going to exit when
7724 * any client is aborted.
7725 */
7726 if (exit_on_abort && st->state == CSTATE_ABORTED)
7727 goto done;
7728
7729 /*
7730 * If advanceConnectionState changed client to finished state,
7731 * that's one fewer client that remains.
7732 */
7733 else if (st->state == CSTATE_FINISHED ||
7734 st->state == CSTATE_ABORTED)
7735 remains--;
7736 }
7737
7738 /* progress report is made by thread 0 for all threads */
7739 if (progress && thread->tid == 0)
7740 {
7741 pg_time_usec_t now2 = pg_time_now();
7742
7743 if (now2 >= next_report)
7744 {
7745 /*
7746 * Horrible hack: this relies on the thread pointer we are
7747 * passed to be equivalent to threads[0], that is the first
7748 * entry of the threads array. That is why this MUST be done
7749 * by thread 0 and not any other.
7750 */
7751 printProgressReport(thread, thread_start, now2,
7752 &last, &last_report);
7753
7754 /*
7755 * Ensure that the next report is in the future, in case
7756 * pgbench/postgres got stuck somewhere.
7757 */
7758 do
7759 {
7760 next_report += (int64) 1000000 * progress;
7761 } while (now2 >= next_report);
7762 }
7763 }
7764 }
7765
7766 done:
7767 if (exit_on_abort)
7768 {
7769 /*
7770 * Abort if any client is not finished, meaning some error occurred.
7771 */
7772 for (int i = 0; i < nstate; i++)
7773 {
7774 if (state[i].state != CSTATE_FINISHED)
7775 {
7776 pg_log_error("Run was aborted due to an error in thread %d",
7777 thread->tid);
7778 exit(2);
7779 }
7780 }
7781 }
7782
7783 disconnect_all(state, nstate);
7784
7785 if (thread->logfile)
7786 {
7787 if (agg_interval > 0)
7788 {
7789 /* log aggregated but not yet reported transactions */
7790 doLog(thread, state, &aggs, false, 0, 0);
7791 }
7792 fclose(thread->logfile);
7793 thread->logfile = NULL;
7794 }
7795 free_socket_set(sockets);
7796 THREAD_FUNC_RETURN;
7797 }
7798
7799 static void
7800 finishCon(CState *st)
7801 {
7802 if (st->con != NULL)
7803 {
7804 PQfinish(st->con);
7805 st->con = NULL;
7806 }
7807 }
7808
7809 /*
7810 * Support for duration option: set timer_exceeded after so many seconds.
7811 */
7812
7813 #ifndef WIN32
7814
7815 static void
7816 handle_sig_alarm(SIGNAL_ARGS)
7817 {
7818 timer_exceeded = true;
7819 }
7820
7821 static void
7822 setalarm(int seconds)
7823 {
7824 pqsignal(SIGALRM, handle_sig_alarm);
7825 alarm(seconds);
7826 }
7827
7828 #else /* WIN32 */
7829
7830 static VOID CALLBACK
7831 win32_timer_callback(PVOID lpParameter, BOOLEAN TimerOrWaitFired)
7832 {
7833 timer_exceeded = true;
7834 }
7835
7836 static void
7837 setalarm(int seconds)
7838 {
7839 HANDLE queue;
7840 HANDLE timer;
7841
7842 /* This function will be called at most once, so we can cheat a bit. */
7843 queue = CreateTimerQueue();
7844 if (seconds > ((DWORD) -1) / 1000 ||
7845 !CreateTimerQueueTimer(&timer, queue,
7846 win32_timer_callback, NULL, seconds * 1000, 0,
7847 WT_EXECUTEINTIMERTHREAD | WT_EXECUTEONLYONCE))
7848 pg_fatal("failed to set timer");
7849 }
7850
7851 #endif /* WIN32 */
7852
7853
7854 /*
7855 * These functions provide an abstraction layer that hides the syscall
7856 * we use to wait for input on a set of sockets.
7857 *
7858 * Currently there are two implementations, based on ppoll(2) and select(2).
7859 * ppoll() is preferred where available due to its typically higher ceiling
7860 * on the number of usable sockets. We do not use the more-widely-available
7861 * poll(2) because it only offers millisecond timeout resolution, which could
7862 * be problematic with high --rate settings.
7863 *
7864 * Function APIs:
7865 *
7866 * alloc_socket_set: allocate an empty socket set with room for up to
7867 * "count" sockets.
7868 *
7869 * free_socket_set: deallocate a socket set.
7870 *
7871 * clear_socket_set: reset a socket set to empty.
7872 *
7873 * add_socket_to_set: add socket with indicated FD to slot "idx" in the
7874 * socket set. Slots must be filled in order, starting with 0.
7875 *
7876 * wait_on_socket_set: wait for input on any socket in set, or for timeout
7877 * to expire. timeout is measured in microseconds; 0 means wait forever.
7878 * Returns result code of underlying syscall (>=0 if OK, else see errno).
7879 *
7880 * socket_has_input: after waiting, call this to see if given socket has
7881 * input. fd and idx parameters should match some previous call to
7882 * add_socket_to_set.
7883 *
7884 * Note that wait_on_socket_set destructively modifies the state of the
7885 * socket set. After checking for input, caller must apply clear_socket_set
7886 * and add_socket_to_set again before waiting again.
7887 */
7888
7889 #ifdef POLL_USING_PPOLL
7890
7891 static socket_set *
7892 alloc_socket_set(int count)
7893 {
7894 socket_set *sa;
7895
7896 sa = (socket_set *) pg_malloc0(offsetof(socket_set, pollfds) +
7897 sizeof(struct pollfd) * count);
7898 sa->maxfds = count;
7899 sa->curfds = 0;
7900 return sa;
7901 }
7902
7903 static void
7904 free_socket_set(socket_set *sa)
7905 {
7906 pg_free(sa);
7907 }
7908
7909 static void
7910 clear_socket_set(socket_set *sa)
7911 {
7912 sa->curfds = 0;
7913 }
7914
7915 static void
7916 add_socket_to_set(socket_set *sa, int fd, int idx)
7917 {
7918 Assert(idx < sa->maxfds && idx == sa->curfds);
7919 sa->pollfds[idx].fd = fd;
7920 sa->pollfds[idx].events = POLLIN;
7921 sa->pollfds[idx].revents = 0;
7922 sa->curfds++;
7923 }
7924
7925 static int
7926 wait_on_socket_set(socket_set *sa, int64 usecs)
7927 {
7928 if (usecs > 0)
7929 {
7930 struct timespec timeout;
7931
7932 timeout.tv_sec = usecs / 1000000;
7933 timeout.tv_nsec = (usecs % 1000000) * 1000;
7934 return ppoll(sa->pollfds, sa->curfds, &timeout, NULL);
7935 }
7936 else
7937 {
7938 return ppoll(sa->pollfds, sa->curfds, NULL, NULL);
7939 }
7940 }
7941
7942 static bool
7943 socket_has_input(socket_set *sa, int fd, int idx)
7944 {
7945 /*
7946 * In some cases, threadRun will apply clear_socket_set and then try to
7947 * apply socket_has_input anyway with arguments that it used before that,
7948 * or might've used before that except that it exited its setup loop
7949 * early. Hence, if the socket set is empty, silently return false
7950 * regardless of the parameters. If it's not empty, we can Assert that
7951 * the parameters match a previous call.
7952 */
7953 if (sa->curfds == 0)
7954 return false;
7955
7956 Assert(idx < sa->curfds && sa->pollfds[idx].fd == fd);
7957 return (sa->pollfds[idx].revents & POLLIN) != 0;
7958 }
7959
7960 #endif /* POLL_USING_PPOLL */
7961
7962 #ifdef POLL_USING_SELECT
7963
7964 static socket_set *
7965 alloc_socket_set(int count)
7966 {
7967 return (socket_set *) pg_malloc0(sizeof(socket_set));
7968 }
7969
7970 static void
7971 free_socket_set(socket_set *sa)
7972 {
7973 pg_free(sa);
7974 }
7975
7976 static void
7977 clear_socket_set(socket_set *sa)
7978 {
7979 FD_ZERO(&sa->fds);
7980 sa->maxfd = -1;
7981 }
7982
7983 static void
7984 add_socket_to_set(socket_set *sa, int fd, int idx)
7985 {
7986 /* See connect_slot() for background on this code. */
7987 #ifdef WIN32
7988 if (sa->fds.fd_count + 1 >= FD_SETSIZE)
7989 {
7990 pg_log_error("too many concurrent database clients for this platform: %d",
7991 sa->fds.fd_count + 1);
7992 exit(1);
7993 }
7994 #else
7995 if (fd < 0 || fd >= FD_SETSIZE)
7996 {
7997 pg_log_error("socket file descriptor out of range for select(): %d",
7998 fd);
7999 pg_log_error_hint("Try fewer concurrent database clients.");
8000 exit(1);
8001 }
8002 #endif
8003 FD_SET(fd, &sa->fds);
8004 if (fd > sa->maxfd)
8005 sa->maxfd = fd;
8006 }
8007
8008 static int
8009 wait_on_socket_set(socket_set *sa, int64 usecs)
8010 {
8011 if (usecs > 0)
8012 {
8013 struct timeval timeout;
8014
8015 timeout.tv_sec = usecs / 1000000;
8016 timeout.tv_usec = usecs % 1000000;
8017 return select(sa->maxfd + 1, &sa->fds, NULL, NULL, &timeout);
8018 }
8019 else
8020 {
8021 return select(sa->maxfd + 1, &sa->fds, NULL, NULL, NULL);
8022 }
8023 }
8024
8025 static bool
8026 socket_has_input(socket_set *sa, int fd, int idx)
8027 {
8028 return (FD_ISSET(fd, &sa->fds) != 0);
8029 }
8030
8031 #endif /* POLL_USING_SELECT */