File: CacheManagerMBeanTest.java

package info (click to toggle)
derby 10.14.2.0-2
  • links: PTS, VCS
  • area: main
  • in suites: bookworm, bullseye
  • size: 78,896 kB
  • sloc: java: 691,930; sql: 42,686; xml: 20,511; sh: 3,373; sed: 96; makefile: 60
file content (404 lines) | stat: -rw-r--r-- 16,636 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
/*

   Derby - Class org.apache.derbyTesting.functionTests.tests.management.CacheManagerMBeanTest

   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.management;

import java.security.Permission;
import java.sql.PreparedStatement;
import java.sql.Statement;
import java.util.Hashtable;
import java.util.Set;
import javax.management.ObjectName;
import javax.management.RuntimeMBeanException;
import junit.framework.Test;
import org.apache.derby.security.SystemPermission;
import org.apache.derbyTesting.junit.BaseTestSuite;
import org.apache.derbyTesting.junit.JDBC;
import org.apache.derbyTesting.junit.SecurityManagerSetup;
import org.apache.derbyTesting.junit.TestConfiguration;

/**
 * Test cases for {@code CacheManagerMBean}.
 */
public class CacheManagerMBeanTest extends MBeanTest {

    private final static int DEFAULT_PAGE_CACHE_SIZE = 1000;
    private final static int DEFAULT_CONTAINER_CACHE_SIZE = 100;
    private final static int DEFAULT_STATEMENT_CACHE_SIZE = 100;

    private static String[] ALL_ATTRIBUTES = {
        "CollectAccessCounts", "HitCount", "MissCount", "EvictionCount",
        "MaxEntries", "AllocatedEntries", "UsedEntries"
    };

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

    public static Test suite() {
        BaseTestSuite suite = new BaseTestSuite();
        suite.addTest(MBeanTest.suite(CacheManagerMBeanTest.class,
                                      "CacheManagerMBeanTest"));

        // Test that the management bean can only be accessed with proper
        // permissions. The custom policy files only have entries for jar
        // files, so skip these test cases when running from classes.
        if (TestConfiguration.loadingFromJars()) {
            Test negative = new CacheManagerMBeanTest("withoutPermsTest");
            negative = JMXConnectionDecorator.platformMBeanServer(negative);
            negative = new SecurityManagerSetup(negative,
                    "org/apache/derbyTesting/functionTests/tests/management/"
                        + "CacheManagerMBeanTest.withoutPerm.policy");
            suite.addTest(negative);

            Test positive = new CacheManagerMBeanTest("withPermsTest");
            positive = JMXConnectionDecorator.platformMBeanServer(positive);
            positive = new SecurityManagerSetup(positive,
                    "org/apache/derbyTesting/functionTests/tests/management/"
                            + "CacheManagerMBeanTest.withPerm.policy");
            suite.addTest(positive);
        }

        return suite;
    }

    @Override
    protected void setUp() throws Exception {
        // Set up management.
        super.setUp();

        // Shut down the database before running the test case, so that the
        // test case can assume that it starts from a clean state where the
        // cache beans have not started yet. shutdownDatabase() fails if
        // the database is not already booted, so get a connection first to
        // ensure that it is booted (otherwise, the test will fail if it
        // runs standalone or first in a suite).
        getConnection().close();
        TestConfiguration.getCurrent().shutdownDatabase();
    }

    /**
     * Create an {@code ObjectName} that identifies a {@code CacheManager}
     * management bean, or a pattern that potentially matches multiple
     * beans.
     *
     * @param cacheName the name of the cache (such as PageCache), or
     *   {@code null} to create a pattern that matches all cache names
     * @param dbName the name of the database, or {@code null} to create
     *   a pattern that matches all database names
     * @return an {@code ObjectName} suitable for looking up beans
     */
    private ObjectName createObjectName(String cacheName, String dbName)
            throws Exception {
        Hashtable<String, String> props = new Hashtable<String, String>();
        props.put("type", "CacheManager");
        props.put("name", cacheName == null ? "*" : cacheName);
        props.put("db", dbName == null ? "*" : ObjectName.quote(dbName));
        return getDerbyMBeanName(props);
    }

    /**
     * Test case that verifies that {@code CacheManagerMBean}s start when
     * a database is started, and stop when the database is shut down.
     */
    public void testAllMBeansStartedAndStopped() throws Exception {
        // This pattern matches all CacheManager management beans when used
        // in a query.
        ObjectName pattern = createObjectName(null, null);

        // There should be no CacheManager MBeans before the database
        // is booted.
        Set<ObjectName> names = queryMBeans(pattern);
        if (!names.isEmpty()) {
            fail("Should not find MBeans before boot, found: " + names);
        }

        // Boot the database, so that the MBeans are started.
        getConnection();

        // There should be three CacheManager beans. One for the page cache,
        // one for the container cache, and one for the statement cache.
        names = queryMBeans(pattern);
        assertEquals("Incorrect number of MBeans found in " + names,
                     3, names.size());

        // Shut down the database.
        TestConfiguration.getCurrent().shutdownDatabase();

        // There should be no CacheManager MBeans after the database has
        // been shut down.
        names = queryMBeans(pattern);
        if (!names.isEmpty()) {
            fail("Should not find MBeans after shutdown, found: " + names);
        }
    }

