diff --git a/src/sqlancer/voltdb/README.md b/src/sqlancer/voltdb/README.md index 0b8e6b746..ac8347044 100644 --- a/src/sqlancer/voltdb/README.md +++ b/src/sqlancer/voltdb/README.md @@ -4,7 +4,7 @@ A SQLancer provider for [VoltDB](https://www.voltactivedata.com/), developed for VoltDB schemas, both replicated and partitioned tables, fills them with single-row inserts, upserts, updates and deletes, and runs SQLancer's oracles against them through the VoltDB JDBC driver. -**Status: milestone 49.** The provider creates schemas and data and runs these logic-bug oracles: NoREC (the default, +**Status: milestone 50.** The provider creates schemas and data and runs these logic-bug oracles: NoREC (the default, milestone 2), TLP WHERE (milestone 3), TLP DISTINCT, TLP HAVING and TLP AGGREGATE (milestone 5), PQS (milestone 6), and PARAMS, literals against JDBC parameters (milestone 8). Since milestone 9 each database's rows are also updated, upserted and deleted before the oracles run. Since milestone 10 each database also has materialized views, which the @@ -65,6 +65,8 @@ Since milestone 47 the HTTP target sends form pairs by POST, PUT or GET, signed Since milestone 48 every other node failure is a graceful `voltadmin stop`, and every other crash a `voltadmin shutdown --save`; see [Graceful stops and shutdowns](#graceful-stops-and-shutdowns-milestone-48). Since milestone 49 `--xdcr` runs can kill nodes too; see [XDCR with node failures](#xdcr-with-node-failures-milestone-49). +Since milestone 50 the JAVAPROC oracle compiles Java stored procedures, compound ones included, loads them with +`@UpdateClasses` and checks what they return and leave; see [The JAVAPROC oracle](#the-javaproc-oracle). `SMOKE`, from milestone 1, only reads every table and checks that the queries succeed. `voltdb/run-sqlancer.sh` (milestone 4) starts a cluster, runs SQLancer against it and saves the results. A nightly lab job (milestone 7) runs it against master's kit; @@ -1346,6 +1348,74 @@ and 32 user changes refused. In run-coverage.sh's 10-minute security run, agains (from 19), `SetYamlConfiguration` 294 of 396 (from 173), `YamlUtils.PropertyParser` 56 of 68 (from 34); security as a whole 26.3% of its lines (from 23.4%). The rest is mostly LDAP and Kerberos, which need servers of their own. +## The JAVAPROC oracle + +Milestone 50. Every procedure the other oracles create is one SQL statement in DDL, so milestone 49's coverage found +the rest of VoltDB's procedure support never run: compound procedures (`CompoundProcedureRunner`, 0 of 180 lines), +`@UpdateClasses` and its checks (`UpdateClassesAcceptancePolicy`, 2 of 23), the procedure compiler's class paths +(`ProcedureCompiler`, 103 of 467), and the multi-batch, abort and expectation paths of `ProcedureRunnerImpl`. + +Each JAVAPROC check writes the Java source of four classes over its own table, `XJ_` (partitioned on k, no +database's), compiles them in SQLancer's JVM (`javax.tools`) against the kit's jars, which run-sqlancer.sh passes as +`--procedure-classpath` (`lib/volt-procedure-api-*.jar`, `voltdb/voltdb-*.jar`, `voltdb/voltdbclient-*.jar`), loads them +with `@UpdateClasses`, and creates the procedures `FROM CLASS`: + +- `JPS__`, single-partition on k: inserts its rows for k in batches of 1 to 5 (`voltExecuteSQL()` per batch, + `EXPECT_SCALAR_MATCH(1)` on each insert, a column from `getSeededRandomNumberGenerator()`, which k-safe replicas must + agree on), reads them back (`EXPECT_ONE_ROW`), and returns its class's version, the count, the sum and + `getUniqueId()`, with an app status; or, by its mode, then aborts (`VoltAbortException`, USER_ABORT), throws + (UNEXPECTED_FAILURE), fails an expectation (`EXPECT_EMPTY`, USER_ABORT), or inserts a duplicate key + (GRACEFUL_FAILURE); +- `JPM__`, multi-partition: the same over 2 to 7 keys, so on several partitions in one transaction; +- `JPC__`, compound (`CREATE COMPOUND PROCEDURE`): its first stage calls JPS for 1 to 4 keys, the last one + failing in a third of the calls, and its second stage, by its mode, completes with the sum of the counts (or aborts + if a call failed), completes with a table, throws `CompoundProcAbortException` (COMPOUND_PROC_USER_ABORT) or another + exception (UNEXPECTED_FAILURE), returns without completing ("end of stage list reached"), queues one more call and + completes, so that the call is never sent, or sets the app status and completes; or the procedure sets up no stages, + calls itself (refused: "nested call"), or queues more calls than a stage may (10); +- `JPN__`, a non-transactional procedure class (`VoltNonTransactionalProcedure`), which VoltDB creates procedures + from only in its own tests. + +Each call writes keys no other call wrote, so the rows it must leave are known: all of them when it succeeds, none when +it fails, its transaction rolled back whole. A compound procedure is not one transaction: the rows of each JPS call it +made that succeeded stay, whatever the compound procedure returns, and a call queued in the stage that completed must +leave no row. When a node failure interrupts a call (in a kill, crash, resize or upgrade run), it may or may not have +committed, but it must have committed whole: all its rows, on every partition, or none; JAVAPROC checks that, then +skips the rest of the check. + +Then one of: + +1. the classes replaced by a new version (`@UpdateClasses` again), which the next call must run; +2. the class of a procedure in use removed, which must be refused ("cannot be removed, it is being used by procedure"); +3. a class whose static initializer throws loaded, which must be refused, and not listed by `@SystemCatalog CLASSES`; +4. a procedure created from a class of the wrong kind, which must be refused: `CREATE PROCEDURE` from JPN or JPC, or + `CREATE COMPOUND PROCEDURE` from JPS; +5. a procedure partitioned on a parameter its class does not have, which must be refused; +6. nothing. + +In the end the procedures are dropped and the classes removed, and `@SystemCatalog CLASSES` must no longer list them. +`@UpdateClasses` also loads and removes the classes on the mirror and the XDCR peer, where the provider repeats the +DDL; the calls and their rows are on this cluster only. At exit JAVAPROC prints its checks, the calls checked by kind, +the failures checked, the calls a node failure interrupted, the classes replaced and the class changes refused; the +summary has the line. Without `--procedure-classpath`, or on a JRE without a compiler, it skips every check. + +A user change by `@SetYamlConfiguration` that races an `@UpdateClasses` reaches the deployment but not the catalog, so +a removed user still logs in (ENG-30710). While avoiding known bugs, JAVAPROC's `@UpdateClasses` calls hold the lock +that LOGIN's and CONFIG's checks hold, so classes change only between them. A classes change also restarts a task that +`ON ERROR STOP` stopped (ENG-30711), so they wait for TASK's checks too. + +In local 90- to 300-second trials (JAVAPROC alone on 1 node; with TASK and STATS on 3 nodes with a kill every 60 s; +beside XDCR; beside DIFF with a 16.0.0 mirror) every check passed: 48 to 78 checks and 191 to 309 calls per trial, the +mirror and the XDCR peer creating the same procedures. In lab build #64's 30-minute kill run: 213 checks, 833 calls +(362 single-partition, 240 multi-partition, 231 compound), 346 failures checked, 38 classes replaced, 137 class changes +refused; in its upgrade run, from 16.0.0 in service: 243 checks, 970 calls. Its security run found ENG-30710 (LOGIN's +removed users logging in), which JAVAPROC now avoids; the security run of build #65 then found ENG-30711 (TASK's stopped +tasks restarted), which it avoids as well. In run-coverage.sh's 10-minute kill run, against the best of milestones 44 to 49: `CompoundProcedureRunner` +143 of 183 lines (from 0), `VoltCompoundProcedure` 31 of 35 (from 0), `ProcedureCompiler` 296 of 477 (from 108), +`UpdateApplicationBase` 249 of 378 (from 193), `NTProcedureService` 187 of 236 (from 137), `ClassMatcher` 32 of 84 +(from 7), `CreateProcedureFromClass` 27 of 39 (from 5), `UpdateClassesAcceptancePolicy` 16 of 23 (from 2), +`InMemoryJarfile` 173 of 269 (from 146); 813 lines more in 38 classes. + ## The STREAMS oracle A stream cannot be read, so STREAMS puts each row into a stream and into a shadow table with the same columns, and @@ -1964,6 +2034,9 @@ The bugs below were found in milestones 43, 46, 47 and 48. | ENG-30696 | DDL fails with "Unable to find reference for catalog item" while `voltadmin stop` takes a node out: the stopping node verifies catalog updates it no longer applies. Lab build #56's upgrade run, on 16.0.0; not reproduced locally. Major. | The error counts as a node failure (VoltDBErrors). | | ENG-30704 | A node stopped with `voltadmin stop` sometimes logs FATAL partition detection ("fewer than half of the previous servers") after it has shut down, as the survivors hang up on it before its JVM exits. Milestone 48's graceful stops, under load only; no reliable reproduction. Minor. | FATAL lines a stopped node logs after its shutdown are not counted (`chaos.excluded`). | | ENG-30705 | A task that `ON ERROR STOP` has stopped runs again after the node that ran it fails: the node that takes over starts its scheduler again (RUNNING) and runs the procedure once more. Found by TASK in lab build #61's kill run; `repros/ENG-30705.sh`; 16.0.0 too. Major. | While `--avoid-known-bugs` is true and nodes fail, TASK does not check the state of a task stopped by an error (the row counts still are). | +| ENG-30708 | During an elastic join, the join's own index snapshot failed on some partitions ("Elastic streaming was invoked without proper activation", "Table streamer has no streams to serialize more"), and the join stayed at "Building index for data migration"; the next command-log truncation snapshot was refused by the engine ("COW context activation is not allowed while elastic indexing is in progress") and every original node crashed ("Failed to activate snapshot stream"), losing the cluster. Found by run-coverage.sh's resize run (milestone 50), once in two runs of the same seed; not reduced: snapshot saves, truncation snapshots and table swaps during a join did not reproduce it alone. Blocker. | None: a resize run can fail with FATAL lines. | +| ENG-30710 | A user removed by `@SetYamlConfiguration` (`.users[name]=null`) still logs in when an `@UpdateClasses` runs at the same time: `@GetYamlConfiguration` no longer lists the user, but the update applies with the catalog unchanged (`securityChange=false`), so authentication keeps the user until the next catalog change. 16.0.0 too. Found by LOGIN beside JAVAPROC (milestone 50) in lab build #64's security run; `repros/ENG-30710.sh` (with `repros/users/RemovedUserRepro.java`) reproduces it at the first user. Critical. | While `--avoid-known-bugs` is true, JAVAPROC's `@UpdateClasses` calls hold the lock LOGIN and CONFIG share. | +| ENG-30711 | `@UpdateClasses` restarts a task that `ON ERROR STOP` stopped: with classes changed, `TaskManager` recreates every task's handler, the stopped one included, which shows RUNNING and runs its procedure again. An ordinary DDL change does not. 16.0.0 too. Found by TASK beside JAVAPROC (milestone 50) in lab build #65's security run; `repros/ENG-30711.sh`. Major. | While `--avoid-known-bugs` is true, TASK's checks and JAVAPROC's `@UpdateClasses` calls exclude each other (a read-write lock). | The bugs below were found in lab build #53 and in milestone 41. diff --git a/src/sqlancer/voltdb/VoltDBOptions.java b/src/sqlancer/voltdb/VoltDBOptions.java index a423cc50c..a8614d227 100644 --- a/src/sqlancer/voltdb/VoltDBOptions.java +++ b/src/sqlancer/voltdb/VoltDBOptions.java @@ -83,6 +83,9 @@ public class VoltDBOptions implements DBMSSpecificOptions { @Parameter(names = "--mirror", description = "Comma-separated host:port client addresses of a second cluster, normally running another VoltDB version: every statement that changes the database is repeated on it, and the DIFF oracle compares the two clusters' rows for the same query") public String mirror; + @Parameter(names = "--procedure-classpath", description = "The VoltDB jars (colon-separated) that Java stored procedures compile against (run-sqlancer.sh passes the kit's): the JAVAPROC oracle compiles its procedure classes with them; without it, JAVAPROC does nothing") + public String procedureClasspath; + @Parameter(names = "--servers", description = "Comma-separated host:port client addresses of every node; SQLancer connects to all of them, so it keeps working while any one node is down (used instead of --host and --port)") public String servers; diff --git a/src/sqlancer/voltdb/VoltDBOracleFactory.java b/src/sqlancer/voltdb/VoltDBOracleFactory.java index 4938b331a..ba262949c 100644 --- a/src/sqlancer/voltdb/VoltDBOracleFactory.java +++ b/src/sqlancer/voltdb/VoltDBOracleFactory.java @@ -13,6 +13,7 @@ import sqlancer.voltdb.oracle.VoltDBDurabilityOracle; import sqlancer.voltdb.oracle.VoltDBGeographyOracle; import sqlancer.voltdb.oracle.VoltDBImportOracle; +import sqlancer.voltdb.oracle.VoltDBJavaProcedureOracle; import sqlancer.voltdb.oracle.VoltDBLimitOracle; import sqlancer.voltdb.oracle.VoltDBLoginOracle; import sqlancer.voltdb.oracle.VoltDBParameterOracle; @@ -263,6 +264,17 @@ public TestOracle create(VoltDBGlobalState globalState) { return new VoltDBLoginOracle(globalState); } }, + /** + * Java stored procedures (milestone 50): single-partition, multi-partition and compound procedure classes compiled + * and loaded with @UpdateClasses return what they wrote, roll back whole when they fail, run the new version once + * replaced, and are refused what VoltDB must refuse. + */ + JAVAPROC { + @Override + public TestOracle create(VoltDBGlobalState globalState) { + return new VoltDBJavaProcedureOracle(globalState); + } + }, /** * Permissions, with --security: the users reader (SQLREAD) and writer (SQL) may run what their roles allow and diff --git a/src/sqlancer/voltdb/oracle/VoltDBJavaProcedureOracle.java b/src/sqlancer/voltdb/oracle/VoltDBJavaProcedureOracle.java new file mode 100644 index 000000000..d1c161097 --- /dev/null +++ b/src/sqlancer/voltdb/oracle/VoltDBJavaProcedureOracle.java @@ -0,0 +1,763 @@ +package sqlancer.voltdb.oracle; + +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.OutputStream; +import java.net.URI; +import java.nio.charset.StandardCharsets; +import java.sql.CallableStatement; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.sql.Statement; +import java.sql.Types; +import java.util.ArrayList; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.atomic.AtomicLong; +import java.util.jar.JarEntry; +import java.util.jar.JarOutputStream; +import javax.tools.DiagnosticCollector; +import javax.tools.FileObject; +import javax.tools.ForwardingJavaFileManager; +import javax.tools.JavaCompiler; +import javax.tools.JavaFileManager; +import javax.tools.JavaFileObject; +import javax.tools.SimpleJavaFileObject; +import javax.tools.StandardJavaFileManager; +import javax.tools.ToolProvider; + +import org.voltdb.client.ClientResponse; +import org.voltdb.client.ProcCallException; + +import sqlancer.IgnoreMeException; +import sqlancer.Randomly; +import sqlancer.Reproducer; +import sqlancer.common.oracle.TestOracle; +import sqlancer.voltdb.VoltDBConnection; +import sqlancer.voltdb.VoltDBErrors; +import sqlancer.voltdb.VoltDBOptions; +import sqlancer.voltdb.VoltDBProvider.VoltDBGlobalState; + +/** + * Java stored procedures (milestone 50). Every procedure the other oracles make is one SQL statement in DDL, so + * milestone 49's coverage found the rest of VoltDB's procedure support unexercised: compound procedures + * ({@code CompoundProcedureRunner}, none of it), {@code @UpdateClasses} and its checks, the procedure compiler's class + * paths, and the multi-batch, abort and expectation paths of {@code ProcedureRunnerImpl}. + *

+ * Each check writes the Java source of four classes over {@code XJ_} (partitioned on k), compiles them in + * SQLancer's JVM against the kit's jars (--procedure-classpath), loads them with {@code @UpdateClasses} and creates the + * procedures {@code FROM CLASS}: + *

    + *
  • single-partition (JPS): inserts n rows for its key in batches, reads them back, and returns its class's version, + * the count and the sum; or, by its mode, then aborts ({@code VoltAbortException}), throws, fails an expectation + * ({@code EXPECT_EMPTY}) or violates the primary key;
  • + *
  • multi-partition (JPM): the same over several keys, so across partitions;
  • + *
  • compound (JPC, {@code CREATE COMPOUND PROCEDURE}): calls JPS for several keys in its first stage, and in its + * second completes (with a number or a table), aborts, throws, never completes, queues calls it completes before + * sending, or sets the response's app status; or calls itself (refused), queues more calls than a stage may, or sets up + * no stages;
  • + *
+ * and a non-transactional procedure class (JPN), which VoltDB creates procedures from only in its own tests. Every key + * a call writes is new, so the rows a call leaves are known: all of them when it succeeds, none when it fails. A + * compound procedure is not one transaction: the rows of each JPS call it made that succeeded stay, whatever it + * returns. When a node failure interrupts a call (with --node-failures and the like) the call may or may not have + * committed, but it must have committed whole: all its rows, on every partition, or none. + *

+ * Then one of: the classes replaced by a new version, which the next call must run; the class of a procedure in use + * removed, which must be refused; a class whose static initializer throws loaded, which must be refused; a procedure + * created from a class of the wrong kind (CREATE PROCEDURE from JPN or JPC, CREATE COMPOUND PROCEDURE from JPS), or + * with a partition parameter it does not have, which must be refused. In the end the procedures are dropped and the + * classes removed, and {@code @SystemCatalog CLASSES} must no longer list them. + *

+ * The classes are also loaded into the mirror (--mirror) and the XDCR peer (--xdcr), where the DDL is repeated; the + * calls and their rows are on this cluster only, and XJ tables are no database's. + */ +public class VoltDBJavaProcedureOracle implements TestOracle { + + private static final String PACKAGE = "sqlancer_jp"; + private static final AtomicLong IDS = new AtomicLong(); + private static final AtomicLong CHECKS = new AtomicLong(); + private static final AtomicLong CALLS = new AtomicLong(); + private static final AtomicLong SP_CALLS = new AtomicLong(); + private static final AtomicLong MP_CALLS = new AtomicLong(); + private static final AtomicLong COMPOUND_CALLS = new AtomicLong(); + private static final AtomicLong FAILURES = new AtomicLong(); + private static final AtomicLong INTERRUPTED = new AtomicLong(); + private static final AtomicLong REPLACED = new AtomicLong(); + private static final AtomicLong REFUSED = new AtomicLong(); + private static final Set CREATED = ConcurrentHashMap.newKeySet(); + // compiling is CPU-heavy: one thread at a time + private static final Object COMPILE = new Object(); + + static { + Runtime.getRuntime() + .addShutdownHook(new Thread(() -> System.out.println("JAVAPROC checks: " + CHECKS + "; calls checked: " + + CALLS + " (single-partition " + SP_CALLS + ", multi-partition " + MP_CALLS + ", compound " + + COMPOUND_CALLS + "); failures checked: " + FAILURES + + "; calls interrupted by a node failure, checked whole: " + INTERRUPTED + + "; classes replaced: " + REPLACED + "; class changes refused: " + REFUSED))); + } + + // a JPS or JPM call's mode, and the status it must end with + private enum Mode { + OK(ClientResponse.SUCCESS), ABORT(ClientResponse.USER_ABORT), THROW(ClientResponse.UNEXPECTED_FAILURE), + EXPECTATION(ClientResponse.USER_ABORT), CONSTRAINT(ClientResponse.GRACEFUL_FAILURE); + + final byte status; + + Mode(byte status) { + this.status = status; + } + } + + // a JPC call's mode + private enum Compound { + // completes with the sum of the JPS calls' counts, or aborts if one failed + SUM, TABLE, THROW_ABORT, THROW, NO_STAGES, NOT_COMPLETED, NESTED, TOO_MANY, DROPPED, APP_STATUS + } + + private enum FollowUp { + NONE, REPLACE, REMOVE_IN_USE, BAD_CLASS, BAD_BASE, BAD_PARTITION + } + + private final VoltDBGlobalState state; + private String lastQuery; + // the next key of this check + private long nextKey; + private boolean failures; + + public VoltDBJavaProcedureOracle(VoltDBGlobalState state) { + this.state = state; + } + + @Override + public void check() throws Exception { + VoltDBOptions o = state.getDbmsSpecificOptions(); + if (o.procedureClasspath == null || o.procedureClasspath.isBlank() + || ToolProvider.getSystemJavaCompiler() == null) { + throw new IgnoreMeException(); + } + failures = o.nodeFailures || o.crashes || o.resizes || o.upgrades; + String db = state.getDatabaseName().toUpperCase(); + String table = "XJ_" + db; + create(table); + long id = IDS.incrementAndGet(); + String suffix = db + "_" + id; + Names n = new Names(suffix); + nextKey = id * 1000; + long version = 1 + Randomly.getNotCachedInteger(0, 1000); + int batch = (int) Randomly.getNotCachedInteger(1, 6); + updateClasses(jar(compile(sources(table, n, version, batch))), null, true); + List procedures = new ArrayList<>(); + try { + ddl("CREATE PROCEDURE PARTITION ON TABLE " + table + " COLUMN k FROM CLASS " + PACKAGE + "." + n.sp); + procedures.add(n.sp); + ddl("CREATE PROCEDURE FROM CLASS " + PACKAGE + "." + n.mp); + procedures.add(n.mp); + ddl("CREATE COMPOUND PROCEDURE FROM CLASS " + PACKAGE + "." + n.cp); + procedures.add(n.cp); + int calls = 2 + (int) Randomly.getNotCachedInteger(0, 4); + for (int i = 0; i < calls; i++) { + randomCall(table, n, version); + } + switch (Randomly.fromOptions(FollowUp.values())) { + case REPLACE: + long next = version + 1 + Randomly.getNotCachedInteger(0, 1000); + updateClasses(jar(compile(sources(table, n, next, batch))), null, true); + version = next; + REPLACED.incrementAndGet(); + singlePartition(table, n, version, Mode.OK); + break; + case REMOVE_IN_USE: + String why = updateClasses(null, PACKAGE + "." + n.sp, false); + mustBeRefused(why, "removing the class of " + n.sp + ", a procedure in use"); + singlePartition(table, n, version, Mode.OK); + break; + case BAD_CLASS: + Map bad = new LinkedHashMap<>(); + bad.put(n.bad, + "package " + PACKAGE + ";\npublic class " + n.bad + " extends org.voltdb.VoltProcedure {\n" + + " static { if (true) { throw new IllegalStateException(\"JAVAPROC: no\"); } }\n" + + " public long run() { return 1; }\n}\n"); + why = updateClasses(jar(compile(bad)), null, false); + mustBeRefused(why, "loading " + n.bad + ", whose static initializer throws"); + if (!failures && listed(n).contains(n.bad.toUpperCase())) { + throw new AssertionError("@SystemCatalog CLASSES lists " + n.bad + ", whose loading was refused"); + } + singlePartition(table, n, version, Mode.OK); + break; + case BAD_BASE: + String[] wrong = Randomly.fromOptions( + new String[] { "CREATE PROCEDURE", n.nt, + "a non-transactional procedure class (VoltDB's own " + "only)" }, + new String[] { "CREATE PROCEDURE", n.cp, "a compound procedure class" }, + new String[] { "CREATE COMPOUND PROCEDURE", n.sp, "a plain procedure class" }); + why = tryDdl(wrong[0] + " " + n.sp + "X FROM CLASS " + PACKAGE + "." + wrong[1]); + mustBeRefused(why, wrong[0] + " from " + wrong[2]); + break; + case BAD_PARTITION: + why = tryDdl("CREATE PROCEDURE " + n.sp + "X PARTITION ON TABLE " + table + + " COLUMN k PARAMETER 7 FROM " + "CLASS " + PACKAGE + "." + n.sp); + mustBeRefused(why, "a procedure partitioned on a parameter its class does not have"); + break; + default: + break; + } + CHECKS.incrementAndGet(); + } finally { + for (int i = procedures.size() - 1; i >= 0; i--) { + tryDdl("DROP PROCEDURE " + procedures.get(i) + " IF EXISTS"); + } + updateClasses(null, n.all(), false); + } + if (!failures) { + Set left = listed(n); + if (!left.isEmpty()) { + throw new AssertionError("@SystemCatalog CLASSES still lists " + left + " after their procedures were " + + "dropped and @UpdateClasses removed them"); + } + } + } + + private void randomCall(String table, Names n, long version) throws SQLException { + switch ((int) Randomly.getNotCachedInteger(0, 3)) { + case 0: + singlePartition(table, n, version, mode()); + break; + case 1: + multiPartition(table, n, version, mode()); + break; + default: + compound(table, n, Randomly.fromOptions(Compound.values())); + break; + } + } + + // a call's mode: half of them succeed + private static Mode mode() { + return Randomly.getBoolean() ? Mode.OK : Randomly.fromOptions(Mode.values()); + } + + // JPS(k, rows, mode) + private void singlePartition(String table, Names n, long version, Mode mode) throws SQLException { + long k = nextKey++; + int rows = 1 + (int) Randomly.getNotCachedInteger(0, 20); + Outcome r = call(n.sp, k, rows, mode.ordinal()); + SP_CALLS.incrementAndGet(); + verify("JPS " + n.sp + "(" + k + ", " + rows + ", " + mode + ")", table, k, 1, rows, mode, r, version); + } + + // JPM(k0, keys, rows, mode): rows for each of keys keys from k0 + private void multiPartition(String table, Names n, long version, Mode mode) throws SQLException { + long k0 = nextKey; + int keys = 2 + (int) Randomly.getNotCachedInteger(0, 6); + nextKey += keys; + int rows = 1 + (int) Randomly.getNotCachedInteger(0, 10); + Outcome r = call(n.mp, k0, keys, rows, mode.ordinal()); + MP_CALLS.incrementAndGet(); + verify("JPM " + n.mp + "(" + k0 + ", " + keys + ", " + rows + ", " + mode + ")", table, k0, keys, rows, mode, r, + version); + } + + private void verify(String what, String table, long k0, int keys, int rows, Mode mode, Outcome r, long version) + throws SQLException { + long[] found = rows(table, k0, k0 + keys - 1); + long all = (long) keys * rows; + long sum = 0; + for (long k = k0; k < k0 + keys; k++) { + for (int i = 0; i < rows; i++) { + sum += k * 1000 + i; + } + } + if (r.interrupted) { + // a node failure: committed whole or not at all + if (found[0] != 0 && (found[0] != all || found[1] != sum)) { + throw new AssertionError(what + ", interrupted by a node failure (" + r.message + "), committed in " + + "part: " + found[0] + " of its " + all + " rows (sum " + found[1] + " of " + sum + ")"); + } + INTERRUPTED.incrementAndGet(); + throw new IgnoreMeException(); + } + CALLS.incrementAndGet(); + if (mode == Mode.OK) { + if (r.status != ClientResponse.SUCCESS) { + throw new AssertionError(what + " should succeed; it failed: " + r.message); + } + long[] row = r.row; + if (row == null || row[0] != version || row[1] != all || row[2] != sum) { + throw new AssertionError(what + " should return version " + version + ", count " + all + " and sum " + + sum + "; it returned " + (row == null ? "no row" : row[0] + ", " + row[1] + ", " + row[2])); + } + if (found[0] != all || found[1] != sum) { + throw new AssertionError(what + " succeeded, but its keys hold " + found[0] + " rows (sum " + found[1] + + "), not " + all + " (sum " + sum + ")"); + } + return; + } + FAILURES.incrementAndGet(); + if (r.status != mode.status) { + throw new AssertionError(what + " should fail with status " + mode.status + "; it ended with status " + + r.status + ": " + r.message); + } + if (found[0] != 0) { + throw new AssertionError(what + " failed (" + r.message + "), but " + found[0] + " of its rows are there; " + + "its transaction should have rolled back whole"); + } + } + + // JPC(k0, calls, subMode, mode) + private void compound(String table, Names n, Compound mode) throws SQLException { + long k0 = nextKey; + int calls = 1 + (int) Randomly.getNotCachedInteger(0, 4); + nextKey += 10; + // the last JPS call fails, by its own mode, in a third of the calls + Mode last = Randomly.fromOptions(Mode.OK, Mode.OK, + Randomly.fromOptions(Mode.ABORT, Mode.THROW, Mode.CONSTRAINT)); + String what = "JPC " + n.cp + "(" + k0 + ", " + calls + ", " + last + ", " + mode + ")"; + Outcome r = call(n.cp, k0, calls, last.ordinal(), mode.ordinal()); + COMPOUND_CALLS.incrementAndGet(); + boolean made = mode != Compound.NO_STAGES && mode != Compound.NESTED && mode != Compound.TOO_MANY; + // the rows each JPS call leaves: j + 1 rows for key k0 + j, none for a failed call or one never made + for (int j = 0; j < calls; j++) { + long k = k0 + j; + long expected = made && (j < calls - 1 || last == Mode.OK) ? j + 1 : 0; + long found = rows(table, k, k)[0]; + boolean ok = found == expected || r.interrupted && found == 0 || failures && found == 0 && made; + if (!ok) { + throw new AssertionError(what + ": key " + k + " holds " + found + " rows, not " + expected + + " (the rows of the JPS call " + j + (r.interrupted ? "; interrupted: " + r.message : "") + + "; the compound procedure ended with status " + r.status + ": " + r.message + ")"); + } + } + // DROPPED: a call queued in the stage that completes is never sent + long dropped = rows(table, k0 + 9, k0 + 9)[0]; + if (dropped != 0) { + throw new AssertionError(what + ": the JPS call queued in the stage that completed was made: key " + + (k0 + 9) + " holds " + dropped + " rows"); + } + if (r.interrupted) { + INTERRUPTED.incrementAndGet(); + throw new IgnoreMeException(); + } + CALLS.incrementAndGet(); + byte status; + switch (mode) { + case SUM: + status = last == Mode.OK ? ClientResponse.SUCCESS : ClientResponse.COMPOUND_PROC_USER_ABORT; + break; + case TABLE: + case DROPPED: + case APP_STATUS: + status = ClientResponse.SUCCESS; + break; + case THROW_ABORT: + status = ClientResponse.COMPOUND_PROC_USER_ABORT; + break; + default: + status = ClientResponse.UNEXPECTED_FAILURE; + break; + } + if (r.status != status) { + // a JPS call a node failure failed makes SUM abort + if (failures && mode == Compound.SUM && r.status == ClientResponse.COMPOUND_PROC_USER_ABORT + && VoltDBErrors.isNodeFailure(new SQLException(r.message))) { + throw new IgnoreMeException(); + } + throw new AssertionError(what + " should end with status " + status + "; it ended with status " + r.status + + ": " + r.message); + } + if (status != ClientResponse.SUCCESS) { + FAILURES.incrementAndGet(); + } + if (mode == Compound.SUM && status == ClientResponse.SUCCESS) { + long sum = (long) calls * (calls + 1) / 2; + if (r.row == null || r.row[0] != sum) { + throw new AssertionError(what + " should return " + sum + ", the JPS calls' counts; it returned " + + (r.row == null ? "no row" : r.row[0])); + } + } + } + + // a procedure call's outcome: SUCCESS and the first row's BIGINT columns, or the status and message it failed + // with, or interrupted by a node failure + private static final class Outcome { + byte status; + String message; + long[] row; + boolean interrupted; + } + + private Outcome call(String procedure, Object... args) throws SQLException { + StringBuilder sql = new StringBuilder("{call ").append(procedure).append("("); + for (int i = 0; i < args.length; i++) { + sql.append(i == 0 ? "?" : ", ?"); + } + sql.append(")}"); + lastQuery = procedure + java.util.Arrays.toString(args); + Outcome r = new Outcome(); + try (CallableStatement call = connection().prepareCall(sql.toString())) { + for (int i = 0; i < args.length; i++) { + if (args[i] instanceof Long) { + call.setLong(i + 1, (Long) args[i]); + } else { + call.setInt(i + 1, (Integer) args[i]); + } + } + try (ResultSet rs = call.executeQuery()) { + r.status = ClientResponse.SUCCESS; + if (rs.next()) { + int columns = rs.getMetaData().getColumnCount(); + r.row = new long[columns]; + for (int c = 0; c < columns; c++) { + r.row[c] = rs.getLong(c + 1); + } + } + } + } catch (IgnoreMeException e) { + r.interrupted = true; + r.message = "a node failure"; + } catch (SQLException e) { + ClientResponse response = response(e); + if (response == null) { + throw new AssertionError(lastQuery + " failed without a response: " + e.getMessage(), e); + } + r.status = response.getStatus(); + r.message = String.valueOf(response.getStatusString()).split("\n")[0]; + if (failures && (r.status == ClientResponse.CONNECTION_LOST || r.status == ClientResponse.SERVER_UNAVAILABLE + || r.status == ClientResponse.RESPONSE_UNKNOWN || r.status == ClientResponse.CONNECTION_TIMEOUT + || VoltDBErrors.isNodeFailure(e))) { + r.interrupted = true; + } + } + return r; + } + + private static ClientResponse response(Throwable thrown) { + for (Throwable t = thrown; t != null; t = t.getCause()) { + if (t instanceof ProcCallException) { + return ((ProcCallException) t).getClientResponse(); + } + } + return null; + } + + // {count, sum of v} of XJ's rows with k in [from, to] + private long[] rows(String table, long from, long to) throws SQLException { + String sql = "SELECT COUNT(*), COALESCE(SUM(v), 0) FROM " + table + " WHERE k BETWEEN " + from + " AND " + to; + lastQuery = sql; + try (Statement st = connection().createStatement(); ResultSet rs = st.executeQuery(sql)) { + rs.next(); + return new long[] { rs.getLong(1), rs.getLong(2) }; + } + } + + // the classes of this check that @SystemCatalog CLASSES lists, upper case + private Set listed(Names n) throws SQLException { + lastQuery = "@SystemCatalog('CLASSES')"; + Set left = new java.util.TreeSet<>(); + try (CallableStatement call = connection().prepareCall("{call @SystemCatalog(?)}")) { + call.setString(1, "CLASSES"); + try (ResultSet rs = call.executeQuery()) { + while (rs.next()) { + String c = rs.getString("CLASS_NAME"); + String simple = c.substring(c.lastIndexOf('.') + 1).toUpperCase(); + if (c.startsWith(PACKAGE + ".") && n.contains(simple)) { + left.add(simple); + } + } + } + } + return left; + } + + private void mustBeRefused(String why, String what) { + if (why == null) { + throw new AssertionError(what + " should be refused; it succeeded"); + } + REFUSED.incrementAndGet(); + } + + // @UpdateClasses(jar, deletes) on this cluster, the mirror and the XDCR peer; returns null, or why this cluster + // refused it (then the others are not asked); with mustSucceed, a refusal fails the check + private String updateClasses(byte[] jar, String deletes, boolean mustSucceed) throws SQLException { + lastQuery = "@UpdateClasses(" + (jar == null ? "null" : "a jar of " + jar.length + " bytes") + ", " + deletes + + ")"; + String why; + // ENG-30710: a user change by @SetYamlConfiguration that races @UpdateClasses reaches the deployment but not + // the catalog, so a removed user still logs in; while avoiding known bugs, classes change only between + // LOGIN's and CONFIG's checks, under their lock + if (state.getDbmsSpecificOptions().avoidKnownBugs) { + // ENG-30711: and not during a TASK check, as a classes change restarts tasks ON ERROR STOP stopped + synchronized (VoltDBConfigOracle.LOCK) { + VoltDBTaskOracle.CLASSES.writeLock().lock(); + try { + why = updateClasses(connection(), jar, deletes); + } finally { + VoltDBTaskOracle.CLASSES.writeLock().unlock(); + } + } + } else { + why = updateClasses(connection(), jar, deletes); + } + if (why != null) { + if (mustSucceed) { + throw new AssertionError(lastQuery + " should succeed; it failed: " + why); + } + return why; + } + for (VoltDBConnection other : new VoltDBConnection[] { connection().getMirror(), connection().getPeer() }) { + if (other != null) { + try { + updateClasses(other, jar, deletes); + } catch (SQLException | IgnoreMeException e) { + // the CREATE PROCEDURE repeated there fails, which marks the database diverged or split + } + } + } + return null; + } + + private static String updateClasses(VoltDBConnection c, byte[] jar, String deletes) throws SQLException { + try (CallableStatement call = c.prepareCall("{call @UpdateClasses(?, ?)}")) { + if (jar == null) { + call.setNull(1, Types.VARBINARY); + } else { + call.setBytes(1, jar); + } + if (deletes == null) { + call.setNull(2, Types.VARCHAR); + } else { + call.setString(2, deletes); + } + call.executeQuery().close(); + return null; + } catch (SQLException e) { + if (response(e) == null) { + throw e; + } + return String.valueOf(e.getMessage()).split("\n")[0]; + } + } + + private VoltDBConnection connection() { + return (VoltDBConnection) state.getConnection(); + } + + private void create(String table) { + if (CREATED.contains(table)) { + return; + } + ddl("CREATE TABLE " + table + " (k BIGINT NOT NULL, i INTEGER NOT NULL, v BIGINT NOT NULL, r BIGINT, " + + "PRIMARY KEY (k, i)); PARTITION TABLE " + table + " ON COLUMN k"); + CREATED.add(table); + } + + private void ddl(String sql) { + String why = tryDdl(sql); + if (why != null && !why.contains("already exists")) { + throw new AssertionError(sql + " should succeed; it failed: " + why); + } + } + + // DDL; returns null, or why it failed + private String tryDdl(String sql) { + lastQuery = sql; + try (Statement st = connection().createStatement()) { + st.execute(sql); + return null; + } catch (SQLException e) { + return String.valueOf(e.getMessage()).split("\n")[0]; + } + } + + private static final class Names { + final String sp; + final String mp; + final String cp; + final String nt; + final String bad; + + Names(String suffix) { + sp = "JPS_" + suffix; + mp = "JPM_" + suffix; + cp = "JPC_" + suffix; + nt = "JPN_" + suffix; + bad = "JPB_" + suffix; + } + + boolean contains(String upper) { + for (String s : new String[] { sp, mp, cp, nt, bad }) { + if (s.toUpperCase().equals(upper)) { + return true; + } + } + return false; + } + + // @UpdateClasses' deletes: every class of the check + String all() { + return PACKAGE + "." + sp + "," + PACKAGE + "." + mp + "," + PACKAGE + "." + cp + "," + PACKAGE + "." + nt + + "," + PACKAGE + "." + bad; + } + } + + // the four classes' sources, by simple name + private static Map sources(String table, Names n, long version, int batch) { + Map s = new LinkedHashMap<>(); + String header = "package " + PACKAGE + + ";\n\nimport org.voltdb.*;\nimport org.voltdb.client.ClientResponse;\n\n"; + String result = " VoltTable t = new VoltTable(new VoltTable.ColumnInfo(\"V\", VoltType.BIGINT),\n" + + " new VoltTable.ColumnInfo(\"N\", VoltType.BIGINT), new VoltTable.ColumnInfo(\"S\", VoltType.BIGINT),\n" + + " new VoltTable.ColumnInfo(\"U\", VoltType.BIGINT));\n" + + " t.addRow(V, count.getLong(0), count.getLong(1), getUniqueId());\n" + + " return new VoltTable[] { t };\n"; + // modes: 0 OK, 1 ABORT, 2 THROW, 3 EXPECTATION, 4 CONSTRAINT + String modes = " switch (mode) {\n" + + " case 1: throw new VoltAbortException(\"JAVAPROC abort \" + k);\n" + + " case 2: throw new IllegalStateException(\"JAVAPROC failure \" + k);\n" + + " case 3: voltQueueSQL(sel, EXPECT_EMPTY, k, k); voltExecuteSQL(true); break;\n" + + " case 4: voltQueueSQL(ins, k, 0, 0L, 0L); voltExecuteSQL(true); break;\n" + + " default: break;\n }\n"; + s.put(n.sp, header + "public class " + n.sp + " extends VoltProcedure {\n" + " public static final long V = " + + version + "L;\n" + " public final SQLStmt ins = new SQLStmt(\"INSERT INTO " + table + + " (k, i, v, r) VALUES (?, ?, ?, ?)\");\n" + + " public final SQLStmt sel = new SQLStmt(\"SELECT COUNT(*), SUM(v) FROM " + table + + " WHERE k BETWEEN ? AND ?\");\n\n" + " public VoltTable[] run(long k, int n, int mode) {\n" + + " java.util.Random random = getSeededRandomNumberGenerator();\n" + + " for (int i = 0; i < n; i++) {\n" + + " voltQueueSQL(ins, EXPECT_SCALAR_MATCH(1), k, i, k * 1000 + i, random.nextLong());\n" + + " if ((i + 1) % " + batch + " == 0) {\n voltExecuteSQL();\n }\n" + + " }\n" + " voltQueueSQL(sel, EXPECT_ONE_ROW, k, k);\n" + + " VoltTable[] results = voltExecuteSQL(mode == 0);\n" + + " VoltTable count = results[results.length - 1];\n" + " count.advanceRow();\n" + modes + + " setAppStatusCode((byte) (k % 100));\n" + " setAppStatusString(\"V\" + V);\n" + result + + " }\n}\n"); + s.put(n.mp, header + "public class " + n.mp + " extends VoltProcedure {\n" + " public static final long V = " + + version + "L;\n" + " public final SQLStmt ins = new SQLStmt(\"INSERT INTO " + table + + " (k, i, v, r) VALUES (?, ?, ?, ?)\");\n" + + " public final SQLStmt sel = new SQLStmt(\"SELECT COUNT(*), SUM(v) FROM " + table + + " WHERE k BETWEEN ? AND ?\");\n\n" + + " public VoltTable[] run(long k, int keys, int n, int mode) {\n" + + " for (int j = 0; j < keys; j++) {\n" + " for (int i = 0; i < n; i++) {\n" + + " voltQueueSQL(ins, EXPECT_SCALAR_MATCH(1), k + j, i, (k + j) * 1000 + i, (long) (j * n + i));\n" + + " }\n" + " if ((j + 1) % " + batch + + " == 0) {\n voltExecuteSQL();\n }\n" + " }\n" + + " voltQueueSQL(sel, EXPECT_ONE_ROW, k, k + keys - 1);\n" + + " VoltTable[] results = voltExecuteSQL(mode == 0);\n" + + " VoltTable count = results[results.length - 1];\n" + " count.advanceRow();\n" + modes + + result + " }\n}\n"); + // modes: Compound's order + s.put(n.cp, header + "public class " + n.cp + " extends VoltCompoundProcedure {\n" + + " public static final long V = " + version + "L;\n" + + " private long k;\n private int calls;\n private int last;\n private int mode;\n\n" + + " public long run(long k, int calls, int last, int mode) {\n" + + " this.k = k;\n this.calls = calls;\n this.last = last;\n this.mode = mode;\n" + + " if (mode != 4) {\n" + " newStageList(this::first).then(this::second).build();\n" + + " }\n" + " return 0L;\n" + " }\n\n" + + " private void first(ClientResponse[] none) {\n" + + " if (mode == 6) {\n queueProcedureCall(\"" + n.cp + "\", k, 1, 0, 0);\n }\n" + + " int c = mode == 7 ? 1000 : calls;\n" + " for (int j = 0; j < c; j++) {\n" + + " queueProcedureCall(\"" + n.sp + "\", k + j, j + 1, j == calls - 1 ? last : 0);\n" + + " }\n" + " }\n\n" + " private void second(ClientResponse[] responses) {\n" + + " long sum = 0;\n" + + " VoltTable t = new VoltTable(new VoltTable.ColumnInfo(\"N\", VoltType.BIGINT),\n" + + " new VoltTable.ColumnInfo(\"STATUS\", VoltType.TINYINT));\n" + + " for (ClientResponse r : responses) {\n" + + " if (r.getStatus() != ClientResponse.SUCCESS) {\n" + " if (mode == 0) {\n" + + " abortProcedure(\"JAVAPROC call failed: \" + r.getStatusString());\n" + + " return;\n" + " }\n" + + " t.addRow(-1L, r.getStatus());\n" + " continue;\n" + " }\n" + + " VoltTable c = r.getResults()[0];\n" + " c.advanceRow();\n" + + " sum += c.getLong(1);\n" + " t.addRow(c.getLong(1), r.getStatus());\n" + + " }\n" + " switch (mode) {\n" + " case 0: completeProcedure(sum); return;\n" + + " case 1: completeProcedure(t); return;\n" + + " case 2: throw new CompoundProcAbortException(\"JAVAPROC abort \" + k);\n" + + " case 3: throw new IllegalStateException(\"JAVAPROC failure \" + k);\n" + + " case 5: return;\n" + " case 8:\n" + " queueProcedureCall(\"" + n.sp + + "\", k + 9, 1, 0);\n" + " completeProcedure(sum);\n" + " return;\n" + + " case 9:\n" + " setAppStatusCode((byte) 7);\n" + + " setAppStatusString(\"V\" + V);\n" + + " completeProcedure(new VoltTable[] { t });\n" + " return;\n" + + " default: completeProcedure(sum);\n" + " }\n" + " }\n}\n"); + s.put(n.nt, + header + "public class " + n.nt + " extends VoltNonTransactionalProcedure {\n" + + " public static final long V = " + version + "L;\n\n" + + " public java.util.concurrent.CompletableFuture run(long k, int n) {\n" + + " return callProcedure(\"" + n.sp + "\", k, n, 0);\n" + " }\n}\n"); + return s; + } + + // compiles the sources against --procedure-classpath; returns each class's bytes by its file's path in a jar + private Map compile(Map sources) { + Map out = new LinkedHashMap<>(); + JavaCompiler compiler = ToolProvider.getSystemJavaCompiler(); + DiagnosticCollector diagnostics = new DiagnosticCollector<>(); + List units = new ArrayList<>(); + for (Map.Entry e : sources.entrySet()) { + units.add(new SimpleJavaFileObject(URI.create("string:///" + PACKAGE + "/" + e.getKey() + ".java"), + JavaFileObject.Kind.SOURCE) { + @Override + public CharSequence getCharContent(boolean ignoreEncodingErrors) { + return e.getValue(); + } + }); + } + synchronized (COMPILE) { + StandardJavaFileManager standard = compiler.getStandardFileManager(diagnostics, null, + StandardCharsets.UTF_8); + JavaFileManager files = new ForwardingJavaFileManager(standard) { + @Override + public JavaFileObject getJavaFileForOutput(Location location, String className, + JavaFileObject.Kind kind, FileObject sibling) { + return new SimpleJavaFileObject(URI.create("bytes:///" + className.replace('.', '/') + ".class"), + kind) { + @Override + public OutputStream openOutputStream() { + return new ByteArrayOutputStream() { + @Override + public void close() throws IOException { + super.close(); + out.put(className.replace('.', '/') + ".class", toByteArray()); + } + }; + } + }; + } + }; + List options = List.of("-classpath", state.getDbmsSpecificOptions().procedureClasspath.trim(), + "--release", "17", "-proc:none", "-nowarn", "-g"); + Boolean ok = compiler.getTask(null, files, diagnostics, options, null, units).call(); + if (!Boolean.TRUE.equals(ok)) { + throw new AssertionError( + "JAVAPROC's procedure classes do not compile: " + diagnostics.getDiagnostics()); + } + } + return out; + } + + private static byte[] jar(Map classes) throws IOException { + ByteArrayOutputStream bytes = new ByteArrayOutputStream(); + try (JarOutputStream jar = new JarOutputStream(bytes)) { + for (Map.Entry e : classes.entrySet()) { + jar.putNextEntry(new JarEntry(e.getKey())); + jar.write(e.getValue()); + jar.closeEntry(); + } + } + return bytes.toByteArray(); + } + + @Override + public Reproducer getLastReproducer() { + return null; + } + + @Override + public String getLastQueryString() { + return lastQuery; + } + +} diff --git a/src/sqlancer/voltdb/oracle/VoltDBTaskOracle.java b/src/sqlancer/voltdb/oracle/VoltDBTaskOracle.java index e7d3e3377..0a80f6e16 100644 --- a/src/sqlancer/voltdb/oracle/VoltDBTaskOracle.java +++ b/src/sqlancer/voltdb/oracle/VoltDBTaskOracle.java @@ -7,6 +7,8 @@ import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.atomic.AtomicLong; +import java.util.concurrent.locks.Lock; +import java.util.concurrent.locks.ReentrantReadWriteLock; import sqlancer.IgnoreMeException; import sqlancer.Randomly; @@ -40,6 +42,9 @@ public class VoltDBTaskOracle implements TestOracle { private static final AtomicLong CHECKS = new AtomicLong(); private static final AtomicLong STOPS = new AtomicLong(); private static final Set CREATED = ConcurrentHashMap.newKeySet(); + // ENG-30711: @UpdateClasses restarts a task that ON ERROR STOP stopped, which runs its procedure again; while + // avoiding known bugs, TASK's checks hold this shared and JAVAPROC's @UpdateClasses calls exclusive + static final ReentrantReadWriteLock CLASSES = new ReentrantReadWriteLock(true); static { Runtime.getRuntime().addShutdownHook(new Thread( @@ -55,6 +60,20 @@ public VoltDBTaskOracle(VoltDBGlobalState state) { @Override public void check() throws Exception { + Lock classes = state.getDbmsSpecificOptions().avoidKnownBugs ? CLASSES.readLock() : null; + if (classes != null) { + classes.lock(); + } + try { + checkWithoutClassChanges(); + } finally { + if (classes != null) { + classes.unlock(); + } + } + } + + private void checkWithoutClassChanges() throws Exception { String db = state.getDatabaseName().toUpperCase(); String table = "XK_" + db; create(table, db); diff --git a/voltdb/repros/ENG-30710.sh b/voltdb/repros/ENG-30710.sh new file mode 100755 index 000000000..4ab828992 --- /dev/null +++ b/voltdb/repros/ENG-30710.sh @@ -0,0 +1,35 @@ +#!/bin/bash +: <<'HEADER' +-- ticket: ENG-30710 +-- summary: A user removed by @SetYamlConfiguration can still log in when @UpdateClasses runs at the same time: the deployment drops the user, the catalog keeps it until the next catalog change +HEADER +# The runner's env: VOLTDB_HOME, PORT_BASE, WORKDIR (and VOLTDB_LICENSE, if any). One node with security on (the +# administrator sqlancer). users/RemovedUserRepro.java: one client thread loads a one-class jar with @UpdateClasses and +# removes it, again and again; the main thread adds a user with @SetYamlConfiguration, removes it, checks that +# @GetYamlConfiguration no longer lists it, and logs in as it. Exit 0 if a removed user logs in (the bug), 1 if none +# does in 300 users. CONTROL=1 runs without @UpdateClasses (then no removed user logs in). +set -u +here=$(cd "$(dirname "$0")" && pwd) +V=$VOLTDB_HOME +C=$WORKDIR/removeduser +B=$PORT_BASE +rm -rf "$C"; mkdir -p "$C/src/repro" "$C/classes" "$C/jar" +cat > "$C/d.xml" < + + +X +"$V/bin/voltdb" init --force ${VOLTDB_LICENSE:+--license "$VOLTDB_LICENSE"} -D "$C/n0" -C "$C/d.xml" > "$C/init.log" 2>&1 +(nohup "$V/bin/voltdb" start -D "$C/n0" -H localhost:$((B + 2)) --client=$B --admin=$((B + 1)) --internal=$((B + 2)) \ + --zookeeper=$((B + 3)) --replication=$((B + 4)) --metrics=$((B + 5)) > "$C/start.log" 2>&1 & echo $! > "$C/n0.pid") +cleanup() { "$V/bin/voltadmin" shutdown --force -H localhost:$((B + 1)) -u sqlancer -p sqlancer > /dev/null 2>&1; sleep 5; kill -9 "$(cat "$C/n0.pid")" 2>/dev/null; } +trap cleanup EXIT +for _ in $(seq 1 120); do grep -q "Server completed initialization" "$C/start.log" 2>/dev/null && break; sleep 1; done +grep -q "Server completed initialization" "$C/start.log" || { echo "the node did not start"; tail -20 "$C/start.log"; exit 2; } +# the jar @UpdateClasses loads: one class, repro.Helper +echo 'package repro; public class Helper { public static long f() { return 1; } }' > "$C/src/repro/Helper.java" +javac -d "$C/jar" "$C/src/repro/Helper.java" && jar cf "$C/repro.jar" -C "$C/jar" repro || exit 2 +cp="$V/voltdb/*:$V/lib/*" +javac -cp "$cp" -d "$C/classes" "$here/users/RemovedUserRepro.java" || exit 2 +java -cp "$cp:$C/classes" RemovedUserRepro localhost:$B "$C/repro.jar" 300 ${CONTROL:+control} 2>&1 | grep -v SLF4J +exit "${PIPESTATUS[0]}" diff --git a/voltdb/repros/ENG-30711.sh b/voltdb/repros/ENG-30711.sh new file mode 100755 index 000000000..c02fa007f --- /dev/null +++ b/voltdb/repros/ENG-30711.sh @@ -0,0 +1,47 @@ +#!/bin/bash +: <<'HEADER' +-- ticket: ENG-30711 +-- summary: @UpdateClasses restarts a task that ON ERROR STOP stopped: it runs its procedure again +HEADER +# The runner's env: VOLTDB_HOME, PORT_BASE, WORKDIR (and VOLTDB_LICENSE, if any). One node. A task runs a procedure +# whose second run fails on a primary key, ON ERROR STOP, every 200 ms; once @Statistics TASK shows it ERROR, +# @UpdateClasses loads a one-class jar. Exit 0 if the task then runs its procedure again (a second failure in the log; +# the bug), 1 if it stays stopped. +# CONTROL=1 makes an ordinary DDL change (CREATE TABLE) instead of @UpdateClasses. +set -u +V=$VOLTDB_HOME +C=$WORKDIR/taskrevive +B=$PORT_BASE +rm -rf "$C"; mkdir -p "$C/src/repro" "$C/jar" +cat > "$C/d.xml" < + +X +"$V/bin/voltdb" init --force ${VOLTDB_LICENSE:+--license "$VOLTDB_LICENSE"} -D "$C/n0" -C "$C/d.xml" > "$C/init.log" 2>&1 +(nohup "$V/bin/voltdb" start -D "$C/n0" -H localhost:$((B + 2)) --client=$B --admin=$((B + 1)) --internal=$((B + 2)) \ + --zookeeper=$((B + 3)) --replication=$((B + 4)) --metrics=$((B + 5)) > "$C/start.log" 2>&1 & echo $! > "$C/n0.pid") +cleanup() { "$V/bin/voltadmin" shutdown --force -H localhost:$((B + 1)) > /dev/null 2>&1; sleep 5; kill -9 "$(cat "$C/n0.pid")" 2>/dev/null; } +trap cleanup EXIT +for _ in $(seq 1 120); do grep -q "Server completed initialization" "$C/start.log" 2>/dev/null && break; sleep 1; done +SQL="$V/bin/sqlcmd --port=$B" +state() { echo "exec @Statistics TASK 0;" | $SQL 2>/dev/null | grep -E "\bXT\b" | grep -oE "RUNNING|ERROR|DISABLED|PAUSED" | head -1; } +echo "CREATE TABLE XS (k BIGINT NOT NULL, t VARCHAR(20), PRIMARY KEY (k)); +CREATE PROCEDURE XU AS INSERT INTO XS VALUES (?, ?); +CREATE TASK XT ON SCHEDULE EVERY 200 MILLISECONDS PROCEDURE XU WITH (1, 'XT') ON ERROR STOP;" | $SQL > /dev/null 2>&1 +for _ in $(seq 1 50); do [ "$(state)" = ERROR ] && break; sleep 0.2; done +echo "before: state $(state), rows $(echo 'SELECT COUNT(*) FROM XS;' | $SQL 2>/dev/null | grep -E '^ *[0-9]+ *$' | tr -d ' ')" +if [ -n "${CONTROL:-}" ]; then + echo "CREATE TABLE OTHER (k BIGINT);" | $SQL > /dev/null 2>&1; echo "a DDL change (CREATE TABLE)" +else + echo 'package repro; public class Helper { public static long f() { return 1; } }' > "$C/src/repro/Helper.java" + javac -d "$C/jar" "$C/src/repro/Helper.java" && jar cf "$C/repro.jar" -C "$C/jar" repro || exit 2 + echo "load classes $C/repro.jar;" | $SQL 2>&1 | grep -v "^Warning\|^ /\|^ But\|^$" | tail -1 +fi +sleep 2 +after=$(state) +echo "after: state $after, rows $(echo 'SELECT COUNT(*) FROM XS;' | $SQL 2>/dev/null | grep -E '^ *[0-9]+ *$' | tr -d ' ')" +grep -h "XT" "$C/n0/voltdbroot/log/volt.log" | grep -i "task\|start\|stop" | cut -c1-200 | tail -5 +runs=$(grep -c "XT: Procedure XU with parameters" "$C/n0/voltdbroot/log/volt.log") +[ "$runs" -gt 1 ] && { echo "the stopped task ran its procedure again: $runs failed runs (the bug)"; exit 0; } +echo "the stopped task stayed stopped: $runs failed run" +exit 1 diff --git a/voltdb/repros/users/RemovedUserRepro.java b/voltdb/repros/users/RemovedUserRepro.java new file mode 100644 index 000000000..e5cf93572 --- /dev/null +++ b/voltdb/repros/users/RemovedUserRepro.java @@ -0,0 +1,103 @@ +import java.nio.file.Files; +import java.nio.file.Paths; +import java.util.concurrent.atomic.AtomicBoolean; + +import org.voltdb.client.Client; +import org.voltdb.client.ClientConfig; +import org.voltdb.client.ClientFactory; +import org.voltdb.client.ClientResponse; +import org.voltdb.client.ProcCallException; + +/** + * RemovedUserRepro SERVER JAR ROUNDS [control]: as the administrator sqlancer/sqlancer, one thread loads the classes of JAR with + * @UpdateClasses and removes them, again and again; the main thread adds a user with @SetYamlConfiguration, removes it, + * checks that @GetYamlConfiguration no longer lists it, and logs in as it, which must be refused. Prints BUG and exits + * 0 at the first removed user that logs in; exits 1 after ROUNDS users without one. With control, no @UpdateClasses. + */ +public class RemovedUserRepro { + public static void main(String[] args) throws Exception { + String server = args[0]; + byte[] jar = Files.readAllBytes(Paths.get(args[1])); + int rounds = Integer.parseInt(args[2]); + Client admin = ClientFactory.createClient(new ClientConfig("sqlancer", "sqlancer")); + admin.createConnection(server); + AtomicBoolean stop = new AtomicBoolean(); + Thread classes = new Thread(() -> { + Client c = ClientFactory.createClient(new ClientConfig("sqlancer", "sqlancer")); + try { + c.createConnection(server); + while (!stop.get()) { + try { + c.callProcedure("@UpdateClasses", jar, null); + c.callProcedure("@UpdateClasses", null, "repro.*"); + } catch (ProcCallException e) { + // another catalog update in progress: try again + } + } + c.close(); + } catch (Exception e) { + e.printStackTrace(); + } + }); + boolean control = args.length > 3 && args[3].equals("control"); + if (!control) { + classes.start(); + } + int updates = 0; + try { + for (int i = 1; i <= rounds; i++) { + String user = "removed" + i; + String password = "pw" + i; + yaml(admin, ".users[" + user + "].password=" + password + "\n.users[" + user + "].roles=user"); + yaml(admin, ".users[" + user + "]=null"); + String users = admin.callProcedure("@GetYamlConfiguration", "deployment.users").getResults()[0] + .fetchRow(0).getString("DATA"); + if (users.contains(user)) { + System.out.println("round " + i + ": @GetYamlConfiguration still lists " + user); + continue; + } + Client c = ClientFactory.createClient(new ClientConfig(user, password)); + try { + c.createConnection(server); + ClientResponse r = c.callProcedure("@Ping"); + System.out.println("BUG: round " + i + ": " + user + ", removed and no longer listed by " + + "@GetYamlConfiguration, logged in and ran @Ping (status " + r.getStatus() + ")"); + stop.set(true); + if (!control) { + classes.join(); + } + System.exit(0); + } catch (Exception e) { + if (!String.valueOf(e.getMessage()).contains("Authentication rejected")) { + System.out.println("round " + i + ": login failed otherwise: " + e.getMessage()); + } + } finally { + c.close(); + } + updates++; + } + } finally { + stop.set(true); + if (!control) { + classes.join(); + } + } + System.out.println("no removed user logged in, " + updates + " users"); + System.exit(1); + } + + // @SetYamlConfiguration('', assignments), retried while another catalog update is in progress + private static void yaml(Client admin, String assignments) throws Exception { + for (int attempt = 0;; attempt++) { + try { + admin.callProcedure("@SetYamlConfiguration", "", assignments); + return; + } catch (ProcCallException e) { + if (attempt > 200 || !String.valueOf(e.getMessage()).contains("in progress")) { + throw e; + } + Thread.sleep(20); + } + } + } +} diff --git a/voltdb/run-coverage.sh b/voltdb/run-coverage.sh index 3f8f178ac..1727e8bec 100755 --- a/voltdb/run-coverage.sh +++ b/voltdb/run-coverage.sh @@ -122,7 +122,7 @@ log() { } all_oracles=NOREC,TLP_WHERE,TLP_DISTINCT,TLP_HAVING,TLP_AGGREGATE,PQS,PARAMS,VIEWS,LIMIT,SUBQUERY,WINDOW,SETOPS -all_oracles=$all_oracles,DERIVED,PROCEDURE,SCHEMA,GEO,DURABLE,XDCR,PLANS,PERMS,STREAMS,TTL,LOAD,SWAP,CONFIG,SNAPSHOT,XCONFLICT,TASK,IMPORT,STATS,LOGIN +all_oracles=$all_oracles,DERIVED,PROCEDURE,SCHEMA,GEO,DURABLE,XDCR,PLANS,PERMS,STREAMS,TTL,LOAD,SWAP,CONFIG,SNAPSHOT,XCONFLICT,TASK,IMPORT,STATS,LOGIN,JAVAPROC license_args=() [ -n "$license" ] && license_args=(--license "$license") diff --git a/voltdb/run-sqlancer.sh b/voltdb/run-sqlancer.sh index 3a49ff87d..55f60b6c9 100755 --- a/voltdb/run-sqlancer.sh +++ b/voltdb/run-sqlancer.sh @@ -357,6 +357,10 @@ user_snapshot_retry=${SQLANCER_USER_SNAPSHOT_RETRY-1} provider_args+=(--snapshot-path "$cluster") # XCONFLICT reads XDCR's conflict log under the nodes' voltdbroots here provider_args+=(--cluster-dir "$cluster") +# JAVAPROC (milestone 50) compiles its procedure classes against the kit's procedure API, server and client jars +procedure_classpath=$(ls "$voltdb_home"/lib/volt-procedure-api-*.jar "$voltdb_home"/voltdb/voltdb-*.jar \ + "$voltdb_home"/voltdb/voltdbclient-*.jar 2>/dev/null | paste -sd: -) +[ -n "$procedure_classpath" ] && provider_args+=(--procedure-classpath "$procedure_classpath") log() { echo "[$(date '+%H:%M:%S')] $*" | tee -a "$results/run.log"; } @@ -1534,6 +1538,7 @@ result=PASS grep -m1 "^IMPORT checks:" "$results/sqlancer/out.log" 2>/dev/null grep -m1 "^STATS calls checked:" "$results/sqlancer/out.log" 2>/dev/null grep -m1 "^LOGIN checks:" "$results/sqlancer/out.log" 2>/dev/null + grep -m1 "^JAVAPROC checks:" "$results/sqlancer/out.log" 2>/dev/null $export && echo "export: $exported rows exported (${http_rows:-0} through HTTP $http_mode by $http_method$([ "${bad_signatures:-0}" -eq 0 ] || echo ", $bad_signatures BAD SIGNATURES"), ${jdbc_rows:-0} through JDBC, $duplicates twice), $inserted inserted$($export_failed && echo ", a MISMATCH (export/)"); gap fills: ${gap_fills:-0} (HTTP held across ${gap_holds:-0} kills)" echo "transient results skipped (ENG-30602): $(grep -c "^ENG-30602 transient:" "$results/sqlancer/out.log" 2>/dev/null || true)" [ "$kill_interval" -gt 0 ] && echo "node failures: $kills kills, ${stops:-0} graceful stops, $rejoins rejoins$($chaos_failed && echo ", a rejoin FAILED (chaos.log)")"