CompileJavaPackages.java revision 3191:e9a7033b2546
1/*
2 * Copyright (c) 2012, 2016, 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
26package com.sun.tools.sjavac;
27
28import java.io.File;
29import java.io.IOException;
30import java.io.Writer;
31import java.net.URI;
32import java.util.ArrayList;
33import java.util.Arrays;
34import java.util.Collections;
35import java.util.HashMap;
36import java.util.List;
37import java.util.Map;
38import java.util.Random;
39import java.util.Set;
40import java.util.concurrent.Callable;
41import java.util.concurrent.ExecutionException;
42import java.util.concurrent.ExecutorService;
43import java.util.concurrent.Executors;
44import java.util.concurrent.Future;
45
46import com.sun.tools.sjavac.comp.CompilationService;
47import com.sun.tools.sjavac.options.Options;
48import com.sun.tools.sjavac.pubapi.PubApi;
49import com.sun.tools.sjavac.server.CompilationSubResult;
50import com.sun.tools.sjavac.server.SysInfo;
51
52/**
53 * This transform compiles a set of packages containing Java sources.
54 * The compile request is divided into separate sets of source files.
55 * For each set a separate request thread is dispatched to a javac server
56 * and the meta data is accumulated. The number of sets correspond more or
57 * less to the number of cores. Less so now, than it will in the future.
58 *
59 * <p><b>This is NOT part of any supported API.
60 * If you write code that depends on this, you do so at your own
61 * risk.  This code and its internal interfaces are subject to change
62 * or deletion without notice.</b></p>
63 */
64public class CompileJavaPackages implements Transformer {
65
66    // The current limited sharing of data between concurrent JavaCompilers
67    // in the server will not give speedups above 3 cores. Thus this limit.
68    // We hope to improve this in the future.
69    final static int limitOnConcurrency = 3;
70
71    Options args;
72
73    public void setExtra(String e) {
74    }
75
76    public void setExtra(Options a) {
77        args = a;
78    }
79
80    public boolean transform(final CompilationService sjavac,
81                             Map<String,Set<URI>> pkgSrcs,
82                             final Set<URI>             visibleSources,
83                             Map<String,Set<String>> oldPackageDependents,
84                             URI destRoot,
85                             final Map<String,Set<URI>>    packageArtifacts,
86                             final Map<String,Map<String, Set<String>>> packageDependencies,
87                             final Map<String,Map<String, Set<String>>> packageCpDependencies,
88                             final Map<String, PubApi> packagePubapis,
89                             final Map<String, PubApi> dependencyPubapis,
90                             int debugLevel,
91                             boolean incremental,
92                             int numCores,
93                             final Writer out,
94                             final Writer err) {
95
96        Log.debug("Performing CompileJavaPackages transform...");
97
98        boolean rc = true;
99        boolean concurrentCompiles = true;
100
101        // Fetch the id.
102        final String id = String.valueOf(new Random().nextInt());
103        // Only keep portfile and sjavac settings..
104        //String psServerSettings = Util.cleanSubOptions(Util.set("portfile","sjavac","background","keepalive"), sjavac.serverSettings());
105
106        SysInfo sysinfo = sjavac.getSysInfo();
107        int numMBytes = (int)(sysinfo.maxMemory / ((long)(1024*1024)));
108        Log.debug("Server reports "+numMBytes+"MiB of memory and "+sysinfo.numCores+" cores");
109
110        if (numCores <= 0) {
111            // Set the requested number of cores to the number of cores on the server.
112            numCores = sysinfo.numCores;
113            Log.debug("Number of jobs not explicitly set, defaulting to "+sysinfo.numCores);
114        } else if (sysinfo.numCores < numCores) {
115            // Set the requested number of cores to the number of cores on the server.
116            Log.debug("Limiting jobs from explicitly set "+numCores+" to cores available on server: "+sysinfo.numCores);
117            numCores = sysinfo.numCores;
118        } else {
119            Log.debug("Number of jobs explicitly set to "+numCores);
120        }
121        // More than three concurrent cores does not currently give a speedup, at least for compiling the jdk
122        // in the OpenJDK. This will change in the future.
123        int numCompiles = numCores;
124        if (numCores > limitOnConcurrency) numCompiles = limitOnConcurrency;
125        // Split the work up in chunks to compiled.
126
127        int numSources = 0;
128        for (String s : pkgSrcs.keySet()) {
129            Set<URI> ss = pkgSrcs.get(s);
130            numSources += ss.size();
131        }
132
133        int sourcesPerCompile = numSources / numCompiles;
134
135        // For 64 bit Java, it seems we can compile the OpenJDK 8800 files with a 1500M of heap
136        // in a single chunk, with reasonable performance.
137        // For 32 bit java, it seems we need 1G of heap.
138        // Number experimentally determined when compiling the OpenJDK.
139        // Includes space for reasonably efficient garbage collection etc,
140        // Calculating backwards gives us a requirement of
141        // 1500M/8800 = 175 KiB for 64 bit platforms
142        // and 1G/8800 = 119 KiB for 32 bit platform
143        // for each compile.....
144        int kbPerFile = 175;
145        String osarch = System.getProperty("os.arch");
146        String dataModel = System.getProperty("sun.arch.data.model");
147        if ("32".equals(dataModel)) {
148            // For 32 bit platforms, assume it is slightly smaller
149            // because of smaller object headers and pointers.
150            kbPerFile = 119;
151        }
152        int numRequiredMBytes = (kbPerFile*numSources)/1024;
153        Log.debug("For os.arch "+osarch+" the empirically determined heap required per file is "+kbPerFile+"KiB");
154        Log.debug("Server has "+numMBytes+"MiB of heap.");
155        Log.debug("Heuristics say that we need "+numRequiredMBytes+"MiB of heap for all source files.");
156        // Perform heuristics to see how many cores we can use,
157        // or if we have to the work serially in smaller chunks.
158        if (numMBytes < numRequiredMBytes) {
159            // Ouch, cannot fit even a single compile into the heap.
160            // Split it up into several serial chunks.
161            concurrentCompiles = false;
162            // Limit the number of sources for each compile to 500.
163            if (numSources < 500) {
164                numCompiles = 1;
165                sourcesPerCompile = numSources;
166                Log.debug("Compiling as a single source code chunk to stay within heap size limitations!");
167            } else if (sourcesPerCompile > 500) {
168                // This number is very low, and tuned to dealing with the OpenJDK
169                // where the source is >very< circular! In normal application,
170                // with less circularity the number could perhaps be increased.
171                numCompiles = numSources / 500;
172                sourcesPerCompile = numSources/numCompiles;
173                Log.debug("Compiling source as "+numCompiles+" code chunks serially to stay within heap size limitations!");
174            }
175        } else {
176            if (numCompiles > 1) {
177                // Ok, we can fit at least one full compilation on the heap.
178                float usagePerCompile = (float)numRequiredMBytes / ((float)numCompiles * (float)0.7);
179                int usage = (int)(usagePerCompile * (float)numCompiles);
180                Log.debug("Heuristics say that for "+numCompiles+" concurrent compiles we need "+usage+"MiB");
181                if (usage > numMBytes) {
182                    // Ouch it does not fit. Reduce to a single chunk.
183                    numCompiles = 1;
184                    sourcesPerCompile = numSources;
185                    // What if the relationship betweem number of compile_chunks and num_required_mbytes
186                    // is not linear? Then perhaps 2 chunks would fit where 3 does not. Well, this is
187                    // something to experiment upon in the future.
188                    Log.debug("Limiting compile to a single thread to stay within heap size limitations!");
189                }
190            }
191        }
192
193        Log.debug("Compiling sources in "+numCompiles+" chunk(s)");
194
195        // Create the chunks to be compiled.
196        final CompileChunk[] compileChunks = createCompileChunks(pkgSrcs, oldPackageDependents,
197                numCompiles, sourcesPerCompile);
198
199        if (Log.isDebugging()) {
200            int cn = 1;
201            for (CompileChunk cc : compileChunks) {
202                Log.debug("Chunk "+cn+" for "+id+" ---------------");
203                cn++;
204                for (URI u : cc.srcs) {
205                    Log.debug(""+u);
206                }
207            }
208        }
209
210        long start = System.currentTimeMillis();
211
212        // Prepare compilation calls
213        List<Callable<CompilationSubResult>> compilationCalls = new ArrayList<>();
214        final Object lock = new Object();
215        for (int i = 0; i < numCompiles; i++) {
216            CompileChunk cc = compileChunks[i];
217            if (cc.srcs.isEmpty()) {
218                continue;
219            }
220
221            String chunkId = id + "-" + String.valueOf(i);
222            compilationCalls.add(() -> {
223                CompilationSubResult result = sjavac.compile("n/a",
224                                                             chunkId,
225                                                             args.prepJavacArgs(),
226                                                             Collections.<File>emptyList(),
227                                                             cc.srcs,
228                                                             visibleSources);
229                synchronized (lock) {
230                    safeWrite(result.stdout, out);
231                    safeWrite(result.stderr, err);
232                }
233                return result;
234            });
235        }
236
237        // Perform compilations and collect results
238        List<CompilationSubResult> subResults = new ArrayList<>();
239        List<Future<CompilationSubResult>> futs = new ArrayList<>();
240        ExecutorService exec = Executors.newFixedThreadPool(concurrentCompiles ? compilationCalls.size() : 1);
241        for (Callable<CompilationSubResult> compilationCall : compilationCalls) {
242            futs.add(exec.submit(compilationCall));
243        }
244        for (Future<CompilationSubResult> fut : futs) {
245            try {
246                subResults.add(fut.get());
247            } catch (ExecutionException ee) {
248                Log.error("Compilation failed: " + ee.getMessage());
249            } catch (InterruptedException ee) {
250                Log.error("Compilation interrupted: " + ee.getMessage());
251                Thread.currentThread().interrupt();
252            }
253        }
254        exec.shutdownNow();
255
256        // Process each sub result
257        for (CompilationSubResult subResult : subResults) {
258            for (String pkg : subResult.packageArtifacts.keySet()) {
259                Set<URI> pkgArtifacts = subResult.packageArtifacts.get(pkg);
260                packageArtifacts.merge(pkg, pkgArtifacts, Util::union);
261            }
262
263            for (String pkg : subResult.packageDependencies.keySet()) {
264                packageDependencies.putIfAbsent(pkg, new HashMap<>());
265                packageDependencies.get(pkg).putAll(subResult.packageDependencies.get(pkg));
266            }
267
268            for (String pkg : subResult.packageCpDependencies.keySet()) {
269                packageCpDependencies.putIfAbsent(pkg, new HashMap<>());
270                packageCpDependencies.get(pkg).putAll(subResult.packageCpDependencies.get(pkg));
271            }
272
273            for (String pkg : subResult.packagePubapis.keySet()) {
274                packagePubapis.merge(pkg, subResult.packagePubapis.get(pkg), PubApi::mergeTypes);
275            }
276
277            for (String pkg : subResult.dependencyPubapis.keySet()) {
278                dependencyPubapis.merge(pkg, subResult.dependencyPubapis.get(pkg), PubApi::mergeTypes);
279            }
280
281            // Check the return values.
282            if (subResult.returnCode != 0) {
283                rc = false;
284            }
285        }
286
287        long duration = System.currentTimeMillis() - start;
288        long minutes = duration/60000;
289        long seconds = (duration-minutes*60000)/1000;
290        Log.debug("Compilation of "+numSources+" source files took "+minutes+"m "+seconds+"s");
291
292        return rc;
293    }
294
295    private void safeWrite(String str, Writer w) {
296        if (str.length() > 0) {
297            try {
298                w.write(str);
299            } catch (IOException e) {
300                Log.error("Could not print compilation output.");
301            }
302        }
303    }
304
305    /**
306     * Split up the sources into compile chunks. If old package dependents information
307     * is available, sort the order of the chunks into the most dependent first!
308     * (Typically that chunk contains the java.lang package.) In the future
309     * we could perhaps improve the heuristics to put the sources into even more sensible chunks.
310     * Now the package are simple sorted in alphabetical order and chunked, then the chunks
311     * are sorted on how dependent they are.
312     *
313     * @param pkgSrcs The sources to compile.
314     * @param oldPackageDependents Old package dependents, if non-empty, used to sort the chunks.
315     * @param numCompiles The number of chunks.
316     * @param sourcesPerCompile The number of sources per chunk.
317     * @return
318     */
319    CompileChunk[] createCompileChunks(Map<String,Set<URI>> pkgSrcs,
320                                       Map<String,Set<String>> oldPackageDependents,
321                                       int numCompiles,
322                                       int sourcesPerCompile) {
323
324        CompileChunk[] compileChunks = new CompileChunk[numCompiles];
325        for (int i=0; i<compileChunks.length; ++i) {
326            compileChunks[i] = new CompileChunk();
327        }
328
329        // Now go through the packages and spread out the source on the different chunks.
330        int ci = 0;
331        // Sort the packages
332        String[] packageNames = pkgSrcs.keySet().toArray(new String[0]);
333        Arrays.sort(packageNames);
334        String from = null;
335        for (String pkgName : packageNames) {
336            CompileChunk cc = compileChunks[ci];
337            Set<URI> s = pkgSrcs.get(pkgName);
338            if (cc.srcs.size()+s.size() > sourcesPerCompile && ci < numCompiles-1) {
339                from = null;
340                ci++;
341                cc = compileChunks[ci];
342            }
343            cc.numPackages++;
344            cc.srcs.addAll(s);
345
346            // Calculate nice package names to use as information when compiling.
347            String justPkgName = Util.justPackageName(pkgName);
348            // Fetch how many packages depend on this package from the old build state.
349            Set<String> ss = oldPackageDependents.get(pkgName);
350            if (ss != null) {
351                // Accumulate this information onto this chunk.
352                cc.numDependents += ss.size();
353            }
354            if (from == null || from.trim().equals("")) from = justPkgName;
355            cc.pkgNames.append(justPkgName+"("+s.size()+") ");
356            cc.pkgFromTos = from+" to "+justPkgName;
357        }
358        // If we are compiling serially, sort the chunks, so that the chunk (with the most dependents) (usually the chunk
359        // containing java.lang.Object, is to be compiled first!
360        // For concurrent compilation, this does not matter.
361        Arrays.sort(compileChunks);
362        return compileChunks;
363    }
364}
365