File: InterruptResilienceTest.java

package info (click to toggle)
derby 10.14.2.0-3
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 79,056 kB
  • sloc: java: 691,961; sql: 42,686; xml: 20,512; sh: 3,373; sed: 96; makefile: 60
file content (712 lines) | stat: -rw-r--r-- 24,046 bytes parent folder | download | duplicates (4)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
/*
  Class org.apache.derbyTesting.functionTests.tests.store.InterruptResilienceTest

  Licensed to the Apache Software Foundation (ASF) under one or more
  contributor license agreements.  See the NOTICE file distributed with
  this work for additional information regarding copyright ownership.
  The ASF licenses this file to you under the Apache License, Version 2.0
  (the "License"); you may not use this file except in compliance with
  the License.  You may obtain a copy of the License at

  http://www.apache.org/licenses/LICENSE-2.0

  Unless required by applicable law or agreed to in writing, software
  distributed under the License is distributed on an "AS IS" BASIS,
  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  See the License for the specific language governing permissions and
  limitations under the License.

*/
package org.apache.derbyTesting.functionTests.tests.store;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.Properties;
import java.util.Random;
import junit.framework.Test;
import org.apache.derbyTesting.junit.BaseJDBCTestCase;
import org.apache.derbyTesting.junit.BaseTestSuite;
import org.apache.derbyTesting.junit.JDBC;
import org.apache.derbyTesting.junit.SystemPropertyTestSetup;
import org.apache.derbyTesting.junit.TestConfiguration;

/**
 * This test started out as a test reproduce and verify fix for DERBY-151.
 * Later evolved into test for DERBY-4741.
 * <p/>
 * The use of stored procedures was done to make the tests meaningful in client
 * server mode as well, but be removed/simplified as long as we only make
 * claims about the resilience of embedded Derby.
 */

public class InterruptResilienceTest extends BaseJDBCTestCase
{

    public InterruptResilienceTest(String name)
    {
        super(name);
    }

    // Share the main thread's configuration with the server side threads.
    private static volatile TestConfiguration thisConf;

    protected static Test makeSuite(String name)
    {
        BaseTestSuite suite = new BaseTestSuite(name);

        Test est = TestConfiguration.embeddedSuite(
            InterruptResilienceTest.class);
        Test cst = TestConfiguration.clientServerSuite(
            InterruptResilienceTest.class);

        est = TestConfiguration.singleUseDatabaseDecorator(est);
        cst = TestConfiguration.singleUseDatabaseDecorator(cst);
        // Cut down on running time:
        Properties p = new Properties();
        p.put("derby.system.durability", "test");
        p.put("derby.infolog.append", "true");
        // we'll force interrupts and thus serious errors, which with
        // ibm jvms would result in javacore files, which aren't of 
        // interest if the test passes. Setting the stream error level 
        // so we don't get those javacores.
        p.put("derby.stream.error.extendedDiagSeverityLevel", "50000");

        suite.addTest(
                new SystemPropertyTestSetup(est, p, true));

        suite.addTest(
                new SystemPropertyTestSetup(cst, p, true));
        return suite;
    }

    public static Test suite()
    {
        String testName = "InterruptResilienceTest";

        if (isIBMJVM()) {
            if (getSystemProperty("java.version").startsWith("1.4.2"))
            {
                println("InterruptResilienceTest skipped for this VM, cf. DERBY-5074/5109");
                return new BaseTestSuite(testName);
            }
        }

        if (!JDBC.vmSupportsJDBC3()) {
            println("Test skipped for this VM, " +
                    "DriverManager is not supported with JSR169");
            return new BaseTestSuite(testName);
        }

        if (hasInterruptibleIO()) {
            println("Test skipped due to interruptible IO.");
            println("This is default on Solaris/Sun Java <= 1.6, use " +
                    "-XX:-UseVMInterruptibleIO if available.");
            return new BaseTestSuite(testName);
        }

        return makeSuite(testName);
    }

