1 /*
   2  * Copyright (c) 2012, 2014, 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.  Oracle designates this
   8  * particular file as subject to the "Classpath" exception as provided
   9  * by Oracle in the LICENSE file that accompanied this code.
  10  *
  11  * This code is distributed in the hope that it will be useful, but WITHOUT
  12  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  13  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  14  * version 2 for more details (a copy is included in the LICENSE file that
  15  * accompanied this code).
  16  *
  17  * You should have received a copy of the GNU General Public License version
  18  * 2 along with this work; if not, write to the Free Software Foundation,
  19  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  20  *
  21  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  22  * or visit www.oracle.com if you need additional information or have any
  23  * questions.
  24  */
  25 
  26 package com.sun.tools.sjavac;
  27 
  28 import java.io.File;
  29 import java.io.PrintStream;
  30 import java.net.URI;
  31 import java.util.Arrays;
  32 import java.util.Collections;
  33 import java.util.Random;
  34 import java.util.Set;
  35 import java.util.List;
  36 import java.util.Map;
  37 
  38 import com.sun.tools.sjavac.options.Options;
  39 import com.sun.tools.sjavac.server.CompilationResult;
  40 import com.sun.tools.sjavac.server.JavacService;
  41 import com.sun.tools.sjavac.server.SysInfo;
  42 
  43 /**
  44  * This transform compiles a set of packages containing Java sources.
  45  * The compile request is divided into separate sets of source files.
  46  * For each set a separate request thread is dispatched to a javac server
  47  * and the meta data is accumulated. The number of sets correspond more or
  48  * less to the number of cores. Less so now, than it will in the future.
  49  *
  50  * <p><b>This is NOT part of any supported API.
  51  * If you write code that depends on this, you do so at your own
  52  * risk.  This code and its internal interfaces are subject to change
  53  * or deletion without notice.</b></p>
  54  */
  55 public class CompileJavaPackages implements Transformer {
  56 
  57     // The current limited sharing of data between concurrent JavaCompilers
  58     // in the server will not give speedups above 3 cores. Thus this limit.
  59     // We hope to improve this in the future.
  60     final static int limitOnConcurrency = 3;
  61 
  62     Options args;
  63 
  64     public void setExtra(String e) {
  65     }
  66 
  67     public void setExtra(Options a) {
  68         args = a;
  69     }
  70 
  71     public boolean transform(final JavacService javacService,
  72                              Map<String,Set<URI>> pkgSrcs,
  73                              final Set<URI>             visibleSources,
  74                              final Map<URI,Set<String>> visibleClasses,
  75                              Map<String,Set<String>> oldPackageDependents,
  76                              URI destRoot,
  77                              final Map<String,Set<URI>>    packageArtifacts,
  78                              final Map<String,Set<String>> packageDependencies,
  79                              final Map<String,List<String>> packagePublicApis,
  80                              final Map<String,Set<String>> classpathPackageDependencies,
  81                              int debugLevel,
  82                              boolean incremental,
  83                              int numCores,
  84                              final PrintStream out,
  85                              final PrintStream err)
  86     {
  87         boolean rc = true;
  88         boolean concurrentCompiles = true;
  89 
  90         // Fetch the id.
  91         final String id = Util.extractStringOption("id", javacService.serverSettings());
  92         // Only keep portfile and sjavac settings..
  93         String psServerSettings = Util.cleanSubOptions(Util.set("portfile","sjavac","background","keepalive"), javacService.serverSettings());
  94 
  95         // Get maximum heap size from the server!
  96         SysInfo sysinfo = javacService.getSysInfo();
  97         if (sysinfo.numCores == -1) {
  98             Log.error("Could not query server for sysinfo! Check javac_server.stdouterr for exceptions");
  99             return false;
 100         }
 101         int numMBytes = (int)(sysinfo.maxMemory / ((long)(1024*1024)));
 102         Log.debug("Server reports "+numMBytes+"MiB of memory and "+sysinfo.numCores+" cores");
 103 
 104         if (numCores <= 0) {
 105             // Set the requested number of cores to the number of cores on the server.
 106             numCores = sysinfo.numCores;
 107             Log.debug("Number of jobs not explicitly set, defaulting to "+sysinfo.numCores);
 108         } else if (sysinfo.numCores < numCores) {
 109             // Set the requested number of cores to the number of cores on the server.
 110             Log.debug("Limiting jobs from explicitly set "+numCores+" to cores available on server: "+sysinfo.numCores);
 111             numCores = sysinfo.numCores;
 112         } else {
 113             Log.debug("Number of jobs explicitly set to "+numCores);
 114         }
 115         // More than three concurrent cores does not currently give a speedup, at least for compiling the jdk
 116         // in the OpenJDK. This will change in the future.
 117         int numCompiles = numCores;
 118         if (numCores > limitOnConcurrency) numCompiles = limitOnConcurrency;
 119         // Split the work up in chunks to compiled.
 120 
 121         int numSources = 0;
 122         for (String s : pkgSrcs.keySet()) {
 123             Set<URI> ss = pkgSrcs.get(s);
 124             numSources += ss.size();
 125         }
 126 
 127         int sourcesPerCompile = numSources / numCompiles;
 128 
 129         // For 64 bit Java, it seems we can compile the OpenJDK 8800 files with a 1500M of heap
 130         // in a single chunk, with reasonable performance.
 131         // For 32 bit java, it seems we need 1G of heap.
 132         // Number experimentally determined when compiling the OpenJDK.
 133         // Includes space for reasonably efficient garbage collection etc,
 134         // Calculating backwards gives us a requirement of
 135         // 1500M/8800 = 175 KiB for 64 bit platforms
 136         // and 1G/8800 = 119 KiB for 32 bit platform
 137         // for each compile.....
 138         int kbPerFile = 175;
 139         String osarch = System.getProperty("os.arch");
 140         String dataModel = System.getProperty("sun.arch.data.model");
 141         if ("32".equals(dataModel)) {
 142             // For 32 bit platforms, assume it is slightly smaller
 143             // because of smaller object headers and pointers.
 144             kbPerFile = 119;
 145         }
 146         int numRequiredMBytes = (kbPerFile*numSources)/1024;
 147         Log.debug("For os.arch "+osarch+" the empirically determined heap required per file is "+kbPerFile+"KiB");
 148         Log.debug("Server has "+numMBytes+"MiB of heap.");
 149         Log.debug("Heuristics say that we need "+numRequiredMBytes+"MiB of heap for all source files.");
 150         // Perform heuristics to see how many cores we can use,
 151         // or if we have to the work serially in smaller chunks.
 152         if (numMBytes < numRequiredMBytes) {
 153             // Ouch, cannot fit even a single compile into the heap.
 154             // Split it up into several serial chunks.
 155             concurrentCompiles = false;
 156             // Limit the number of sources for each compile to 500.
 157             if (numSources < 500) {
 158                 numCompiles = 1;
 159                 sourcesPerCompile = numSources;
 160                 Log.debug("Compiling as a single source code chunk to stay within heap size limitations!");
 161             } else if (sourcesPerCompile > 500) {
 162                 // This number is very low, and tuned to dealing with the OpenJDK
 163                 // where the source is >very< circular! In normal application,
 164                 // with less circularity the number could perhaps be increased.
 165                 numCompiles = numSources / 500;
 166                 sourcesPerCompile = numSources/numCompiles;
 167                 Log.debug("Compiling source as "+numCompiles+" code chunks serially to stay within heap size limitations!");
 168             }
 169         } else {
 170             if (numCompiles > 1) {
 171                 // Ok, we can fit at least one full compilation on the heap.
 172                 float usagePerCompile = (float)numRequiredMBytes / ((float)numCompiles * (float)0.7);
 173                 int usage = (int)(usagePerCompile * (float)numCompiles);
 174                 Log.debug("Heuristics say that for "+numCompiles+" concurrent compiles we need "+usage+"MiB");
 175                 if (usage > numMBytes) {
 176                     // Ouch it does not fit. Reduce to a single chunk.
 177                     numCompiles = 1;
 178                     sourcesPerCompile = numSources;
 179                     // What if the relationship betweem number of compile_chunks and num_required_mbytes
 180                     // is not linear? Then perhaps 2 chunks would fit where 3 does not. Well, this is
 181                     // something to experiment upon in the future.
 182                     Log.debug("Limiting compile to a single thread to stay within heap size limitations!");
 183                 }
 184             }
 185         }
 186 
 187         Log.debug("Compiling sources in "+numCompiles+" chunk(s)");
 188 
 189         // Create the chunks to be compiled.
 190         final CompileChunk[] compileChunks = createCompileChunks(pkgSrcs, oldPackageDependents,
 191                 numCompiles, sourcesPerCompile);
 192 
 193         if (Log.isDebugging()) {
 194             int cn = 1;
 195             for (CompileChunk cc : compileChunks) {
 196                 Log.debug("Chunk "+cn+" for "+id+" ---------------");
 197                 cn++;
 198                 for (URI u : cc.srcs) {
 199                     Log.debug(""+u);
 200                 }
 201             }
 202         }
 203 
 204         // The return values for each chunked compile.
 205         final CompilationResult[] rn = new CompilationResult[numCompiles];
 206         // The requets, might or might not run as a background thread.
 207         final Thread[] requests  = new Thread[numCompiles];
 208 
 209         long start = System.currentTimeMillis();
 210 
 211         for (int i=0; i<numCompiles; ++i) {
 212             final int ii = i;
 213             final CompileChunk cc = compileChunks[i];
 214 
 215             // Pass the num_cores and the id (appended with the chunk number) to the server.
 216             final String cleanedServerSettings = psServerSettings+",poolsize="+numCores+",id="+id+"-"+i;
 217 
 218             requests[i] = new Thread() {
 219                 @Override
 220                 public void run() {
 221                     rn[ii] = javacService.compile("n/a",
 222                                                   id + "-" + ii,
 223                                                   args.prepJavacArgs(),
 224                                                   Collections.<File>emptyList(),
 225                                                   cc.srcs,
 226                                                   visibleSources);
 227                     packageArtifacts.putAll(rn[ii].packageArtifacts);
 228                     packageDependencies.putAll(rn[ii].packageDependencies);
 229                     packagePublicApis.putAll(rn[ii].packagePublicApis);
 230                     classpathPackageDependencies.putAll(rn[ii].classpathPackageDependencies);
 231                 }
 232             };
 233 
 234             if (cc.srcs.size() > 0) {
 235                 String numdeps = "";
 236                 if (cc.numDependents > 0) numdeps = "(with "+cc.numDependents+" dependents) ";
 237                 if (!incremental || cc.numPackages > 16) {
 238                     String info = "("+cc.pkgFromTos+")";
 239                     if (info.equals("( to )")) {
 240                         info = "";
 241                     }
 242                     Log.info("Compiling "+cc.srcs.size()+" files "+numdeps+"in "+cc.numPackages+" packages "+info);
 243                 } else {
 244                     Log.info("Compiling "+cc.pkgNames+numdeps);
 245                 }
 246                 if (concurrentCompiles) {
 247                     requests[ii].start();
 248                 }
 249                 else {
 250                     requests[ii].run();
 251                     // If there was an error, then stop early when running single threaded.
 252                     if (rn[i].returnCode != 0) {
 253                         return false;
 254                     }
 255                 }
 256             }
 257         }
 258         if (concurrentCompiles) {
 259             // If there are background threads for the concurrent compiles, then join them.
 260             for (int i=0; i<numCompiles; ++i) {
 261                 try { requests[i].join(); } catch (InterruptedException e) { }
 262             }
 263         }
 264 
 265         // Check the return values.
 266         for (int i=0; i<numCompiles; ++i) {
 267             if (compileChunks[i].srcs.size() > 0) {
 268                 if (rn[i].returnCode != 0) {
 269                     rc = false;
 270                 }
 271             }
 272         }
 273         long duration = System.currentTimeMillis() - start;
 274         long minutes = duration/60000;
 275         long seconds = (duration-minutes*60000)/1000;
 276         Log.debug("Compilation of "+numSources+" source files took "+minutes+"m "+seconds+"s");
 277 
 278         return rc;
 279     }
 280 
 281 
 282     /**
 283      * Split up the sources into compile chunks. If old package dependents information
 284      * is available, sort the order of the chunks into the most dependent first!
 285      * (Typically that chunk contains the java.lang package.) In the future
 286      * we could perhaps improve the heuristics to put the sources into even more sensible chunks.
 287      * Now the package are simple sorted in alphabetical order and chunked, then the chunks
 288      * are sorted on how dependent they are.
 289      *
 290      * @param pkgSrcs The sources to compile.
 291      * @param oldPackageDependents Old package dependents, if non-empty, used to sort the chunks.
 292      * @param numCompiles The number of chunks.
 293      * @param sourcesPerCompile The number of sources per chunk.
 294      * @return
 295      */
 296     CompileChunk[] createCompileChunks(Map<String,Set<URI>> pkgSrcs,
 297                                  Map<String,Set<String>> oldPackageDependents,
 298                                  int numCompiles,
 299                                  int sourcesPerCompile) {
 300 
 301         CompileChunk[] compileChunks = new CompileChunk[numCompiles];
 302         for (int i=0; i<compileChunks.length; ++i) {
 303             compileChunks[i] = new CompileChunk();
 304         }
 305 
 306         // Now go through the packages and spread out the source on the different chunks.
 307         int ci = 0;
 308         // Sort the packages
 309         String[] packageNames = pkgSrcs.keySet().toArray(new String[0]);
 310         Arrays.sort(packageNames);
 311         String from = null;
 312         for (String pkgName : packageNames) {
 313             CompileChunk cc = compileChunks[ci];
 314             Set<URI> s = pkgSrcs.get(pkgName);
 315             if (cc.srcs.size()+s.size() > sourcesPerCompile && ci < numCompiles-1) {
 316                 from = null;
 317                 ci++;
 318                 cc = compileChunks[ci];
 319             }
 320             cc.numPackages++;
 321             cc.srcs.addAll(s);
 322 
 323             // Calculate nice package names to use as information when compiling.
 324             String justPkgName = Util.justPackageName(pkgName);
 325             // Fetch how many packages depend on this package from the old build state.
 326             Set<String> ss = oldPackageDependents.get(pkgName);
 327             if (ss != null) {
 328                 // Accumulate this information onto this chunk.
 329                 cc.numDependents += ss.size();
 330             }
 331             if (from == null || from.trim().equals("")) from = justPkgName;
 332             cc.pkgNames.append(justPkgName+"("+s.size()+") ");
 333             cc.pkgFromTos = from+" to "+justPkgName;
 334         }
 335         // If we are compiling serially, sort the chunks, so that the chunk (with the most dependents) (usually the chunk
 336         // containing java.lang.Object, is to be compiled first!
 337         // For concurrent compilation, this does not matter.
 338         Arrays.sort(compileChunks);
 339         return compileChunks;
 340     }
 341 }