    /**
     * Test the {@code CacheManagerMBean} for the page cache.
     */
    public void testPageCache() throws Exception {
        getConnection(); // boot the database
        Set<ObjectName> names =
                queryMBeans(createObjectName("PageCache", null));

        assertEquals("Should have a single page cache", 1, names.size());

        ObjectName name = names.iterator().next();

        assertBooleanAttribute(false, name, "CollectAccessCounts");
        assertLongAttribute(0, name, "HitCount");
        assertLongAttribute(0, name, "MissCount");
        assertLongAttribute(0, name, "EvictionCount");
        assertLongAttribute(DEFAULT_PAGE_CACHE_SIZE, name, "MaxEntries");
        // Cannot reliably tell how many entries to expect.
        // More than 0 for sure.
        Long allocated = (Long) getAttribute(name, "AllocatedEntries");
        assertTrue("Allocated entries: " + allocated, allocated > 0);
        Long used = (Long) getAttribute(name, "UsedEntries");
        assertTrue("Used entries: " + used, used > 0);

        // Execute a statement against a table, so that the cache will be
        // accessed.
        PreparedStatement ps = prepareStatement(
                                    "select * from sysibm.sysdummy1");
        JDBC.assertDrainResults(ps.executeQuery());

        // Since collection of access counts is disabled by default, don't
        // expect the counts to be updated.
        assertLongAttribute(0, name, "HitCount");
        assertLongAttribute(0, name, "MissCount");
        assertLongAttribute(0, name, "EvictionCount");

        // Now enable the access counts and re-execute the query. It
        // should result in a hit in the page cache.
        setAttribute(name, "CollectAccessCounts", Boolean.TRUE);
        assertBooleanAttribute(true, name, "CollectAccessCounts");
        JDBC.assertDrainResults(ps.executeQuery());
        assertLongAttribute(1, name, "HitCount");
        assertLongAttribute(0, name, "MissCount");

        // Disable the access counts.
        setAttribute(name, "CollectAccessCounts", Boolean.FALSE);
        assertBooleanAttribute(false, name, "CollectAccessCounts");
    }

    /**
     * Test the {@code CacheManagerMBean} for the page cache.
     */
    public void testContainerCache() throws Exception {
        getConnection(); // boot the database
        Set<ObjectName> names =
                queryMBeans(createObjectName("ContainerCache", null));

        assertEquals("Should have a single container cache", 1, names.size());

        ObjectName name = names.iterator().next();

        assertBooleanAttribute(false, name, "CollectAccessCounts");
        assertLongAttribute(0, name, "HitCount");
        assertLongAttribute(0, name, "MissCount");
        assertLongAttribute(0, name, "EvictionCount");
        assertLongAttribute(DEFAULT_CONTAINER_CACHE_SIZE, name, "MaxEntries");
        // Cannot reliably tell how many entries to expect.
        // More than 0 for sure.
        Long allocated = (Long) getAttribute(name, "AllocatedEntries");
        assertTrue("Allocated entries: " + allocated, allocated > 0);
        Long used = (Long) getAttribute(name, "UsedEntries");
        assertTrue("Used entries: " + used, used > 0);
    }