    protected void setUp()
            throws java.lang.Exception {
        try {
            Class<?> clazz = Class.forName("org.apache.derby.jdbc.EmbeddedDriver");
            clazz.getConstructor().newInstance();
        } catch (Exception e) {
        }
        super.setUp();
        Statement stmt = createStatement();
        stmt.executeUpdate("create table t1(x int primary key)");
        stmt.executeUpdate("create table mtTab(i bigint, " +
                           "inserter varchar(40), " +
                           "primary key(i, inserter))");
        stmt.close();

        thisConf = TestConfiguration.getCurrent();
        threadNo = 0;    // counter for multiple threads tests

        // DERBY-6122
        //
        // Set a big enough timeout such that no fixture in this test encounters
        // a timeout.  The point is to force the Derby tests to exercise a new 
        // block of code added to Driver20 to handle interrupts raised during 
        // login attempts. As InterruptResilienceTest runs, interrupts are 
        // supposed to happen--although it's hard to force the exact timing of 
        // the interrupts. The login timeout added to this test is only 
        // supposed to test the following case:
        //
        // 1) An interrupt occurs within the time limit set 
        //    by DriverManager.setLoginTimeout()
        //
        // 2) The new code added to Driver20 fields the interrupt and continues
        //    attempting to log in.
        //
        DriverManager.setLoginTimeout( 1000 );
        
        allDone = false; // flag for threads to terminate
    }

    /**
     * Clean up the connection maintained by this test.
     */
    protected void tearDown()
            throws java.lang.Exception {

        DriverManager.setLoginTimeout( 0 );

        // Forget about uncommitted changes
        rollback();

        // Drop the tables created in setUp() if they still exist
        dropTable("t1");
        dropTable("mtTab");
        commit();

        super.tearDown();
    }

    // We do the actual test inside a stored procedure so we can test this for
    // client/server as well, otherwise we would just interrupt the client
    // thread. This SP correposnds to #testRAFWriteInterrupted.
    public static void tstRAFwriteInterrupted() throws SQLException {
        Connection c = DriverManager.getConnection("jdbc:default:connection");
        c.setAutoCommit(false);
        PreparedStatement insert = null;
        long seen = 0;
        long lost = 0;
        try {
            insert = c.prepareStatement("insert into t1 values (?)");

            // About 75000 iterations is needed to see any concurrency
            // wait on RawDaemonThread during recovery, cf.
            // running with debug flag "RAF4" for RAFContainer4.
            for (int i = 0; i < 100000; i++) {
                if (i % 1000 == 0) {
                    c.commit();
                }

                // Make sure to interrupt after commit, since log writing isn't
                // safe for interrupts (on Solaris only) yet.
                Thread.currentThread().interrupt();

                insert.setLong(1, i);
                insert.executeUpdate();

                assertTrue("interrupt flag lost", Thread.interrupted());
            }
        } finally {
            // always clear flag
            Thread.interrupted();

            if (insert != null) {
                try {
                    insert.close(); // already closed by error
                } catch (SQLException e) {
                }
            }

            c.close();
        }
    }

    public void testRAFWriteInterrupted () throws SQLException {
        Statement s = createStatement();
        s.executeUpdate(
            "create procedure tstRAFWriteInterrupted () modifies sql data " +
            "external name 'org.apache.derbyTesting.functionTests" +
            ".tests.store.InterruptResilienceTest.tstRAFwriteInterrupted' " +
            "language java parameter style java");

        s.executeUpdate("call tstRAFWriteInterrupted()");
    }


