1 /*
   2  * Copyright (c) 2014, 2017, Oracle and/or its affiliates. All rights reserved.
   3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   4  *
   5  * This code is free software; you can redistribute it and/or modify it
   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.
   8  *
   9  * This code is distributed in the hope that it will be useful, but WITHOUT
  10  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  11  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  12  * version 2 for more details (a copy is included in the LICENSE file that
  13  * accompanied this code).
  14  *
  15  * You should have received a copy of the GNU General Public License version
  16  * 2 along with this work; if not, write to the Free Software Foundation,
  17  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  18  *
  19  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  20  * or visit www.oracle.com if you need additional information or have any
  21  * questions.
  22  *
  23  */
  24 
  25 import jdk.test.lib.Utils;
  26 import jdk.test.lib.JDKToolFinder;
  27 import jdk.test.lib.Platform;
  28 import jdk.test.lib.cds.CDSOptions;
  29 import jdk.test.lib.cds.CDSTestUtils;
  30 import jdk.test.lib.process.ProcessTools;
  31 import jdk.test.lib.process.OutputAnalyzer;
  32 import java.io.File;
  33 import java.text.SimpleDateFormat;
  34 import java.util.ArrayList;
  35 import java.util.Date;
  36 
  37 /**
  38  * This is a test utility class for common AppCDS test functionality.
  39  *
  40  * Various methods use (String ...) for passing VM options. Note that the order
  41  * of the VM options are important in certain cases. Many methods take arguments like
  42  *
  43  *    (String prefix[], String suffix[], String... opts)
  44  *
  45  * Note that the order of the VM options is:
  46  *
  47  *    prefix + opts + suffix
  48  */
  49 public class TestCommon extends CDSTestUtils {
  50     private static final String JSA_FILE_PREFIX = System.getProperty("user.dir") +
  51         File.separator + "appcds-";
  52 
  53     private static final SimpleDateFormat timeStampFormat =
  54         new SimpleDateFormat("HH'h'mm'm'ss's'SSS");
  55 
  56     private static final String timeoutFactor =
  57         System.getProperty("test.timeout.factor", "1.0");
  58 
  59     private static String currentArchiveName;
  60 
  61     // Call this method to start new archive with new unique name
  62     public static void startNewArchiveName() {
  63         deletePriorArchives();
  64         currentArchiveName = JSA_FILE_PREFIX +
  65             timeStampFormat.format(new Date()) + ".jsa";
  66     }
  67 
  68     // Call this method to get current archive name
  69     public static String getCurrentArchiveName() {
  70         return currentArchiveName;
  71     }
  72 
  73     // Attempt to clean old archives to preserve space
  74     // Archives are large artifacts (20Mb or more), and much larger than
  75     // most other artifacts created in jtreg testing.
  76     // Therefore it is a good idea to clean the old archives when they are not needed.
  77     // In most cases the deletion attempt will succeed; on rare occasion the
  78     // delete operation will fail since the system or VM process still holds a handle
  79     // to the file; in such cases the File.delete() operation will silently fail, w/o
  80     // throwing an exception, thus allowing testing to continue.
  81     public static void deletePriorArchives() {
  82         File dir = new File(System.getProperty("user.dir"));
  83         String files[] = dir.list();
  84         for (String name : files) {
  85             if (name.startsWith("appcds-") && name.endsWith(".jsa")) {
  86                 if (!(new File(dir, name)).delete())
  87                     System.out.println("deletePriorArchives(): delete failed for file " + name);
  88             }
  89         }
  90     }
  91 
  92 
  93     // Create AppCDS archive using most common args - convenience method
  94     // Legacy name preserved for compatibility
  95     public static OutputAnalyzer dump(String appJar, String appClasses[],
  96                                                String... suffix) throws Exception {
  97         return createArchive(appJar, appClasses, suffix);
  98     }
  99 
 100 
 101     // Create AppCDS archive using most common args - convenience method
 102     public static OutputAnalyzer createArchive(String appJar, String appClasses[],
 103                                                String... suffix) throws Exception {
 104         AppCDSOptions opts = (new AppCDSOptions()).setAppJar(appJar)
 105             .setAppClasses(appClasses);
 106         opts.addSuffix(suffix);
 107         return createArchive(opts);
 108     }
 109 
 110 
 111     // Create AppCDS archive using appcds options
 112     public static OutputAnalyzer createArchive(AppCDSOptions opts)
 113         throws Exception {
 114 
 115         ArrayList<String> cmd = new ArrayList<String>();
 116         File classList = makeClassList(opts.appClasses);
 117         startNewArchiveName();
 118 
 119         for (String p : opts.prefix) cmd.add(p);
 120 
 121         if (opts.appJar != null) {
 122             cmd.add("-cp");
 123             cmd.add(opts.appJar);
 124         } else {
 125             cmd.add("-cp");
 126             cmd.add("\"\"");
 127         }
 128 
 129         cmd.add("-Xshare:dump");
 130         cmd.add("-Xlog:cds,cds+hashtables");
 131         cmd.add("-XX:+UseAppCDS");
 132         cmd.add("-XX:ExtraSharedClassListFile=" + classList.getPath());
 133 
 134         if (opts.archiveName == null)
 135             opts.archiveName = getCurrentArchiveName();
 136 
 137         cmd.add("-XX:SharedArchiveFile=" + opts.archiveName);
 138 
 139         for (String s : opts.suffix) cmd.add(s);
 140 
 141         String[] cmdLine = cmd.toArray(new String[cmd.size()]);
 142         ProcessBuilder pb = ProcessTools.createJavaProcessBuilder(true, cmdLine);
 143         return executeAndLog(pb, "dump");
 144     }
 145 
 146 
 147     // Execute JVM using AppCDS archive with specified AppCDSOptions
 148     public static OutputAnalyzer runWithArchive(AppCDSOptions opts)
 149         throws Exception {
 150 
 151         ArrayList<String> cmd = new ArrayList<String>();
 152 
 153         for (String p : opts.prefix) cmd.add(p);
 154 
 155         cmd.add("-Xshare:" + opts.xShareMode);
 156         cmd.add("-XX:+UseAppCDS");
 157         cmd.add("-showversion");
 158         cmd.add("-XX:SharedArchiveFile=" + getCurrentArchiveName());
 159         cmd.add("-Dtest.timeout.factor=" + timeoutFactor);
 160 
 161         if (opts.appJar != null) {
 162             cmd.add("-cp");
 163             cmd.add(opts.appJar);
 164         }
 165 
 166         for (String s : opts.suffix) cmd.add(s);
 167 
 168         String[] cmdLine = cmd.toArray(new String[cmd.size()]);
 169         ProcessBuilder pb = ProcessTools.createJavaProcessBuilder(true, cmdLine);
 170         return executeAndLog(pb, "exec");
 171     }
 172 
 173 
 174     public static OutputAnalyzer execCommon(String... suffix) throws Exception {
 175         AppCDSOptions opts = (new AppCDSOptions());
 176         opts.addSuffix(suffix);
 177         return runWithArchive(opts);
 178     }
 179 
 180 
 181     public static OutputAnalyzer exec(String appJar, String... suffix) throws Exception {
 182         AppCDSOptions opts = (new AppCDSOptions()).setAppJar(appJar);
 183         opts.addSuffix(suffix);
 184         return runWithArchive(opts);
 185     }
 186 
 187 
 188     public static OutputAnalyzer execAuto(String... suffix) throws Exception {
 189         AppCDSOptions opts = (new AppCDSOptions());
 190         opts.addSuffix(suffix).setXShareMode("auto");
 191         return runWithArchive(opts);
 192     }
 193 
 194     public static OutputAnalyzer execOff(String... suffix) throws Exception {
 195         AppCDSOptions opts = (new AppCDSOptions());
 196         opts.addSuffix(suffix).setXShareMode("off");
 197         return runWithArchive(opts);
 198     }
 199 
 200     public static OutputAnalyzer execModule(String prefix[], String upgrademodulepath, String modulepath,
 201                                             String mid, String... testClassArgs)
 202         throws Exception {
 203 
 204         AppCDSOptions opts = (new AppCDSOptions());
 205 
 206         opts.addPrefix(prefix);
 207         if (upgrademodulepath == null) {
 208             opts.addSuffix("-p", modulepath, "-m", mid);
 209         } else {
 210             opts.addSuffix("--upgrade-module-path", upgrademodulepath,
 211                            "-p", modulepath, "-m", mid);
 212         }
 213         opts.addSuffix(testClassArgs);
 214 
 215         return runWithArchive(opts);
 216     }
 217 
 218 
 219     // A common operation: dump, then check results
 220     public static OutputAnalyzer testDump(String appJar, String appClasses[],
 221                                           String... suffix) throws Exception {
 222         OutputAnalyzer output = dump(appJar, appClasses, suffix);
 223         output.shouldContain("Loading classes to share");
 224         output.shouldHaveExitValue(0);
 225         return output;
 226     }
 227 
 228 
 229     /**
 230      * Simple test -- dump and execute appJar with the given appClasses in classlist.
 231      */
 232     public static OutputAnalyzer test(String appJar, String appClasses[], String... args)
 233         throws Exception {
 234         testDump(appJar, appClasses);
 235 
 236         OutputAnalyzer output = exec(appJar, args);
 237         return checkExec(output);
 238     }
 239 
 240 
 241     public static OutputAnalyzer checkExecReturn(OutputAnalyzer output, int ret,
 242                            boolean checkContain, String... matches) throws Exception {
 243         try {
 244             for (String s : matches) {
 245                 if (checkContain) {
 246                     output.shouldContain(s);
 247                 } else {
 248                     output.shouldNotContain(s);
 249                 }
 250             }
 251             output.shouldHaveExitValue(ret);
 252         } catch (Exception e) {
 253             checkCommonExecExceptions(output, e);
 254         }
 255 
 256         return output;
 257     }
 258 
 259 
 260     // Convenience concatenation utils
 261     public static String[] list(String ...args) {
 262         return args;
 263     }
 264 
 265 
 266     public static String[] list(String arg, int count) {
 267         ArrayList<String> stringList = new ArrayList<String>();
 268         for (int i = 0; i < count; i++) {
 269             stringList.add(arg);
 270         }
 271 
 272         String outputArray[] = stringList.toArray(new String[stringList.size()]);
 273         return outputArray;
 274     }
 275 
 276 
 277     public static String[] concat(String... args) {
 278         return list(args);
 279     }
 280 
 281 
 282     public static String[] concat(String prefix[], String... extra) {
 283         ArrayList<String> list = new ArrayList<String>();
 284         for (String s : prefix) {
 285             list.add(s);
 286         }
 287         for (String s : extra) {
 288             list.add(s);
 289         }
 290 
 291         return list.toArray(new String[list.size()]);
 292     }
 293 
 294 
 295     // ===================== Concatenate paths
 296     public static String concatPaths(String... paths) {
 297         String prefix = "";
 298         String s = "";
 299         for (String p : paths) {
 300             s += prefix;
 301             s += p;
 302             prefix = File.pathSeparator;
 303         }
 304         return s;
 305     }
 306 
 307 
 308     public static String getTestJar(String jar) {
 309         File jarFile = CDSTestUtils.getTestArtifact(jar, true);
 310         if (!jarFile.isFile()) {
 311             throw new RuntimeException("Not a regular file: " + jarFile.getPath());
 312         }
 313         return jarFile.getPath();
 314     }
 315 
 316 
 317     public static String getTestDir(String d) {
 318         File dirFile = CDSTestUtils.getTestArtifact(d, true);
 319         if (!dirFile.isDirectory()) {
 320             throw new RuntimeException("Not a directory: " + dirFile.getPath());
 321         }
 322         return dirFile.getPath();
 323     }
 324 }