File: RemoveDbStress.java

package info (click to toggle)
libdb-je-java 3.3.62-3
  • links: PTS, VCS
  • area: main
  • in suites: squeeze
  • size: 12,832 kB
  • ctags: 18,708
  • sloc: java: 149,906; xml: 1,980; makefile: 14; sh: 12
file content (257 lines) | stat: -rw-r--r-- 8,963 bytes parent folder | download
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
/*-
 * See the file LICENSE for redistribution information.
 *
 * Copyright (c) 2002,2008 Oracle.  All rights reserved.
 *
 * $Id: RemoveDbStress.java,v 1.2 2008/01/07 14:29:20 cwl Exp $
 */

import java.io.File;
import java.util.Random;

import com.sleepycat.je.Cursor;
import com.sleepycat.je.Database;
import com.sleepycat.je.DatabaseConfig;
import com.sleepycat.je.DatabaseEntry;
import com.sleepycat.je.DatabaseException;
import com.sleepycat.je.Environment;
import com.sleepycat.je.EnvironmentConfig;
import com.sleepycat.je.LockMode;
import com.sleepycat.je.OperationStatus;
import com.sleepycat.je.config.EnvironmentParams;
import com.sleepycat.je.dbi.MemoryBudget;

/**
 * Make sure no bugs are spotted when remove/truncate database is being called
 * and the log cleaner and checkpointer threads are interacting with the db.
 */
public class RemoveDbStress {
    private int totalIterations = 500000;
    private int totalThreads = 4;
    private String envHome = "./tmp";
    private Random random = new Random();
    private Environment env = null;

    public static void main(String[] args) {

        RemoveDbStress stress = new RemoveDbStress();
        try {
            stress.run(args);
        } catch (Exception e){
            System.err.println("Error initializing env!");
            e.printStackTrace();
            System.exit(1);
        }
    }

    
    /** Kickoff the run. */
    private void run(String args[]) throws Exception {

        for (int i = 0; i < args.length; i += 1) {
            String arg = args[i];
            boolean moreArgs = i < args.length - 1;
            if (arg.equals("-h") && moreArgs) {
                envHome = args[++i];
            } else if (arg.equals("-iter") && moreArgs) {
                totalIterations = Integer.parseInt(args[++i]);
            } else if (arg.equals("-threads") && moreArgs) {
                totalThreads = Integer.parseInt(args[++i]);
            } else {
                usage("Unknown arg: " + arg);
            }
        }
        openEnv();
        printArgs(args);
        
        /*
         * Perform some operations to simulate a scenario to find bugs:
         * make sure remove/truncate database is being called and the log
         * cleaner and checkpointer threads are interacting with the db.
         */
        Worker[] workers = new Worker[totalThreads];
        for (int i = 0; i < totalThreads; i += 1) {
            workers[i] = new Worker(i);
            workers[i].start();
            Thread.sleep(1000); /* Stagger threads. */
        }
        for (int i = 0; i < totalThreads; i += 1) {
            workers[i].join();
        }
        
        closeEnv();
    }
    
    /** Print usage. */
    private void usage(String error) {

        if (error != null) {
            System.err.println(error);
        }
        System.err.println
            ("java " + getClass().getName() + '\n' +
             "      [-h <homeDir>] [-iter <iterations>] " +
             "[-threads <appThreads>]\n");
        System.exit(1);
    }

    /** Print cmd arguments and database env settings to log file. */
    private void printArgs(String[] args)
        throws DatabaseException {

        System.out.print("Command line arguments:");
        for (String arg : args) {
            System.out.print(' ');
            System.out.print(arg);
        }
        System.out.println();
        System.out.println();
        System.out.println("Environment configuration:");
        System.out.println(env.getConfig());
        System.out.println();
    }
    