    // We do the actual test inside a stored procedure so we can test this for
    // client/server as well, otherwise we would just interrupt the client
    // thread. This SP correponds to #testRAFReadWriteMultipleThreads.
    public static void tstRAFReadWriteMultipleThreads() throws Exception {

        //--------------------
        // part 1
        //--------------------

        Connection c = DriverManager.getConnection("jdbc:default:connection");

        ArrayList<WorkerThread> workers = new ArrayList<WorkerThread>();

        ArrayList<InterruptorThread> interruptors =
                new ArrayList<InterruptorThread>();

        for (int i = 0; i < NO_OF_THREADS; i++) {
            WorkerThread w = new WorkerThread(
                thisConf.openDefaultConnection(),
                false /* read */,
                NO_OF_MT_OPS);

            workers.add(w);

            w.start();
            try {
                Thread.sleep(1000);
            } catch (Exception e) {
            }

            InterruptorThread it = new InterruptorThread(w, 500);
            interruptors.add(it);
            it.start();
        }

        for (int i = 0; i < workers.size(); i++) {
            WorkerThread w = workers.get(i);
            w.join();

            if (w.e != null) {
                fail("WorkerThread " + i, w.e);
            }
        }

        allDone = true;

        for (int i = 0; i < interruptors.size(); i++) {
            interruptors.get(i).join();
        }

        try {
            Thread.sleep(1000);
        } catch (Exception e) {
        }

        Statement s = c.createStatement();
        ResultSet rs = s.executeQuery("select count(*) from mtTab");

        JDBC.assertSingleValueResultSet(
            rs, Long.toString(NO_OF_THREADS * NO_OF_MT_OPS));

        //--------------------
        // part 2
        //--------------------

        // Reset thread state variables
        allDone = false;
        threadNo = 0;

        workers.clear();
        interruptors.clear();

        for (int i = 0; i < NO_OF_THREADS; i++) {
            WorkerThread w = new WorkerThread(
                // This will be an embedded connection always since for the
                // server thread current cf will be JUNIT_CONFIG.
                thisConf.openDefaultConnection(),
                true,
                NO_OF_MT_OPS);

            workers.add(w);

            try {
                Thread.sleep(1000);
            } catch (Exception e) {
            }

            InterruptorThread it = new InterruptorThread(w, 500);
            interruptors.add(it);
            it.start();
        }

        // Wait till here to start works, so interruptors don't get too late to
        // the game
        for (int i = 0; i < workers.size(); i++) {
            workers.get(i).start();
        }

        for (int i = 0; i < workers.size(); i++) {
            WorkerThread w = workers.get(i);
            w.join();

            if (w.e != null) {
                fail("WorkerThread " + i, w.e);
            }
        }

        allDone = true;

        for (int i = 0; i < interruptors.size(); i++) {
            interruptors.get(i).join();
        }

        c.close();
    }


    static class InterruptorThread extends Thread {
        private WorkerThread myVictim;
        private int millisBetweenShots;

        public InterruptorThread(WorkerThread v, int m){
            super();
            myVictim = v;
            millisBetweenShots = m;
        }

        public void run() {
            setName("InterruptorThread. Thread #" + getThreadNo());
            println("Running " + getName() +
                    " with victim " + myVictim.getName());

            int shots = 0;

            while (!allDone) {
                try {
                    Thread.sleep(millisBetweenShots);
                    myVictim.interrupt();
                    shots++;
                } catch (Exception e) {
                }
            }

            println(getName() + " shot " + shots +
                    " interrupts at " + myVictim.getName());
        }
    }


    static class WorkerThread extends Thread {
        private final boolean readertest;
        private final long noOps;
        public Throwable e; // if any seen
        private Connection c;

        public WorkerThread(Connection c, boolean readertest, long noOps) {
            super();
            this.readertest = readertest;
            this.noOps = noOps;
            this.c = c;
        }

