Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
PojavLauncherTeam
GitHub Repository: PojavLauncherTeam/openj9
Path: blob/master/test/functional/CacheManagement/src/tests/sharedclasses/TestUtils.java
6004 views
1
/*******************************************************************************
2
* Copyright (c) 2010, 2021 IBM Corp. and others
3
*
4
* This program and the accompanying materials are made available under
5
* the terms of the Eclipse Public License 2.0 which accompanies this
6
* distribution and is available at https://www.eclipse.org/legal/epl-2.0/
7
* or the Apache License, Version 2.0 which accompanies this distribution and
8
* is available at https://www.apache.org/licenses/LICENSE-2.0.
9
*
10
* This Source Code may also be made available under the following
11
* Secondary Licenses when the conditions for such availability set
12
* forth in the Eclipse Public License, v. 2.0 are satisfied: GNU
13
* General Public License, version 2 with the GNU Classpath
14
* Exception [1] and GNU General Public License, version 2 with the
15
* OpenJDK Assembly Exception [2].
16
*
17
* [1] https://www.gnu.org/software/classpath/license.html
18
* [2] http://openjdk.java.net/legal/assembly-exception.html
19
*
20
* SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 OR LicenseRef-GPL-2.0 WITH Assembly-exception
21
*******************************************************************************/
22
23
package tests.sharedclasses;
24
25
import java.io.File;
26
import java.io.FileInputStream;
27
import java.io.FileOutputStream;
28
import java.io.IOException;
29
import java.io.InputStream;
30
import java.net.URL;
31
import java.util.ArrayList;
32
import java.util.Enumeration;
33
import java.util.HashSet;
34
import java.util.List;
35
import java.util.Properties;
36
import java.util.Set;
37
38
39
/**
40
* A superclass for test programs that provides lots of helpful methods for setting up
41
* a shared classes environment and running shared classes commands.
42
*
43
* Configuration is done from a config file. The default name is config.properties, which can
44
* be overridden with a -Dconfig.properties=<pathToConfigFile>
45
*/
46
public class TestUtils {
47
48
public static boolean debug = false;
49
50
// Known commands, defined in the config file
51
public static final String DestroyCacheCommand = "destroyCache";
52
public static final String DestroyPersistentCacheCommand = "destroyPersistentCache";
53
public static final String DestroyNonPersistentCacheCommand = "destroyNonPersistentCache";
54
public static final String RunSimpleJavaProgram = "runSimpleJavaProgram";
55
public static final String RunComplexJavaProgramWithPersistentCache = "runComplexJavaProgram";
56
public static final String RunPrintStats = "runPrintStats";
57
public static final String RunPrintAllStats = "runPrintAllStats";
58
public static final String RunResetPersistentCache = "runResetPersistentCache";
59
public static final String RunResetNonPersistentCache = "runResetNonPersistentCache";
60
public static final String RunSimpleJavaProgramWithPersistentCache = "runSimpleJavaProgramWithPersistentCache";
61
public static final String RunSimpleJavaProgramWithPersistentCacheCheckStringTable = "runSimpleJavaProgramWithPersistentCacheCheckStringTable";
62
public static final String RunSimpleJavaProgramWithNonPersistentCache = "runSimpleJavaProgramWithNonPersistentCache";
63
public static final String CreateNonPersistentCache = "createNonPersistentCache";
64
public static final String CreateCacheSnapshot = "createCacheSnapshot";
65
public static final String ListAllCaches = "listAllCaches";
66
public static final String ExpireAllCaches = "expireAllCaches";
67
public static final String DestroyAllCaches = "destroyAllCaches";
68
public static final String DestroyAllSnapshots = "destroyAllSnapshots";
69
public static final String CreateIncompatibleCache = "createIncompatibleCache";
70
public static final String RunInfiniteLoopJavaProgramWithPersistentCache = "runInfiniteLoopJavaProgramWithPersistentCache";
71
public static final String RunInfiniteLoopJavaProgramWithNonPersistentCache = "runInfiniteLoopJavaProgramWithNonPersistentCache";
72
public static final String ExpireAllCachesWithTime = "expireAllCachesWithTime";
73
public static final String RunSimpleJavaProgramWithAgentWithPersistentCache = "runSimpleJavaProgramWithAgentWithPersistentCache";
74
public static final String RunSimpleJavaProgramWithAgentWithNonPersistentCache = "runSimpleJavaProgramWithAgentWithNonPersistentCache";
75
public static final String RunHanoiProgramWithCache = "runHanoiProgramWithCache";
76
public static final String CheckJavaVersion = "checkJavaVersion";
77
78
private static final String CMD_PREFIX="cmd.";
79
80
private static boolean isRealtimeDefined = false;
81
82
static Properties config;
83
84
/**
85
* Load the properties from the configuration file - some of these can be overridden
86
* with -D - these are cacheDir and controlDir
87
*/
88
static {
89
try {
90
91
config = new Properties();
92
93
// Load the target specific properties ... note that we default to windows ...
94
String configFile = System.getProperty("test.target.config", "config.defaults");
95
InputStream is = TestUtils.class.getClassLoader().getResourceAsStream(configFile);
96
config.load(is);
97
98
if (config.getProperty("logCommands","false").equalsIgnoreCase("true")) {
99
RunCommand.logCommands=true;
100
}
101
102
if (config.getProperty("debug","false").equalsIgnoreCase("true")) {
103
debug = true;
104
}
105
// Allow some sys props to override the config
106
//String override = System.getProperty("cacheDir");
107
//if (override!=null) config.put("cacheDir",override);
108
//override = System.getProperty("controlDir");
109
//if (override!=null) config.put("controlDir",override);
110
//override = System.getProperty("defaultCacheLocation");
111
//if (override!=null) config.put("defaultCacheLocation",override);
112
113
// Check if the defaultCacheLocation was set, otherwise lets work it out
114
if (config.getProperty("defaultCacheLocation")==null) {
115
if (config.getProperty("cacheDir")==null && config.getProperty("controlDir")==null) {
116
System.out.println("Please set either defaultCacheLocation or cacheDir or controlDir in the config file or with -D!");
117
}
118
}
119
120
if (config.get("apploc")==null) {
121
// work it out...
122
URL url = TestUtils.class.getClassLoader().getResource("testcode.jar");
123
String thePath = new File(url.getFile()).getParentFile().getAbsolutePath();
124
thePath = thePath.replace('\\','/');
125
config.put("apploc", thePath);
126
}
127
128
/* */
129
String javaTestCommand = System.getProperty("JAVA_TEST_COMMAND","");
130
String java5home = System.getProperty("JAVA5_HOME","");
131
String exesuff = System.getProperty("EXECUTABLE_SUFFIX","");
132
String realtime = System.getProperty("REALTIME","");
133
javaTestCommand=javaTestCommand.replace('\\','/');
134
java5home=java5home.replace('\\','/');
135
136
if (!realtime.equals("") && !realtime.equalsIgnoreCase("false")) {
137
isRealtimeDefined = true;
138
}
139
140
config.put("java_exe",javaTestCommand);
141
142
config.put("java5_exe",java5home + "/" + "jre" + "/" + "bin" + "/" + "java"+exesuff);
143
config.put("java5c_exe",java5home + "/" + "bin" + "/" + "javac"+exesuff);
144
config.put("java5jar_exe",java5home + "/" + "bin" + "/" + "jar"+exesuff);
145
146
147
config.put("cmd.runCompileSimpleApp","%java5c_exe% %1%/SimpleApp.java");
148
config.put("cmd.runCompileSimpleApp2","%java5c_exe% %1%/SimpleApp2.java");
149
config.put("cmd.runJarClassesInDir","%java5jar_exe% cf MySimpleApp.jar -C %1% .");
150
config.put("cmd.runProgramSimpleApp","%java_exe% "+(isRealtimeDefined ? "-Xrealtime " : "")+"-Xshareclasses:"+(isRealtimeDefined ? "grow," : "")+"persistent,name=%1%,verbose -classpath %2% SimpleApp");
151
152
System.out.println("\n--------- PROGRAM RUN COMMANDLINE INFO ---------");
153
System.out.println("java_exe =\t" + config.get("java_exe"));
154
System.out.println("cmd.runProgramSimpleApp =\t" + config.get("cmd.runProgramSimpleApp" + "\n"));
155
156
if (config.getProperty("logCommands","false").equalsIgnoreCase("true")) {
157
RunCommand.logCommands=true;
158
}
159
160
if (exesuff.equals(".exe")==true)
161
{
162
String appdata = System.getenv("APPDATA");
163
String defaultCacheLocation = new File(appdata+"\\..\\Local Settings\\Application Data").getAbsolutePath();
164
config.put("defaultCacheLocation",defaultCacheLocation);
165
}
166
else
167
{
168
if (false == isDefaultDirTmp()) {
169
config.put("defaultCacheGroupAccessLocation","/tmp/");
170
}
171
config.put("defaultCacheLocation","/tmp/");
172
}
173
174
} catch (Exception e) {
175
e.printStackTrace();
176
}
177
}
178
179
public static boolean realtimeTestsSelected(){
180
return isRealtimeDefined;
181
}
182
183
public static void registerCommand(String key, String command) {
184
config.put("cmd."+key,command);
185
}
186
187
public static String getCacheDir() { return (String)config.get("cacheDir");}
188
public static String getCacheGroupAccessDir() { return (String)config.get("defaultCacheGroupAccessLocation");}
189
public static void setCacheDir(String dir) {
190
if (dir==null) config.remove("cacheDir");
191
else {
192
config.put("cacheDir",dir);
193
}
194
}
195
196
public static String getControlDir() { return (String)config.get("controlDir");}
197
public static void setControlDir(String dir) {
198
if (dir==null) config.remove("controlDir");
199
else config.put("controlDir",dir);
200
}
201
202
203
204
205
public static String getCommand(String commandKey) {
206
return getCommand(commandKey,"","","");
207
}
208
209
public static String getCommand(String commandKey,String insert1) {
210
return getCommand(commandKey,insert1,"","");
211
}
212
213
public static String getCommand(String commandKey,String insert1,String insert2) {
214
return getCommand(commandKey,insert1,insert2,"");
215
}
216
217
public static String getCommand(String commandKey,String insert,String insert2,String insert3) {
218
String theCommand=(String)config.get(CMD_PREFIX+commandKey);
219
if (theCommand==null) {
220
fail("Could not find command "+commandKey);
221
}
222
Enumeration keys = config.keys();
223
while (keys.hasMoreElements()) {
224
String k = (String)keys.nextElement();
225
if (k.startsWith(CMD_PREFIX)) continue; // not something to apply
226
String replaceVal = config.getProperty(k);
227
theCommand = theCommand.replaceAll("%"+k+"%", replaceVal);
228
}
229
if (insert!=null) {
230
231
// need to copy with one special case, where we are using a back level
232
// VM to create an incompatible cache - since it wont understand cacheDir
233
// yet we want to create the cache in a particular directory. we will
234
// need to use controlDir in this case...
235
if (commandKey.equals(CreateIncompatibleCache)) {
236
if (config.get("cacheDir")!=null) {
237
insert = insert+",controlDir="+config.getProperty("cacheDir"); // gotta use controlDir...
238
}
239
if (config.get("controlDir")!=null) {
240
insert = insert+",controlDir="+config.getProperty("controlDir");
241
}
242
}
243
else if (commandKey.equals("runCompileSimpleApp") || commandKey.equals("runCompileSimpleApp2") ||commandKey.equals("runJarClassesInDir"))
244
{
245
246
}
247
//getCacheFileName getCacheFileNameNonPersist
248
else {
249
250
// Insert %1% is always the cache name "name=%1%"
251
// we can add subsequent options through a tiny extension to that
252
if (config.get("cacheDir")!=null) {
253
insert = insert+",cacheDir="+config.getProperty("cacheDir");
254
}
255
if (config.get("controlDir")!=null) {
256
insert = insert+",controlDir="+config.getProperty("controlDir");
257
}
258
}
259
theCommand = fixup(theCommand,"%1%",insert);
260
theCommand = fixup(theCommand,"%2%",insert2);
261
theCommand = fixup(theCommand,"%3%",insert3);
262
}
263
return theCommand;
264
}
265
266
public static String fixup(String what,String from,String to) {
267
String result = what;
268
int idx = what.indexOf(from);
269
while (idx!=-1) {
270
StringBuffer s = new StringBuffer(what.substring(0,idx));
271
s.append(to);
272
s.append(what.substring(idx+from.length()));
273
what = s.toString();
274
idx = what.indexOf(from);
275
}
276
return what;
277
}
278
279
public static void createNonPersistentCache(String cachename) {
280
log("Creating non-persistent cache '"+cachename+"'");
281
RunCommand.execute(getCommand(CreateNonPersistentCache,cachename));
282
}
283
284
public static void createCacheSnapshot(String cachename) {
285
log("Creating snapshot of cache'" + cachename + "'");
286
String expectedErrorMessages[] = new String[] {
287
"JVMSHRC700I" /* Snapshot of non-persistent shared cache <cachename> has been created */
288
};
289
RunCommand.execute(getCommand(CreateCacheSnapshot, cachename), null, expectedErrorMessages, false, false, null);
290
}
291
292
public static void createPersistentCache(String cachename) {
293
log("Creating persistent cache '"+cachename+"'");
294
RunCommand.execute(getCommand(RunSimpleJavaProgram,cachename));
295
}
296
297
298
public static void listAllCaches() {
299
RunCommand.execute(getCommand(ListAllCaches),false);
300
}
301
302
public static void expireAllCaches() {
303
RunCommand.execute(getCommand(ExpireAllCaches),false);
304
}
305
306
public static void expireAllCachesWithTime(String timeInMins) {
307
RunCommand.execute(getCommand(ExpireAllCachesWithTime, timeInMins),false);
308
}
309
310
public static void runDestroyAllCaches() {
311
RunCommand.execute(getCommand(DestroyAllCaches),false);
312
}
313
314
public static void runDestroyAllGroupAccessCaches() {
315
RunCommand.execute(getCommand(DestroyAllCaches, ",groupaccess"),false);
316
}
317
318
public static void runDestroyAllSnapshots() {
319
RunCommand.execute(getCommand(DestroyAllSnapshots), false);
320
}
321
322
public static void createIncompatibleCache(String cachename) {
323
RunCommand.execute(getCommand(CreateIncompatibleCache,cachename));
324
}
325
326
public static void runSimpleJavaProgram(String cachename) {
327
RunCommand.execute(getCommand(RunSimpleJavaProgram,cachename));
328
}
329
330
public static void checkJavaVersion() {
331
RunCommand.execute(getCommand(CheckJavaVersion), false);
332
}
333
334
/**
335
* @example runPrintStats("foo",false,"classpath");
336
* @example runPrintStats("foo",false,"url");
337
* @example runPrintStats("foo",false,"token");
338
* @example runPrintStats("foo",false,"romclass");
339
* @example runPrintStats("foo",true,"rommethod");
340
* @example runPrintStats("foo",true,"aot");
341
* @example runPrintStats("foo",true,"jitprofile");
342
* @example runPrintStats("foo",true,"zipcache");
343
*/
344
public static void runPrintStats(String cachename,boolean isPersistent, String option) {
345
RunCommand.execute(getCommand(RunPrintStats,cachename,"="+option,(isPersistent?"":",nonpersistent")),false);
346
}
347
public static void runPrintStats(String cachename,boolean isPersistent) {
348
RunCommand.execute(getCommand(RunPrintStats,cachename,"",(isPersistent?"":",nonpersistent")),false);
349
}
350
351
public static void runResetPersistentCache(String cachename) {
352
RunCommand.execute(getCommand(RunResetPersistentCache,cachename),false);
353
}
354
355
public static void runResetNonPersistentCache(String cachename) {
356
RunCommand.execute(getCommand(RunResetNonPersistentCache,cachename),false);
357
}
358
359
public static void runPrintAllStats(String cachename,boolean isPersistent) {
360
RunCommand.execute(getCommand(RunPrintAllStats,cachename,(isPersistent?"":",nonpersistent")),false);
361
}
362
public static void runSimpleJavaProgramWithPersistentCache(String cachename) {
363
RunCommand.execute(getCommand(RunSimpleJavaProgramWithPersistentCache,cachename));
364
checkOutputForDump(false);
365
}
366
public static void runSimpleJavaProgramWithPersistentCacheCheckStringTable(String cachename) {
367
RunCommand.execute(getCommand(RunSimpleJavaProgramWithPersistentCacheCheckStringTable,cachename));
368
checkOutputForDump(false);
369
}
370
public static void runSimpleJavaProgramWithPersistentCache(String cachename,boolean careAboutExitValue) {
371
RunCommand.execute(getCommand(RunSimpleJavaProgramWithPersistentCache,cachename),careAboutExitValue);
372
checkOutputForDump(false);
373
}
374
public static void runSimpleJavaProgramWithPersistentCacheCheckForDump(String cachename) {
375
RunCommand.execute(getCommand(RunSimpleJavaProgramWithPersistentCache,cachename));
376
checkOutputForDump(true);
377
}
378
public static void runSimpleJavaProgramWithPersistentCacheCheckForDump(String cachename, boolean careAboutExitValue) {
379
RunCommand.execute(getCommand(RunSimpleJavaProgramWithPersistentCache,cachename), careAboutExitValue);
380
checkOutputForDump(true);
381
}
382
/* waitForMessage is the message for which this process waits */
383
public static void runInfiniteLoopJavaProgramWithPersistentCache(String cachename, String waitForMessage) {
384
RunCommand.execute(getCommand(RunInfiniteLoopJavaProgramWithPersistentCache, cachename), waitForMessage);
385
checkOutputForDump(false);
386
}
387
/* waitForMessage is the message for which this process waits */
388
public static void runInfiniteLoopJavaProgramWithNonPersistentCache(String cachename, String waitForMessage) {
389
RunCommand.execute(getCommand(RunInfiniteLoopJavaProgramWithNonPersistentCache, cachename), waitForMessage);
390
checkOutputForDump(false);
391
}
392
393
/**
394
* Will execute a simple java program using the named cache, extra options like "verbose,silent" can be specified
395
* and they will be appended to the constructed -Xshareclasses option string that is used to launch the program.
396
* @param cachename name of the cache to use
397
* @param extraSharedClassesOptions extra shared classes options, eg "verbose,silent"
398
*/
399
public static void runSimpleJavaProgramWithPersistentCache(String cachename,String extraSharedClassesOptions) {
400
// this hides the magic rule that due to the command construction, the "name=" is always the last part of the
401
// Xshareclasses string in the defined commands. So to add more shared classes options we just have to append
402
// them to the cache name.
403
runSimpleJavaProgramWithPersistentCache(cachename+
404
(extraSharedClassesOptions!=null&&extraSharedClassesOptions.length()>0?","+extraSharedClassesOptions:""));
405
}
406
407
/**
408
* Will execute a simple java program using the named cache, extra options like "verbose,silent" can be specified
409
* and they will be appended to the constructed -Xshareclasses option string that is used to launch the program.
410
* @param cachename name of the cache to use
411
* @param extraSharedClassesOptions extra shared classes options, eg "verbose,silent"
412
* @param waitForMessage message for which this process waits
413
*/
414
public static void runInfiniteLoopJavaProgramWithPersistentCache(String cachename,String extraSharedClassesOptions,String waitForMessage) {
415
// this hides the magic rule that due to the command construction, the "name=" is always the last part of the
416
// Xshareclasses string in the defined commands. So to add more shared classes options we just have to append
417
// them to the cache name.
418
runInfiniteLoopJavaProgramWithPersistentCache(cachename+
419
(extraSharedClassesOptions!=null&&extraSharedClassesOptions.length()>0?","+extraSharedClassesOptions:""), waitForMessage);
420
}
421
422
/**
423
* Will execute a simple java program using the named cache, extra options like "verbose,silent" can be specified
424
* and they will be appended to the constructed -Xshareclasses option string that is used to launch the program.
425
* @param cachename name of the cache to use
426
* @param extraSharedClassesOptions extra shared classes options, eg "verbose,silent"
427
*/
428
public static void runSimpleJavaProgramWithNonPersistentCache(String cachename,String extraSharedClassesOptions) {
429
// this hides the magic rule that due to the command construction, the "name=" is always the last part of the
430
// Xshareclasses string in the defined commands. So to add more shared classes options we just have to append
431
// them to the cache name.
432
runSimpleJavaProgramWithNonPersistentCache(cachename+
433
(extraSharedClassesOptions!=null&&extraSharedClassesOptions.length()>0?","+extraSharedClassesOptions:""));
434
}
435
436
/**
437
* Will execute a simple java program using the named cache, extra options like "verbose,silent" can be specified
438
* and they will be appended to the constructed -Xshareclasses option string that is used to launch the program.
439
* @param cachename name of the cache to use
440
* @param extraSharedClassesOptions extra shared classes options, eg "verbose,silent"
441
* @param waitForMessage message for which this process waits
442
*/
443
public static void runInfiniteLoopJavaProgramWithNonPersistentCache(String cachename,String extraSharedClassesOptions,String waitForMessage) {
444
// this hides the magic rule that due to the command construction, the "name=" is always the last part of the
445
// Xshareclasses string in the defined commands. So to add more shared classes options we just have to append
446
// them to the cache name.
447
runInfiniteLoopJavaProgramWithNonPersistentCache(cachename+
448
(extraSharedClassesOptions!=null&&extraSharedClassesOptions.length()>0?","+extraSharedClassesOptions:""), waitForMessage);
449
}
450
451
protected static void checkOutputForDump(boolean dumpGenerated) {
452
if (dumpGenerated) {
453
checkOutputContains("JVMDUMP....", "The JVM is dumping!!");
454
} else {
455
checkOutputDoesNotContain("JVMDUMP....", "The JVM is dumping!!");
456
}
457
}
458
459
public static void runSimpleJavaProgramWithPersistentCacheAndReset(String cachename) {
460
RunCommand.execute(getCommand(RunSimpleJavaProgramWithPersistentCache,cachename+",reset"));
461
}
462
463
public static void runSimpleJavaProgramWithNonPersistentCacheMayFail(String cachename) {
464
RunCommand.executeMayFail(getCommand(RunSimpleJavaProgramWithNonPersistentCache,cachename));
465
}
466
467
public static void runSimpleJavaProgramWithNonPersistentCache(String cachename) {
468
RunCommand.execute(getCommand(RunSimpleJavaProgramWithNonPersistentCache,cachename));
469
}
470
471
public static void runSimpleJavaProgramWithNonPersistentCache(String cachename,boolean careAboutExitValue) {
472
RunCommand.execute(getCommand(RunSimpleJavaProgramWithNonPersistentCache,cachename),careAboutExitValue);
473
}
474
475
public static void runSimpleJavaProgramWithNonPersistentCacheAndReset(String cachename) {
476
RunCommand.execute(getCommand(RunSimpleJavaProgramWithNonPersistentCache,cachename+",reset"));
477
}
478
/**
479
* @param cachename name of the cache to use
480
* @param agentName name of the JVMTI agent. Actually it needs to be one of the JVMTI test in com.ibm.jvmti.tests package.
481
* See TestSharedCacheEnableBCI.java for an example.
482
* @param agentArgs arguments to JVMTI agent. Again, these are the arguments passed to JVMTI test in com.ibm.jvmti.tests package.
483
* See TestSharedCacheEnableBCI.java for an example.
484
*/
485
public static void runSimpleJavaProgramWithAgentWithPersistentCache(String cachename, String agentName, String agentArgs) {
486
RunCommand.execute(getCommand(RunSimpleJavaProgramWithAgentWithPersistentCache, cachename, agentName, agentArgs));
487
checkOutputForDump(false);
488
}
489
/**
490
* Will execute a simple java program with a JVMTI agent using the named cache, extra options like "verbose,silent" can be specified
491
* and they will be appended to the constructed -Xshareclasses option string that is used to launch the program.
492
* @param cachename name of the cache to use
493
* @param extraSharedClassesOptions extra shared classes options, eg "verbose,silent"
494
*/
495
public static void runSimpleJavaProgramWithAgentWithPersistentCache(String cachename, String extraSharedClassesOptions, String agentName, String agentArgs) {
496
// this hides the magic rule that due to the command construction, the "name=" is always the last part of the
497
// Xshareclasses string in the defined commands. So to add more shared classes options we just have to append
498
// them to the cache name.
499
runSimpleJavaProgramWithAgentWithPersistentCache(cachename+
500
(extraSharedClassesOptions!=null&&extraSharedClassesOptions.length()>0?","+extraSharedClassesOptions:""),
501
agentName, agentArgs);
502
}
503
/**
504
* @param cachename name of the cache to use
505
* @param agentName name of the JVMTI agent. Actually it needs to be one of the JVMTI test in com.ibm.jvmti.tests package.
506
* See TestSharedCacheEnableBCI.java for an example.
507
* @param agentArgs arguments to JVMTI agent. Again, these are the arguments passed to JVMTI test in com.ibm.jvmti.tests package.
508
* See TestSharedCacheEnableBCI.java for an example.
509
*/
510
public static void runSimpleJavaProgramWithAgentWithNonPersistentCache(String cachename, String agentName, String agentArgs) {
511
RunCommand.execute(getCommand(RunSimpleJavaProgramWithAgentWithNonPersistentCache, cachename, agentName, agentArgs));
512
checkOutputForDump(false);
513
}
514
/**
515
* Will execute a simple java program with a JVMTI agent using the named cache, extra options like "verbose,silent" can be specified
516
* and they will be appended to the constructed -Xshareclasses option string that is used to launch the program.
517
* @param cachename name of the cache to use
518
* @param extraSharedClassesOptions extra shared classes options, eg "verbose,silent"
519
*/
520
public static void runSimpleJavaProgramWithAgentWithNonPersistentCache(String cachename, String extraSharedClassesOptions, String agentName, String agentArgs) {
521
// this hides the magic rule that due to the command construction, the "name=" is always the last part of the
522
// Xshareclasses string in the defined commands. So to add more shared classes options we just have to append
523
// them to the cache name.
524
runSimpleJavaProgramWithAgentWithNonPersistentCache(cachename+
525
(extraSharedClassesOptions!=null&&extraSharedClassesOptions.length()>0?","+extraSharedClassesOptions:""),
526
agentName, agentArgs);
527
}
528
529
/**
530
* Will execute a hanoi program using the named cache, extraSharedClassesOptions like "verbose,silent" can be specified
531
* and they will be appended to the constructed -Xshareclasses option string. extraJavaOpt like "-Xint" can also be
532
* specified that is used to launch the program.
533
*
534
* @param cachename name of the cache to use
535
* @param extraSharedClassesOptions extra shared classes options, eg "verbose,silent"
536
*/
537
public static void runHanoiProgramWithCache(String cachename,String extraSharedClassesOptions, String extraJavaOpt) {
538
// this hides the magic rule that due to the command construction, the "name=" is always the last part of the
539
// -Xshareclasses string in the defined commands. So to add more shared classes options we just have to append
540
// them to the cache name.
541
RunCommand.execute(getCommand(RunHanoiProgramWithCache,
542
cachename+(extraSharedClassesOptions!=null&&extraSharedClassesOptions.length()>0?","+extraSharedClassesOptions:""),
543
(extraJavaOpt!=null&&extraJavaOpt.length()>0?" "+extraJavaOpt:"")
544
));
545
checkOutputForDump(false);
546
}
547
548
protected static String getCacheFileLocationForNonPersistentCache(String cachename) {
549
String cacheDir = getCacheDir(cachename,false);
550
String expectedFileLocation =
551
cacheDir+File.separator+
552
getCacheFileName(cachename,false);
553
return expectedFileLocation;
554
}
555
protected static String getCacheFileDirectory(boolean forPersistentCache) {
556
String defaultLoc = getConfigParameter("defaultCacheLocation");
557
String cacheDirLoc = getConfigParameter("cacheDir");
558
String controlDirLoc=getConfigParameter("controlDir");
559
String theDir = null;
560
if (cacheDirLoc!=null) theDir = cacheDirLoc+(forPersistentCache?"":File.separator+"javasharedresources");
561
else if (controlDirLoc!=null) theDir = controlDirLoc+(forPersistentCache?"":File.separator+"javasharedresources");
562
else theDir = defaultLoc+File.separator+"javasharedresources";
563
return theDir;
564
}
565
566
protected static String getCacheFileLocationForPersistentCache(String cachename) {
567
String cacheDir = getCacheDir(cachename,true);
568
String expectedFileLocation =
569
cacheDir+File.separator+
570
getCacheFileName(cachename,true);
571
return expectedFileLocation;
572
}
573
574
protected static String getCacheFileLocationForCacheSnapshot(String cachename) {
575
String cacheDir = getCacheDir(cachename, false);
576
String expectedFileLocation =
577
cacheDir + File.separator +
578
getSnapshotFileName(cachename);
579
return expectedFileLocation;
580
}
581
582
public static void checkFileExists(String location) {
583
if (!new File(location).exists()) {
584
fail("No file found at '"+location+"'");
585
}
586
}
587
588
public static void checkFileDoesNotExist(String location) {
589
if (new File(location).exists()) {
590
fail("Did not expect to find file at '"+location+"'");
591
}
592
}
593
594
public static void fail(String msg) {
595
showOutput();
596
System.err.println(msg);
597
System.err.println("\tLast command: "+RunCommand.lastCommand);
598
throw new TestFailedException(msg);
599
}
600
601
private static String lastcmd_getCacheDir = "";
602
private static String lastresult_getCacheDir = "";
603
public static String getCacheDir(String cachename,boolean persistent)
604
{
605
//NOTE: use above statics to save some time when running tests ...
606
607
String cmd = "";
608
if ( false == isDefaultDirTmp() && cachename.indexOf("groupaccess") != -1 ) {
609
if (persistent==true)
610
{
611
cmd = getCommand("getCacheFileNameGroupAccess",cachename);
612
}
613
else
614
{
615
cmd = getCommand("getCacheFileNameNonPersistGroupAccess",cachename);
616
}
617
} else {
618
if (persistent==true)
619
{
620
cmd = getCommand("getCacheFileName",cachename);
621
}
622
else
623
{
624
cmd = getCommand("getCacheFileNameNonPersist",cachename);
625
}
626
}
627
628
if (lastcmd_getCacheDir.equals(cmd) && lastresult_getCacheDir.equals("")!=false)
629
{
630
return lastresult_getCacheDir;
631
}
632
lastcmd_getCacheDir=cmd;
633
634
RunCommand.execute(cmd,false);
635
String stderr = RunCommand.lastCommandStderr;
636
637
String[] stderrarray = stderr.split("\n");
638
639
for (int j=0; j<stderrarray.length;j+=1)
640
{
641
String test = stderrarray[j];
642
if (test.indexOf("/")==0 || test.indexOf(":\\")==1)
643
{
644
645
int i = test.lastIndexOf(java.io.File.separator);
646
if (i<1)
647
{
648
fail("Error: for cachename "+cachename+" not sure what happened but i is "+i);
649
return "";
650
}
651
String cacheDir = test.substring(0,i);//read just the dir
652
lastresult_getCacheDir = cacheDir;
653
return cacheDir;
654
}
655
}
656
fail("Error: should never hit this code.");
657
return "";
658
}
659
660
private static String lastcmd_getCacheFileName = "";
661
private static String lastresult_getCacheFileName = "";
662
public static String getCacheFileName(String cachename,boolean persistent) {
663
664
//NOTE: use above statics to save some time when running tests ...
665
666
String cmd = "";
667
668
if (persistent==true)
669
{
670
cmd = getCommand("getCacheFileName",cachename);
671
}
672
else
673
{
674
cmd = getCommand("getCacheFileNameNonPersist",cachename);
675
}
676
677
if (lastcmd_getCacheFileName.equals(cmd) && lastresult_getCacheFileName.equals("")!=false)
678
{
679
return lastresult_getCacheFileName;
680
}
681
lastcmd_getCacheFileName=cmd;
682
683
RunCommand.execute(cmd,false);
684
String stderr = RunCommand.lastCommandStderr;
685
686
String[] stderrarray = stderr.split("\n");
687
688
for (int j=0; j<stderrarray.length;j+=1)
689
{
690
String test = stderrarray[j];
691
if (test.indexOf("/")==0 || test.indexOf(":\\")==1)
692
{
693
int i = test.lastIndexOf(java.io.File.separator);
694
if (i>=test.length())
695
{
696
fail("Error: for cachename "+cachename+" not sure what happened but i is "+i);
697
return "";
698
}
699
String cachefile =test.substring(i+1,test.length());
700
//System.out.println("HERE(getCacheFileName):"+test+" "+cachefile);
701
lastresult_getCacheFileName = cachefile;
702
return cachefile;
703
}
704
}
705
fail("Error: should never hit this code.");
706
return "";
707
708
709
}
710
711
public static String getSnapshotFileName(String snapshotname) {
712
713
//NOTE: use above statics to save some time when running tests ...
714
715
String cmd = getCommand("getSnapshotFileName", snapshotname);
716
717
if (lastcmd_getCacheFileName.equals(cmd) && lastresult_getCacheFileName.equals("") != false) {
718
return lastresult_getCacheFileName;
719
}
720
lastcmd_getCacheFileName = cmd;
721
722
RunCommand.execute(cmd, false);
723
String stderr = RunCommand.lastCommandStderr;
724
725
String[] stderrarray = stderr.split("\n");
726
727
for (int j = 0; j < stderrarray.length; j += 1) {
728
String test = stderrarray[j];
729
if (test.indexOf("/") == 0 || test.indexOf(":\\") == 1) {
730
int i = test.lastIndexOf(java.io.File.separator);
731
if (i >= test.length()) {
732
fail("Error: for snapshotname " + snapshotname + " not sure what happened but i is " + i);
733
return "";
734
}
735
String snapshotfile = test.substring(i + 1, test.length());
736
lastresult_getCacheFileName = snapshotfile;
737
return snapshotfile;
738
}
739
}
740
fail("Error: should never hit this code.");
741
return "";
742
}
743
744
protected static String getConfigParameter(String string) {
745
return (String)config.get(string);
746
}
747
748
protected static void setConfigParameter(String key,String value) {
749
if (value==null) config.remove(key);
750
else config.put(key,value);
751
}
752
753
public static boolean destroyCache(String cachename) {
754
RunCommand.execute(getCommand(DestroyCacheCommand,cachename),false);
755
if (messageOccurred("JVMSHRC023E")) return false;
756
else return true;
757
}
758
759
public static boolean destroyPersistentCache(String cachename) {
760
RunCommand.execute(getCommand(DestroyPersistentCacheCommand,cachename),false);
761
if (messageOccurred("JVMSHRC023E")) return false;
762
else return true;
763
}
764
765
public static boolean destroyNonPersistentCache(String cachename) {
766
RunCommand.execute(getCommand(DestroyNonPersistentCacheCommand,cachename),false);
767
if (messageOccurred("JVMSHRC023E")) return false;
768
else return true;
769
}
770
771
public static boolean messageOccurred(String msgId) {
772
if (RunCommand.lastCommandStderr.indexOf(msgId)!=-1) return true;
773
if (RunCommand.lastCommandStdout.indexOf(msgId)!=-1) return true;
774
return false;
775
}
776
777
public static void showOutput() {
778
System.out.println("Command executed: '"+RunCommand.lastCommand+"'");
779
System.out.println("vvv STDOUT vvv");
780
System.out.println(RunCommand.lastCommandStdout);
781
System.out.println("^^^ STDOUT ^^^");
782
System.out.println("vvv STDERR vvv");
783
System.out.println(RunCommand.lastCommandStderr);
784
System.out.println("^^^ STDERR ^^^");
785
System.out.println("vvv STACK TRACE vvv");
786
new Throwable().printStackTrace(System.out);
787
System.out.println("^^^ STACK TRACE ^^^");
788
789
if (RunCommand.the2ndLastCommand != null) {
790
System.out.println("2nd last command executed: '"+RunCommand.the2ndLastCommand+"'");
791
System.out.println("vvv 2ND LAST STDOUT vvv");
792
System.out.println(RunCommand.the2ndLastCommandStdout);
793
System.out.println("^^^ 2ND LAST STDOUT ^^^");
794
System.out.println("vvv 2ND LAST STDERR vvv");
795
System.out.println(RunCommand.the2ndLastCommandStderr);
796
System.out.println("^^^ 2ND LAST STDERR ^^^");
797
}
798
}
799
800
public static void checkOutputContains(String regex,String explanation) {
801
String[] lines = RunCommand.lastCommandStderrLines;
802
boolean found = false;
803
if (lines!=null) {
804
for (int i = 0; i < lines.length; i++) {
805
if (lines[i].matches("^.*"+regex+".*$")) {
806
// System.out.println("this line '"+lines[i]+"' matches "+regex);
807
found=true;
808
break;
809
}
810
}
811
}
812
if (!found) {
813
// check stdout
814
lines = RunCommand.lastCommandStdoutLines;
815
found = false;
816
if (lines!=null) {
817
for (int i = 0; i < lines.length; i++) {
818
if (lines[i].matches("^.*"+regex+".*$")) {
819
// System.out.println("this line '"+lines[i]+"' matches "+regex);
820
found=true;
821
}
822
}
823
}
824
}
825
if (!found) {
826
fail(explanation);
827
}
828
}
829
public static void checkOutputDoesNotContain(String regex,String explanation) {
830
String[] lines = RunCommand.lastCommandStderrLines;
831
boolean isFound = false;
832
if (lines!=null) {
833
for (int i = 0; i < lines.length; i++) {
834
if (lines[i].matches("^.*"+regex+".*$")) {
835
// System.out.println("this line '"+lines[i]+"' matches "+regex);
836
isFound=true;
837
}
838
}
839
}
840
if (isFound) {
841
fail(explanation);
842
}
843
}
844
845
public static void checkForMessage(String msgid, String explanation) {
846
if (!messageOccurred(msgid)) {
847
fail(explanation);
848
}
849
}
850
public static void checkNoFileForPersistentCache(String cachename) {
851
checkFileDoesNotExist(getCacheFileLocationForPersistentCache(cachename));
852
}
853
//TODO isnt this the same as that other method below?
854
public static void checkNoFileForNonPersistentCache(String cachename) {
855
if (isWindows()) {
856
checkFileDoesNotExist(getCacheFileLocationForNonPersistentCache(cachename));
857
} else { checkFileDoesNotExist(getCacheFileLocationForNonPersistentCache(cachename));
858
checkFileDoesNotExist(getCacheFileLocationForNonPersistentCache(cachename).replace("memory","semaphore"));
859
}
860
}
861
862
public static void checkFileDoesNotExistForPersistentCache(String cachename) {
863
checkFileDoesNotExist(getCacheFileLocationForPersistentCache(cachename));
864
}
865
866
public static void checkFileDoesNotExistForCacheSnapshot(String cachename) {
867
checkFileDoesNotExist(getCacheFileLocationForCacheSnapshot(cachename));
868
}
869
870
public static void checkFileDoesNotExistForNonPersistentCache(String cachename) {
871
if (isWindows()) {
872
checkFileDoesNotExist(getCacheFileLocationForNonPersistentCache(cachename));
873
} else {
874
checkFileDoesNotExist(getCacheFileLocationForNonPersistentCache(cachename));
875
checkFileDoesNotExist(getCacheFileLocationForNonPersistentCache(cachename).replace("memory","semaphore"));
876
}
877
}
878
879
public static void checkFileExistsForPersistentCache(String cachename) {
880
checkFileExists(getCacheFileLocationForPersistentCache(cachename));
881
}
882
883
public static void checkFileExistsForNonPersistentCache(String cachename) {
884
Properties p = System.getProperties();
885
if (isWindows()) {
886
checkFileExists(getCacheFileLocationForNonPersistentCache(cachename));
887
} else {
888
// linux is harder, there is a memory file and a semaphore file to worry about
889
checkFileExists(getCacheFileLocationForNonPersistentCache(cachename));
890
checkFileExists(getCacheFileLocationForNonPersistentCache(cachename).replace("memory","semaphore"));
891
}
892
}
893
894
public static void checkFileExistsForCacheSnapshot(String cachename) {
895
checkFileExists(getCacheFileLocationForCacheSnapshot(cachename));
896
}
897
898
899
public static boolean isWindows() {
900
return System.getProperty("os.name").toLowerCase().startsWith("windows");
901
}
902
903
public static boolean isMVS() {
904
return System.getProperty("os.name").toLowerCase().startsWith("z/os");
905
}
906
907
public static boolean isLinux() {
908
return System.getProperty("os.name").toLowerCase().startsWith("linux");
909
}
910
911
public static String getOS() {
912
return System.getProperty("os.name");
913
}
914
915
public static boolean isCompressedRefEnabled() {
916
checkJavaVersion();
917
if (messageOccurred("Compressed References")) {
918
return true;
919
} else {
920
return false;
921
}
922
}
923
924
public static void checkForSuccessfulPersistentCacheOpenMessage(
925
String cachename) {
926
checkOutputContains("JVMSHRC237I.*" + cachename,
927
"Did not get expected message about successful cache open");
928
}
929
930
public static void checkForSuccessfulPersistentCacheCreationMessage(
931
String cachename) {
932
checkOutputContains("JVMSHRC236I.*" + cachename,
933
"Did not get expected message about successful cache creation");
934
}
935
936
public static void checkForSuccessfulPersistentCacheDestroyMessage(
937
String cachename) {
938
checkOutputContains(cachename + ".*has been destroyed",
939
"Did not get expected message about successful cache destroy");
940
}
941
942
public static void checkForSuccessfulNonPersistentCacheOpenMessage(
943
String cachename) {
944
checkOutputContains("JVMSHRC159I.*" + cachename,
945
"Did not get expected message about successful cache open");
946
}
947
948
public static void checkForSuccessfulNonPersistentCacheCreationMessage(
949
String cachename) {
950
checkOutputContains("JVMSHRC158I.*" + cachename,
951
"Did not get expected message about successful cache creation");
952
}
953
954
public static void checkForSuccessfulNonPersistentCacheDestoryMessage(
955
String cachename) {
956
checkOutputContains(cachename + ".*is destroyed",
957
"Did not get expected message about successful cache destroy");
958
}
959
960
public static void checkOutputForCompatiblePersistentCache(String cachename,boolean shouldBeFound) {
961
checkOutputForCompatibleCache(cachename, true, shouldBeFound);
962
}
963
964
public static void checkOutputForCompatibleNonPersistentCache(String cachename,boolean shouldBeFound) {
965
checkOutputForCompatibleCache(cachename, false, shouldBeFound);
966
}
967
968
/**
969
* In the most recent command output (RunCommand.lastCommandStderrLines) this method checks for
970
* the named cache in the 'Incompatible caches' section. The flag shouldBeFound indicates whether
971
* it should be named in the section.
972
*/
973
public static void checkOutputForIncompatibleCache(String name,boolean shouldBeFound) {
974
String[] lines = RunCommand.lastCommandStderrLines;
975
boolean isFound = false;
976
if (lines!=null) {
977
int i=0;
978
boolean inCompatSection = false;
979
while (i<lines.length) {
980
if (inCompatSection) {
981
// Ok, this might be our entry
982
if (lines[i].matches(name+"[ \\t].*$")) {
983
isFound=true;
984
}
985
}
986
if (lines[i].startsWith("Incompatible")) inCompatSection=true;
987
if (lines[i].trim().equals("")) inCompatSection=false;
988
i++;
989
}
990
}
991
if (shouldBeFound) {
992
if (!isFound) {
993
fail("Cache '"+name+"' was not found to be incompatible");
994
}
995
} else {
996
if (isFound) {
997
fail("Cache '"+name+"' was unexpectedly found to be incompatible");
998
}
999
}
1000
}
1001
1002
1003
1004
public static void checkOutputForCompatibleCache(String name, boolean isPersistent,boolean shouldBeFound) {
1005
String[] lines = RunCommand.lastCommandStderrLines;
1006
boolean isFound = false;
1007
if (lines!=null) {
1008
int i=0;
1009
boolean inCompatSection = false;
1010
while (i<lines.length) {
1011
if (inCompatSection) {
1012
// Ok, this might be our entry
1013
if (lines[i].matches(name+".*"+(isPersistent?"(yes|persistent)":"(no|non-persistent)")+".*$")) {
1014
isFound=true;
1015
}
1016
}
1017
if (lines[i].startsWith("Compatible")) inCompatSection=true;
1018
if (lines[i].trim().equals("")) inCompatSection=false;
1019
i++;
1020
}
1021
}
1022
if (shouldBeFound) {
1023
if (!isFound) {
1024
fail((isPersistent?"":"Non-")+"Persistent cache '"+name+"' was not found to be compatible");
1025
}
1026
} else {
1027
if (isFound) {
1028
fail((isPersistent?"":"Non-")+"Persistent cache '"+name+"' was unexpectedly found to be compatible");
1029
}
1030
}
1031
}
1032
1033
public static List processOutputForCompatibleCacheList() {
1034
List compatibleCaches = new ArrayList();
1035
String[] lines = RunCommand.lastCommandStderrLines;
1036
if (lines!=null) {
1037
int i=0;
1038
boolean inCompatSection = false;
1039
while (i<lines.length) {
1040
if (inCompatSection) {
1041
// Chop from position 0 to the first non-space or tab
1042
// System.out.println(">>>"+lines[i]+"<<<");
1043
if (lines[i].length()!=0) { // this will avoid including the final line of compatible section
1044
int p=0; while (p<lines[i].length() && lines[i].charAt(p)!=' ' && lines[i].charAt(p)!='\t') p++;
1045
compatibleCaches.add(lines[i].substring(0,p));
1046
}
1047
}
1048
if (lines[i].startsWith("Compatible")) inCompatSection=true;
1049
if (lines[i].trim().equals("")) {
1050
inCompatSection=false;
1051
}
1052
i++;
1053
}
1054
}
1055
return compatibleCaches;
1056
}
1057
1058
public static void deleteTemporaryDirectory(String path) {
1059
File f = new File(path);
1060
if (f.exists()) {
1061
File[] files = f.listFiles();
1062
for (int i = 0; i < files.length; i++) {
1063
if (files[i].isDirectory()) {
1064
deleteTemporaryDirectory((files[i]).getAbsolutePath());
1065
} else {
1066
files[i].delete();
1067
if (files[i].exists()) {
1068
fail("Couldn't delete temp file " + files[i].getAbsolutePath());
1069
}
1070
}
1071
}
1072
f.delete();
1073
}
1074
if (f.exists()) {
1075
fail("Couldn't delete temp dir " + f.getAbsolutePath());
1076
}
1077
//System.out.println("Deleted Tmp Folder: " + f.getAbsolutePath());
1078
}
1079
1080
public static String createTemporaryDirectory(String testname) {
1081
try {
1082
File f = File.createTempFile("testSC"+testname,"dir");
1083
1084
//System.out.println("Created Tmp Folder: "+f.getAbsolutePath());
1085
1086
if (!f.delete()) fail("Couldn't create the temp dir");
1087
if (!f.mkdir()) fail("Couldnt create the temp dir");
1088
return f.getAbsolutePath();
1089
} catch (IOException e) {
1090
fail("Couldnt create temp dir: "+e);
1091
return null;
1092
}
1093
}
1094
1095
/**
1096
* Create some caches that are generation 07 and 01
1097
*/
1098
protected static void createGenerations01() {
1099
log("Creating cache generations...");
1100
createPersistentCache("Foo"); createPersistentCache("Bar");
1101
createNonPersistentCache("Foo");createNonPersistentCache("Bar");
1102
renameGenerations("G07","G01"); // rename generation 03 files to generation 02
1103
createPersistentCache("Foo"); createPersistentCache("Bar");
1104
createNonPersistentCache("Foo");createNonPersistentCache("Bar");
1105
}
1106
public static void log(String s) {
1107
if (debug) System.out.println(s);
1108
}
1109
1110
/**
1111
* Create some caches that are generation 03 and 02
1112
*/
1113
protected static void createGenerations02() {
1114
createPersistentCache("Foo"); createPersistentCache("Bar");
1115
createNonPersistentCache("Foo");createNonPersistentCache("Bar");
1116
renameGenerations("G07","G02"); // rename generation 03 files to generation 01
1117
1118
createPersistentCache("Foo"); createPersistentCache("Bar");
1119
createNonPersistentCache("Foo");createNonPersistentCache("Bar");
1120
1121
}
1122
1123
public static void renameGenerations(String from, String to) {
1124
renameGeneration("Foo",true,from,to);
1125
renameGeneration("Bar",true,from,to);
1126
renameGeneration("Foo",false,from,to);
1127
renameGeneration("Bar",false,from,to);
1128
}
1129
1130
/**
1131
* Passed a generation number like 'G07', it will change that to 'to' (eg. G02).
1132
*/
1133
public static void renameGeneration(String name, boolean isPersistent,
1134
String from, String to) {
1135
log("Changing generation numbers for "+(isPersistent?"":"non-")+"persistent cache '"+name+"' from "+from+" to "+to);
1136
if (isWindows() || isPersistent) {
1137
String cachefilename = getCacheFileName(name, isPersistent); // TODO null will need fixing for linux and non-persistent caches
1138
1139
String expectedFileLocation = null;
1140
if (isPersistent) {
1141
expectedFileLocation = getCacheFileLocationForPersistentCache(name);
1142
} else {
1143
expectedFileLocation = getCacheFileLocationForNonPersistentCache(name);
1144
}
1145
1146
// String expectedFileLocation =
1147
// getConfigParameter("defaultCacheLocation")+File.separator+
1148
// "javasharedresources"+File.separator+cachefilename;
1149
1150
File currentCache = new File(expectedFileLocation);
1151
if (!currentCache.exists()) {
1152
fail("Unexpectedly couldn't find cache file: "+expectedFileLocation);
1153
}
1154
1155
if (expectedFileLocation.endsWith(from)) {
1156
String newLocation = expectedFileLocation.substring(0,expectedFileLocation.length()-from.length())+to;
1157
if (!currentCache.renameTo(new File(newLocation))) {
1158
fail("Could not rename from '"+expectedFileLocation+"' to '"+newLocation+"'");
1159
}
1160
}
1161
} else {
1162
// non-persistent caches on non-windows have two control files
1163
String locMemory = getCacheFileLocationForNonPersistentCache(name);
1164
File f = new File(locMemory);
1165
if (!f.exists()) fail("Unexpectedly couldn't find cache file: "+locMemory);
1166
if (locMemory.endsWith(from)) {
1167
String newLocation = locMemory.substring(0,locMemory.length()-from.length())+to;
1168
if (!f.renameTo(new File(newLocation))) {
1169
fail("Could not rename from '"+locMemory+"' to '"+newLocation+"'");
1170
}
1171
}
1172
String locSemaphore = getCacheFileLocationForNonPersistentCache(name).replace("memory","semaphore");
1173
f = new File(locSemaphore);
1174
if (!f.exists()) fail("Unexpectedly couldn't find cache file: "+locSemaphore);
1175
if (locSemaphore.endsWith(from)) {
1176
String newLocation = null;
1177
if (to.equals("G01") || to.equals("G02")) {
1178
// semaphore doesnt have generation number on for gen1/2
1179
newLocation = locSemaphore.substring(0,locSemaphore.length()-from.length()-1);
1180
} else {
1181
newLocation = locSemaphore.substring(0,locSemaphore.length()-from.length())+to;
1182
}
1183
if (!f.renameTo(new File(newLocation))) {
1184
fail("Could not rename from '"+locSemaphore+"' to '"+newLocation+"'");
1185
}
1186
}
1187
}
1188
}
1189
//
1190
// public void touchFiles(String listForTouching) {
1191
//
1192
// if (listForTouching.length()==0) return;
1193
// StringTokenizer st = new StringTokenizer(listForTouching,",");
1194
// try { Thread.sleep(1000); } catch (Exception e) {} // allow for filesystem with crap resolution timer
1195
// while (st.hasMoreTokens()) {
1196
// String touch = st.nextToken();
1197
// File f = new File(touch);
1198
// f.r
1199
// if (!f.exists()) throw new RuntimeException("Can't find: "+touch);
1200
// boolean b = f.setLastModified(System.currentTimeMillis());
1201
// log("Touched: "+f+" : "+(b?"successful":"unsuccessful"));
1202
// }
1203
// }
1204
1205
public static void corruptCache(String cachename, boolean isPersistent, String howToCorruptIt) {
1206
String theFile = (isPersistent?getCacheFileLocationForPersistentCache(cachename):
1207
getCacheFileLocationForNonPersistentCache(cachename));
1208
1209
//if (!isPersistent && !isWindows()) {
1210
// System.out.println("corruptCache is not implemented on this target");
1211
// return;
1212
//}
1213
1214
if (howToCorruptIt.equals("truncate")) {
1215
1216
File f = new File(theFile);
1217
File fNew = new File(theFile+".tmp");
1218
// chop it to 1000 bytes
1219
int i =0;
1220
byte[] buff = new byte[1000];
1221
try {
1222
FileInputStream fis = new FileInputStream(f);
1223
FileOutputStream fos = new FileOutputStream(fNew);
1224
while (i<10000) {
1225
int read = fis.read(buff);
1226
if (read>0)
1227
{
1228
i+=read;
1229
fos.write(buff,0,read);
1230
}
1231
else
1232
{
1233
fail("Could not create the fake corrupt file.");
1234
break;
1235
}
1236
}
1237
fos.flush();
1238
fos.close();
1239
fis.close();
1240
if (!f.delete()) fail("Failed to delete existing cache");
1241
if (!fNew.renameTo(f)) fail("Could not rename new truncated cache");
1242
} catch (Exception e) {
1243
fail("Cannot truncate file "+e);
1244
}
1245
} else if (howToCorruptIt.equals("ftpascii")) {
1246
File f = new File(theFile);
1247
File fNew = new File(theFile+".tmp");
1248
// chop it to 10000 bytes
1249
int i =0;
1250
byte[] buff = new byte[1000];
1251
try {
1252
FileInputStream fis = new FileInputStream(f);
1253
FileOutputStream fos = new FileOutputStream(fNew);
1254
int read=1;
1255
while (true && read>0) {
1256
read = fis.read(buff);
1257
i+=read;
1258
byte b = 0x7f;
1259
if (read>-1) {
1260
for (int j=0;j<read;j++) {
1261
buff[j]=(byte)(buff[j]&b);
1262
}
1263
fos.write(buff,0,read);
1264
}
1265
}
1266
fos.flush();fos.close();
1267
fis.close();
1268
// System.out.println("Copied "+i+" bytes");
1269
if (!f.delete()) fail("Failed to delete existing cache");
1270
if (!fNew.renameTo(f)) fail("Could not rename new ftpascii cache");
1271
} catch (Exception e) {
1272
e.printStackTrace();
1273
fail("Cannot ftpascii file "+e);
1274
}
1275
} else if (howToCorruptIt.equals("zero")) {
1276
File f = new File(theFile);
1277
File fNew = new File(theFile+".tmp");
1278
byte[] buff = new byte[1000];
1279
try {
1280
FileInputStream fis = new FileInputStream(f);
1281
FileOutputStream fos = new FileOutputStream(fNew);
1282
int read=1;
1283
int blocksToZero = 200;
1284
int offsetForZero=5000;
1285
boolean corrupted=false;
1286
1287
if (realtimeTestsSelected()){
1288
offsetForZero=100000;
1289
}
1290
1291
while (read > 0) {
1292
read = fis.read(buff);
1293
offsetForZero-=read;
1294
if (read > -1) {
1295
if (offsetForZero<=0 && !corrupted) {
1296
if ((blocksToZero--)<0) {
1297
corrupted=true;
1298
}
1299
for (int j=0;j<read;j++) {
1300
buff[j]=0;
1301
}
1302
}
1303
fos.write(buff,0,read);
1304
}
1305
}
1306
fos.flush();fos.close();
1307
fis.close();
1308
if (!f.delete()) fail("Failed to delete existing cache");
1309
if (!fNew.renameTo(f)) fail("Could not rename new zerod cache");
1310
} catch (Exception e) {
1311
e.printStackTrace();
1312
fail("Cannot zero file "+e);
1313
}
1314
} else if (howToCorruptIt.equals("zeroStringCache")) {
1315
File f = new File(theFile);
1316
File fNew = new File(theFile+".tmp");
1317
byte[] buff = new byte[1000];
1318
try {
1319
FileInputStream fis = new FileInputStream(f);
1320
FileOutputStream fos = new FileOutputStream(fNew);
1321
int read=1;
1322
int blocksToZero = 3;
1323
int offsetForZero=2000;
1324
boolean corrupted=false;
1325
1326
while (read > 0) {
1327
read = fis.read(buff);
1328
offsetForZero-=read;
1329
if (read > -1) {
1330
if (offsetForZero<=0 && !corrupted) {
1331
if ((blocksToZero--)<0) {
1332
corrupted=true;
1333
}
1334
for (int j=0;j<read;j++) {
1335
buff[j]=0;
1336
}
1337
}
1338
fos.write(buff,0,read);
1339
}
1340
}
1341
fos.flush();fos.close();
1342
fis.close();
1343
if (!f.delete()) fail("Failed to delete existing cache");
1344
if (!fNew.renameTo(f)) fail("Could not rename new zeroStringCache cache");
1345
} catch (Exception e) {
1346
e.printStackTrace();
1347
fail("Cannot zeroStringCache file "+e);
1348
}
1349
} else if (howToCorruptIt.equals("zeroFirstPage")) {
1350
File f = new File(theFile);
1351
File fNew = new File(theFile+".tmp");
1352
byte[] buff = new byte[1024];
1353
try {
1354
FileInputStream fis = new FileInputStream(f);
1355
FileOutputStream fos = new FileOutputStream(fNew);
1356
int read=1;
1357
boolean corrupted=false;
1358
1359
while (read > 0) {
1360
read = fis.read(buff);
1361
if (read > -1) {
1362
if (!corrupted) {
1363
for (int j=0;j<read;j++) {
1364
buff[j]=0;
1365
}
1366
corrupted = true;
1367
}
1368
fos.write(buff,0,read);
1369
}
1370
}
1371
fos.flush();fos.close();
1372
fis.close();
1373
if (!f.delete()) fail("Failed to delete existing cache");
1374
if (!fNew.renameTo(f)) fail("Could not rename new zerod cache");
1375
} catch (Exception e) {
1376
e.printStackTrace();
1377
fail("Cannot zero file "+e);
1378
}
1379
}
1380
}
1381
1382
protected static boolean copyFile(File from,File to) {
1383
int i =0;
1384
byte[] buff = new byte[1000];
1385
try {
1386
FileInputStream fis = new FileInputStream(from);
1387
FileOutputStream fos = new FileOutputStream(to);
1388
int read=1;
1389
while (true && read>0) {
1390
read = fis.read(buff);
1391
i+=read;
1392
if (read>-1) fos.write(buff,0,read);
1393
}
1394
fos.flush();fos.close();
1395
fis.close();
1396
// System.out.println("Copied "+i+" bytes from "+from+" to "+to);
1397
} catch (Exception e) {
1398
fail("Cannot copy file '"+from+"' "+e);
1399
}
1400
return true;
1401
}
1402
public static void moveControlFilesForNonPersistentCache(String name,
1403
String whereFrom, String whereTo) {
1404
if (isWindows()) {
1405
File f = new File(whereFrom+File.separator+getCacheFileName(name,false));
1406
File fNew = new File(whereTo+File.separator+getCacheFileName(name, false));
1407
if (!f.renameTo(fNew)) fail("Could not rename the control file");
1408
} else {
1409
File f = new File(whereFrom+File.separator+getCacheFileName(name,false));
1410
File fNew = new File(whereTo+File.separator+getCacheFileName(name, false));
1411
if (!f.renameTo(fNew)) fail("Could not rename the memory file from "+f.getAbsolutePath()+" to "+fNew.getAbsolutePath());
1412
1413
f = new File(whereFrom+File.separator+getCacheFileName(name,false).replace("memory", "semaphore"));
1414
fNew = new File(whereTo+File.separator+getCacheFileName(name, false).replace("memory", "semaphore"));
1415
if (!f.renameTo(fNew)) fail("Could not rename the semaphore file from "+f.getAbsolutePath()+" to "+fNew.getAbsolutePath());
1416
}
1417
}
1418
public static Set getSharedMemorySegments() {
1419
Set shmSegments = new HashSet();
1420
RunCommand.execute("ipcs");
1421
String[] lines = RunCommand.lastCommandStdoutLines;
1422
if (lines!=null) {
1423
int i=0;
1424
boolean inSharedMemorySegmentSection = false;
1425
while (i<lines.length) {
1426
if (inSharedMemorySegmentSection) {
1427
if (lines[i].startsWith("0x")) {
1428
String shm = lines[i].substring(11,21).trim();
1429
// System.out.println("From line '"+lines[i]+"' we have "+shm);
1430
shmSegments.add(shm);
1431
}
1432
}
1433
if (lines[i].indexOf("Shared Memory Segments")!=-1) inSharedMemorySegmentSection=true;
1434
if (lines[i].trim().equals("")) inSharedMemorySegmentSection=false;
1435
i++;
1436
}
1437
}
1438
return shmSegments;
1439
}
1440
public static Set getSharedSemaphores() {
1441
Set shmSegments = new HashSet();
1442
RunCommand.execute("ipcs");
1443
String[] lines = RunCommand.lastCommandStdoutLines;
1444
if (lines!=null) {
1445
int i=0;
1446
boolean inSharedSemaphoresSection = false;
1447
while (i<lines.length) {
1448
if (inSharedSemaphoresSection) {
1449
if (lines[i].startsWith("0x")) {
1450
String sem = lines[i].substring(11,21).trim();
1451
// System.out.println("From line '"+lines[i]+"' we have "+sem);
1452
shmSegments.add(sem);
1453
}
1454
}
1455
if (lines[i].indexOf("Semaphore Arrays")!=-1) inSharedSemaphoresSection=true;
1456
if (lines[i].trim().equals("")) inSharedSemaphoresSection=false;
1457
i++;
1458
}
1459
}
1460
return shmSegments;
1461
}
1462
1463
public static boolean removeSemaphoreForCache(String cacheName) {
1464
StringBuffer removeSemCmd = new StringBuffer("ipcrm -s ");
1465
String semid = null;
1466
RunCommand.execute(getCommand(ListAllCaches), false);
1467
String[] lines = RunCommand.lastCommandStderrLines;
1468
for (int i = 0; i < lines.length; i++) {
1469
if (lines[i].startsWith(cacheName)) {
1470
String token[] = lines[i].split("(\\s)+");
1471
/* verify cache name */
1472
if (token[0].trim().equals(cacheName) == false) {
1473
continue;
1474
}
1475
/* verify non-persistent cache */
1476
if ((token[3].trim().equals("no") == false) && (token[3].trim().equals("non-persistent") == false)) {
1477
continue;
1478
}
1479
/* get semaphore */
1480
semid = token[7].trim();
1481
}
1482
}
1483
1484
if (semid != null) {
1485
removeSemCmd.append(semid);
1486
RunCommand.execute(removeSemCmd.toString());
1487
return true;
1488
} else {
1489
return false;
1490
}
1491
}
1492
1493
public static boolean removeSharedMemoryForCache(String cacheName) {
1494
StringBuffer removeShmCmd = new StringBuffer("ipcrm -m ");
1495
String shmid = null;
1496
RunCommand.execute(getCommand(ListAllCaches), false);
1497
String[] lines = RunCommand.lastCommandStderrLines;
1498
for (int i = 0; i < lines.length; i++) {
1499
if (lines[i].startsWith(cacheName)) {
1500
String token[] = lines[i].split("(\\s)+");
1501
/* verify cache name */
1502
if (token[0].trim().equals(cacheName) == false) {
1503
continue;
1504
}
1505
/* verify non-persistent cache */
1506
if ((token[3].trim().equals("no") == false) && (token[3].trim().equals("non-persistent") == false)) {
1507
continue;
1508
}
1509
/* get shared memory */
1510
shmid = token[6].trim();
1511
}
1512
1513
}
1514
if (shmid != null) {
1515
removeShmCmd.append(shmid);
1516
RunCommand.execute(removeShmCmd.toString());
1517
return true;
1518
} else {
1519
return false;
1520
}
1521
}
1522
1523
public static String[] getLastCommandStdout() {
1524
return RunCommand.lastCommandStdoutLines;
1525
}
1526
1527
public static String[] getLastCommandStderr() {
1528
return RunCommand.lastCommandStderrLines;
1529
}
1530
1531
public static boolean isDefaultDirTmp() {
1532
// ibm 11+ has the same -DOPENJ9_BUILD as openj9
1533
return System.getProperty("java.vm.vendor").toLowerCase().contains("ibm") && System.getProperty("java.specification.version").contains("1.8") || isMVS();
1534
}
1535
1536
public static String removeJavaSharedResourcesDir(String dir) {
1537
if (dir != null && dir.length() > 0) {
1538
String tempDir = dir;
1539
if (tempDir.endsWith(java.io.File.separator)) {
1540
tempDir = tempDir.substring(0, dir.length() - 1);
1541
}
1542
if (tempDir.endsWith(java.io.File.separator + "javasharedresources")) {
1543
int index = tempDir.lastIndexOf(java.io.File.separator);
1544
return tempDir.substring(0, index);
1545
}
1546
return dir;
1547
}
1548
fail("Error: should never hit this code, directory " + dir + " is not correct.");
1549
return "";
1550
}
1551
}
1552
1553