    /**
     * Open an Environment.
     */
    private void openEnv() throws Exception {
        EnvironmentConfig config = new EnvironmentConfig();
        config.setAllowCreate(true);

        config.setConfigParam
            (EnvironmentParams.MAX_MEMORY.getName(),
             MemoryBudget.MIN_MAX_MEMORY_SIZE_STRING);
        /* Don't track detail with a tiny cache size. */
        config.setConfigParam
            (EnvironmentParams.CLEANER_TRACK_DETAIL.getName(), "false");
        config.setConfigParam
            (EnvironmentParams.CLEANER_BYTES_INTERVAL.getName(),
             "100");
        config.setConfigParam
            (EnvironmentParams.CHECKPOINTER_BYTES_INTERVAL.getName(),
             "100");
        config.setConfigParam
            (EnvironmentParams.COMPRESSOR_WAKEUP_INTERVAL.getName(),
             "1000000");
        config.setConfigParam(EnvironmentParams.LOG_MEM_SIZE.getName(),
                  EnvironmentParams.LOG_MEM_SIZE_MIN_STRING);
        config.setConfigParam
            (EnvironmentParams.NUM_LOG_BUFFERS.getName(), "2");
        config.setConfigParam
            (EnvironmentParams.ENV_RUN_EVICTOR.getName(), "true");
        config.setConfigParam
            (EnvironmentParams.ENV_RUN_INCOMPRESSOR.getName(), "true");
        config.setConfigParam
            (EnvironmentParams.ENV_RUN_CLEANER.getName(), "true");
        config.setConfigParam
            (EnvironmentParams.ENV_RUN_CHECKPOINTER.getName(), "true");
        env = new Environment(new File(envHome), config);
    }

    private void closeEnv()
        throws DatabaseException {
        env.close();
    }
    
    class Worker extends Thread {
        private int iterations = 0;

        /** The identifier of the current thread. */
        private int id;

        /**
         * Creates a new worker thread object.
         */
        public Worker(int id) {
            this.id = id;
        }

        /**
         * This thread is responsible for executing transactions.
         */
        public void run() {

            long startTime = System.currentTimeMillis();
            while (iterations < totalIterations) {
                try {
                    doOperations();
                } catch (Exception e) {
                    System.err.println
                        ("Error! " + iterations +
                         " iterations processed so far.");
                    e.printStackTrace();
                    System.exit(1);
                }
                iterations += 1;
                if ((iterations % 1000) == 0)
                    System.out.println
                        (new java.util.Date() + ": Thread " + id +
                         " finishes " + iterations + " iterations.");
            }
            long endTime = System.currentTimeMillis();
            float elapsedSec = (float) ((endTime - startTime) / 1e3);
            float throughput = ((float) totalIterations) / elapsedSec;
            System.out.println
                ("Thread " + id + " finishes " + iterations +
                 " iterations in:" + elapsedSec +
                 " sec, average throughput:" + throughput + " op/sec.");
        }
        
        /**
         * Perform some insert and delete operations in order to wakeup the
         * checkpointer, cleaner and evictor.
         */
        private void doOperations() throws DatabaseException {
            String dbName = "testDb" + id;
            DatabaseConfig dbConfig = new DatabaseConfig();
            dbConfig.setAllowCreate(true);
            dbConfig.setSortedDuplicates(true);
            Database db = env.openDatabase(null, dbName, dbConfig);
            Cursor cursor = db.openCursor(null, null);
            doSimpleCursorPutAndDelete(cursor);
            cursor.close();
            db.close();
            
            if (random.nextFloat() < .5) {
                env.removeDatabase(null, dbName);
            } else {
                env.truncateDatabase(null, dbName, false);
            }
        }

        /**
         * Write some data to wakeup the checkpointer, cleaner and evictor.
         */
        protected void doSimpleCursorPutAndDelete(Cursor cursor)
            throws DatabaseException {
            
            String[] simpleKeyStrings = {
                    "foo", "bar", "baz", "aaa", "fubar",
                    "foobar", "quux", "mumble", "froboy" };

            String[] simpleDataStrings = {
                    "one", "two", "three", "four", "five",
                    "six", "seven", "eight", "nine" };

            DatabaseEntry foundKey = new DatabaseEntry();
            DatabaseEntry foundData = new DatabaseEntry();

            for (int i = 0; i < simpleKeyStrings.length; i++) {
                foundKey.setData(simpleKeyStrings[i].getBytes());
                foundData.setData(simpleDataStrings[i].getBytes());
                if (cursor.putNoOverwrite(foundKey, foundData) !=
                    OperationStatus.SUCCESS) {
                    throw new DatabaseException("non-0 return");
                }
            }

            OperationStatus status =
                cursor.getFirst(foundKey, foundData, LockMode.DEFAULT);

            while (status == OperationStatus.SUCCESS) {
                cursor.delete();
                status = cursor.getNext(foundKey, foundData, LockMode.DEFAULT);
            }
        }
    }
}