        public void run() {
            int threadNo = getThreadNo();
            int interruptsSeen = 0;

            setName("WorkerThread. Thread#" + threadNo);
            println("Running " + getName());

            try {
                c.setAutoCommit(false);

                String pStmtText =
                    readertest ?
                    "select * from mtTab where i=?" :
                    "insert into mtTab values (?,?)";
                PreparedStatement s = c.prepareStatement(pStmtText);

                Random rnd = new Random();

                int retries = 0;

                for (long ops = 0; ops < noOps + retries; ops++) {

                    if (readertest) {
                        // Arbitrarily select one of the rows int the tables to
                        // read
                        long candidate = randAbs(rnd.nextLong()) % noOps;
                        s.setLong(1, candidate);

                        // Since when we query, we might see 08000 if the
                        // interrupt flag is set when the rs.getNextRow calls
                        // checkCancellationFlag, we must be prepared to
                        // reestablish connection.

                        try {
                            ResultSet rs = s.executeQuery();
                            rs.next();
                            if (interrupted()) {
                                interruptsSeen++;
                            }

                            assertEquals("wrong row content",
                                         candidate, rs.getLong(1));

                            rs.close();
                        } catch (SQLException e) {
                            if ("08000".equals(e.getSQLState())) {
                                c = thisConf.openDefaultConnection();
                                s = c.prepareStatement(pStmtText);
                                assertTrue(interrupted());
                                interruptsSeen++;
                                retries++;
                                continue;
                            } else {
                                fail("expected 08000", e);
                            }
                        }

                        c.commit();

                        if (interrupted()) {
                            interruptsSeen++;
                        }
                    } else {
                        s.setLong(1, ops);
                        s.setString(2, getName());

                        try {
                            s.executeUpdate();
                        } catch (SQLException e) {
                            // Occasionally we could see a lock wait being
                            // interrupted: reconnect and continue. DERBY-5001.
                            // See also LockInterruptTest.
                            if ("08000".equals(e.getSQLState())) {
                                c = thisConf.openDefaultConnection();
                                s = c.prepareStatement(pStmtText);
                                assertTrue(interrupted());
                                interruptsSeen++;
                                retries++;
                                continue;
                            } else {
                                fail("expected 08000", e);
                            }
                        }


                        if (interrupted()) {
                            interruptsSeen++;
                        }

                        c.commit();

                        if (interrupted()) {
                            interruptsSeen++;
                        }
                    }
                }
                s.close();
            } catch (Throwable e) {
                this.e = e;
            } finally {
                try { c.close(); } catch (Exception e) {}
            }

            println("Thread " + getName() + " saw " + interruptsSeen +
                    " interrupts");
        }
    }

    // Number of parallel threads to use
    static int NO_OF_THREADS = 3;

    static long NO_OF_MT_OPS = 10000;

    // Counter to enumerate threads for tests employing several threads.  Reset
    // for each test in setUp.
    private static int threadNo;

    synchronized static int getThreadNo() {
        return ++threadNo;
    }

    private static long randAbs(long l) {
        if (l == Long.MIN_VALUE) {
            return Long.MAX_VALUE; // 2's complement, so no way to make value
                                   // positive
        } else {
            return Math.abs(l);
        }
    }

    // Signal to threads to stop whatever they are doing. Reset
    // for each test in setUp.
    static volatile boolean allDone;

    /**
     * MT write (part 1) and read (part 2) test under interrupt shower.  This
     * stess tests the NIO random access file interrupt channel recovery in
     * RAFContainer4.
     */
    public void testRAFReadWriteMultipleThreads () throws SQLException {
        Statement s = createStatement();

        s.executeUpdate(
            "create procedure tstRAFReadWriteMultipleThreads () " +
            "modifies sql data " +
            "external name 'org.apache.derbyTesting.functionTests" +
            ".tests.store.InterruptResilienceTest" +
            ".tstRAFReadWriteMultipleThreads' " +
            "language java parameter style java");

        s.executeUpdate("call tstRAFReadWriteMultipleThreads()");
    }

    // We do the actual test inside a stored procedure so we can test this for
    // client/server as well, otherwise we would just interrupt the client
    // thread. This SP correponds to #testLongQueryInterrupt
    public static void tstInterruptLongQuery() throws Exception {
        Connection c = DriverManager.getConnection("jdbc:default:connection");
        Statement s = c.createStatement();

        try {
            Thread.currentThread().interrupt();
            ResultSet rs = s.executeQuery(
                "select * from sys.syscolumns");
            while (rs.next()) {};
            fail("expected CONN_INTERRUPT");
        } catch (SQLException e) {
            assertSQLState("expected CONN_INTERRUPT", "08000", e);
            // assertTrue(c.isClosed()); // DERBY-4993
            assertTrue(Thread.interrupted());
        }
    }