    /**
     * Test the {@code CacheManagerMBean} for the statement cache.
     */
    public void testStatementCache() throws Exception {
        getConnection(); // boot the database
        Set<ObjectName> names =
                queryMBeans(createObjectName("StatementCache", null));

        assertEquals("Should have a single statement cache", 1, names.size());

        ObjectName name = names.iterator().next();

        assertBooleanAttribute(false, name, "CollectAccessCounts");
        assertLongAttribute(0, name, "HitCount");
        assertLongAttribute(0, name, "MissCount");
        assertLongAttribute(0, name, "EvictionCount");
        assertLongAttribute(DEFAULT_STATEMENT_CACHE_SIZE, name, "MaxEntries");
        // The statement cache is initially empty
        assertLongAttribute(0, name, "AllocatedEntries");
        assertLongAttribute(0, name, "UsedEntries");

        // Prepare a statement. Now there should be one allocated entry, and
        // that entry is also a used entry.
        prepareStatement("values 1").close();
        assertLongAttribute(1, name, "AllocatedEntries");
        assertLongAttribute(1, name, "UsedEntries");

        // One more...
        prepareStatement("values 2").close();
        assertLongAttribute(2, name, "AllocatedEntries");
        assertLongAttribute(2, name, "UsedEntries");

        // Now clear the statement cache. One more entry is allocated (for
        // the statement that clears the cache), but no entries should be
        // used after the statement cache is cleared.
        Statement s = createStatement();
        s.execute("call syscs_util.syscs_empty_statement_cache()");
        assertLongAttribute(3, name, "AllocatedEntries");
        assertLongAttribute(0, name, "UsedEntries");

        // None of the accesses to the statement cache should have been
        // counted so far.
        assertLongAttribute(0, name, "HitCount");
        assertLongAttribute(0, name, "MissCount");
        assertLongAttribute(0, name, "EvictionCount");

        // Enable counting of cache accesses.
        setAttribute(name, "CollectAccessCounts", Boolean.TRUE);
        assertBooleanAttribute(true, name, "CollectAccessCounts");

        // Prepare a statement. Since the cache is empty, it must be a miss.
        prepareStatement("values 1").close();
        assertLongAttribute(0, name, "HitCount");
        assertLongAttribute(1, name, "MissCount");
        assertLongAttribute(0, name, "EvictionCount");

        // One more...
        prepareStatement("values 2").close();
        assertLongAttribute(0, name, "HitCount");
        assertLongAttribute(2, name, "MissCount");
        assertLongAttribute(0, name, "EvictionCount");

        // Now, this should cause a hit.
        prepareStatement("values 1").close();
        assertLongAttribute(1, name, "HitCount");
        assertLongAttribute(2, name, "MissCount");
        assertLongAttribute(0, name, "EvictionCount");

        // Prepare so many statements that the cache is filled twice.
        for (int i = 0; i < DEFAULT_STATEMENT_CACHE_SIZE * 2; i++) {
            prepareStatement("values 1, " + i).close();
        }

        // None of the above statements were already in the cache, so expect
        // all of them to cause misses.
        assertLongAttribute(1, name, "HitCount");
        assertLongAttribute(
                2 + DEFAULT_STATEMENT_CACHE_SIZE * 2, name, "MissCount");

        // We have prepared 2 + (DEFAULT_STATEMENT_CACHE_SIZE * 2) statements,
        // and the cache can only hold DEFAULT_STATEMENT_CACHE_SIZE of them,
        // so expect DEFAULT_STATEMENT_CACHE_SIZE + 2 statements to have been
        // evicted from the cache.
        assertLongAttribute(2 + DEFAULT_STATEMENT_CACHE_SIZE,
                            name, "EvictionCount");

        // Expect the cache to be full.
        assertLongAttribute(DEFAULT_STATEMENT_CACHE_SIZE, name, "MaxEntries");
        assertLongAttribute(DEFAULT_STATEMENT_CACHE_SIZE,
                            name, "AllocatedEntries");
        assertLongAttribute(DEFAULT_STATEMENT_CACHE_SIZE, name, "UsedEntries");

        // Disable the access counts.
        setAttribute(name, "CollectAccessCounts", Boolean.FALSE);
        assertBooleanAttribute(false, name, "CollectAccessCounts");
    }

    /**
     * Test that the CacheManagerMBean cannot be accessed if the code
     * base lacks SystemPermission("engine", "monitor").
     */
    public void withoutPermsTest() throws Exception {
        getConnection(); // boot the database
        Set<ObjectName> names =
                queryMBeans(createObjectName("StatementCache", null));

        assertEquals("Should have a single statement cache", 1, names.size());

        ObjectName name = names.iterator().next();

        // This is the permission required to access the MBean, but we don't
        // have it.
        SystemPermission monitorPerm =
                new SystemPermission("engine", "monitor");

        // Reading attributes should cause security exception.
        for (String attrName : ALL_ATTRIBUTES) {
            try {
                getAttribute(name, attrName);
                fail();
            } catch (RuntimeMBeanException e) {
                vetException(e, monitorPerm);
            }
        }

        // Modifying attributes should also cause security exception.
        try {
            setAttribute(name, "CollectAccessCounts", Boolean.FALSE);
            fail();
        } catch (RuntimeMBeanException e) {
            vetException(e, monitorPerm);
        }
    }

    /**
     * Check that an exception raised when accessing an MBean, is caused
     * by missing a specific permission.
     *
     * @param e the exception to check
     * @param perm the missing permission to check for
     */
    private void vetException(RuntimeMBeanException e, Permission perm) {
        Throwable cause = e.getCause();
        if (cause instanceof SecurityException) {
            String msg = cause.getMessage();
            if (msg != null && msg.contains(perm.toString())) {
                // This is the expected exception.
                return;
            }
        }

        fail("Unexpected exception", e);
    }

    /**
     * Test that the CacheManagerMBean can be accessed if the code base
     * runs with the same permissions as the {@link #withoutPermsTest} test
     * case plus SystemPermission("engine", "monitor").
     */
    public void withPermsTest() throws Exception {
        getConnection(); // boot the database
        Set<ObjectName> names =
                queryMBeans(createObjectName("StatementCache", null));

        assertEquals("Should have a single statement cache", 1, names.size());

        ObjectName name = names.iterator().next();

        // Expect no SecurityException when reading attributes ...
        for (String attrName : ALL_ATTRIBUTES) {
            getAttribute(name, attrName);
        }

        // ... or when modifying them.
        setAttribute(name, "CollectAccessCounts", Boolean.FALSE);
    }
}