    // Test that query if interrupted will get stopped as expected in
    // BasicNoPutResultSetImpl#checkCancellationFlag
    public void testLongQueryInterrupt() throws SQLException {
        Connection c = getConnection();
        Statement s = createStatement();
        s.executeUpdate(
            "create procedure tstInterruptLongQuery() " +
            "reads sql data " +
            "external name 'org.apache.derbyTesting.functionTests" +
            ".tests.store.InterruptResilienceTest" +
            ".tstInterruptLongQuery' " +
            "language java parameter style java");
        try {
            s.executeUpdate("call tstInterruptLongQuery()");
            fail("expected 40XC0 exception");
        } catch (SQLException e) {
            assertSQLState("expected 40XC0", "40XC0", e); // dead statement
            assertTrue(c.isClosed());
        }

    }


    // We do the actual test inside a stored procedure so we can test this for
    // client/server as well, otherwise we would just interrupt the client
    // thread. This SP correponds to #testInterruptBatch
    public static void tstInterruptBatch() throws Exception {
        Connection c = DriverManager.getConnection("jdbc:default:connection");
        Statement s = c.createStatement();
        s.executeUpdate("create table tmp(i int)");
        PreparedStatement ps = c.prepareStatement("insert into tmp values (?)");

        // fill batch:
        for (int i=0; i < 10; i++) {
            s.addBatch("insert into tmp values (" + i + ")");
        }

        s.executeBatch(); // should work OK, since no interrupt present

        // refill batch:
        for (int i=0; i < 10; i++) {
            s.addBatch("insert into tmp values (" + i + ")");
        }

        try {
            Thread.currentThread().interrupt();
            s.executeBatch();
            fail("expected CONN_INTERRUPT");
        } catch (SQLException e) {
            assertSQLState("expected CONN_INTERRUPT", "08000", e);
            // assertTrue(c.isClosed()); // DERBY-4993
            assertTrue(Thread.interrupted());
        }
    }


    // Test that batched statements, if interrupted, will get stopped as
    // expected.
    public void testInterruptBatch() throws SQLException {
        Connection c = getConnection();
        Statement s = createStatement();
        setAutoCommit(false);

        s.executeUpdate(
            "create procedure tstInterruptBatch() " +
            "modifies sql data " +
            "external name 'org.apache.derbyTesting.functionTests" +
            ".tests.store.InterruptResilienceTest" +
            ".tstInterruptBatch' " +
            "language java parameter style java");
        try {
            s.executeUpdate("call tstInterruptBatch()");
            fail("expected 40XC0 exception");
        } catch (SQLException e) {
            assertSQLState("expected 40XC0", "40XC0", e); // dead statement
            assertTrue(c.isClosed());
        }

        setAutoCommit(false);
        s = createStatement();
        // The table created inside stored routine should be gone:
        s.executeUpdate("create table tmp(i int)");
        rollback();

    }


    public void testInterruptShutdown() throws SQLException {
        if (!usingEmbedded()) {
            // Only meaningful for embedded.
            return;
        }

        setAutoCommit(false);

        try {
            Statement s = createStatement();
            s.executeUpdate("create table foo (i int)");
            PreparedStatement ps =
                prepareStatement("insert into foo values ?");

            for (int i = 0; i < 1000; i++) {
                ps.setInt(1,i);
                ps.executeUpdate();
            }

            Thread.currentThread().interrupt();

            TestConfiguration.getCurrent().shutdownDatabase();

            // Assert thread's flag:
            // DERBY-5152: Fails before fix due to lcc going away.
            assertTrue(Thread.currentThread().isInterrupted());

        } finally {
            Thread.interrupted(); // clear flag
        }
    }

    /**
     * DERBY-5233: verify that CREATE TABLE (i.e. container creation) survives
     * interrupts with NIO.
     */
    public void testCreateDropInterrupted() throws SQLException {

        if (!usingEmbedded()) {
            // Only meaningful for embedded.
            return;
        }

        setAutoCommit(false);

        Statement s = createStatement();

        try {
            Thread.currentThread().interrupt();

            s.executeUpdate("create table foo (i int)");
            s.executeUpdate("insert into foo values 1");
            s.executeUpdate("drop table foo");

            // Assert thread's flag:
            assertTrue(Thread.currentThread().isInterrupted());

        } finally {
            Thread.interrupted(); // clear flag
        }
    }
}