CompileJavaPackages.java revision 2958:27da0c3ac83a
1/*
2 * Copyright (c) 2012, 2015, 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.PrintStream;
30import java.net.URI;
31import java.util.Arrays;
32import java.util.Collections;
33import java.util.HashMap;
34import java.util.Map;
35import java.util.Set;
36
37import com.sun.tools.sjavac.options.Options;
38import com.sun.tools.sjavac.pubapi.PubApi;
39import com.sun.tools.sjavac.server.CompilationResult;
40import com.sun.tools.sjavac.server.Sjavac;
41import 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 */
55public 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 Sjavac sjavac,
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,Map<String, Set<String>>> packageDependencies,
79                             final Map<String,Map<String, Set<String>>> packageCpDependencies,
80                             final Map<String, PubApi> packagePubapis,
81                             final Map<String, PubApi> dependencyPubapis,
82                             int debugLevel,
83                             boolean incremental,
84                             int numCores,
85                             final PrintStream out,
86                             final PrintStream err) {
87
88        Log.debug("Performing CompileJavaPackages transform...");
89
90        boolean rc = true;
91        boolean concurrentCompiles = true;
92
93        // Fetch the id.
94        final String id = Util.extractStringOption("id", sjavac.serverSettings());
95        // Only keep portfile and sjavac settings..
96        //String psServerSettings = Util.cleanSubOptions(Util.set("portfile","sjavac","background","keepalive"), sjavac.serverSettings());
97
98        // Get maximum heap size from the server!
99        SysInfo sysinfo = sjavac.getSysInfo();
100        if (sysinfo == null) {
101            Log.error("Could not query server for sysinfo!");
102            return false;
103        }
104        int numMBytes = (int)(sysinfo.maxMemory / ((long)(1024*1024)));
105        Log.debug("Server reports "+numMBytes+"MiB of memory and "+sysinfo.numCores+" cores");
106
107        if (numCores <= 0) {
108            // Set the requested number of cores to the number of cores on the server.
109            numCores = sysinfo.numCores;
110            Log.debug("Number of jobs not explicitly set, defaulting to "+sysinfo.numCores);
111        } else if (sysinfo.numCores < numCores) {
112            // Set the requested number of cores to the number of cores on the server.
113            Log.debug("Limiting jobs from explicitly set "+numCores+" to cores available on server: "+sysinfo.numCores);
114            numCores = sysinfo.numCores;
115        } else {
116            Log.debug("Number of jobs explicitly set to "+numCores);
117        }
118        // More than three concurrent cores does not currently give a speedup, at least for compiling the jdk
119        // in the OpenJDK. This will change in the future.
120        int numCompiles = numCores;
121        if (numCores > limitOnConcurrency) numCompiles = limitOnConcurrency;
122        // Split the work up in chunks to compiled.
123
124        int numSources = 0;
125        for (String s : pkgSrcs.keySet()) {
126            Set<URI> ss = pkgSrcs.get(s);
127            numSources += ss.size();
128        }
129
130        int sourcesPerCompile = numSources / numCompiles;
131
132        // For 64 bit Java, it seems we can compile the OpenJDK 8800 files with a 1500M of heap
133        // in a single chunk, with reasonable performance.
134        // For 32 bit java, it seems we need 1G of heap.
135        // Number experimentally determined when compiling the OpenJDK.
136        // Includes space for reasonably efficient garbage collection etc,
137        // Calculating backwards gives us a requirement of
138        // 1500M/8800 = 175 KiB for 64 bit platforms
139        // and 1G/8800 = 119 KiB for 32 bit platform
140        // for each compile.....
141        int kbPerFile = 175;
142        String osarch = System.getProperty("os.arch");
143        String dataModel = System.getProperty("sun.arch.data.model");
144        if ("32".equals(dataModel)) {
145            // For 32 bit platforms, assume it is slightly smaller
146            // because of smaller object headers and pointers.
147            kbPerFile = 119;
148        }
149        int numRequiredMBytes = (kbPerFile*numSources)/1024;
150        Log.debug("For os.arch "+osarch+" the empirically determined heap required per file is "+kbPerFile+"KiB");
151        Log.debug("Server has "+numMBytes+"MiB of heap.");
152        Log.debug("Heuristics say that we need "+numRequiredMBytes+"MiB of heap for all source files.");
153        // Perform heuristics to see how many cores we can use,
154        // or if we have to the work serially in smaller chunks.
155        if (numMBytes < numRequiredMBytes) {
156            // Ouch, cannot fit even a single compile into the heap.
157            // Split it up into several serial chunks.
158            concurrentCompiles = false;
159            // Limit the number of sources for each compile to 500.
160            if (numSources < 500) {
161                numCompiles = 1;
162                sourcesPerCompile = numSources;
163                Log.debug("Compiling as a single source code chunk to stay within heap size limitations!");
164            } else if (sourcesPerCompile > 500) {
165                // This number is very low, and tuned to dealing with the OpenJDK
166                // where the source is >very< circular! In normal application,
167                // with less circularity the number could perhaps be increased.
168                numCompiles = numSources / 500;
169                sourcesPerCompile = numSources/numCompiles;
170                Log.debug("Compiling source as "+numCompiles+" code chunks serially to stay within heap size limitations!");
171            }
172        } else {
173            if (numCompiles > 1) {
174                // Ok, we can fit at least one full compilation on the heap.
175                float usagePerCompile = (float)numRequiredMBytes / ((float)numCompiles * (float)0.7);
176                int usage = (int)(usagePerCompile * (float)numCompiles);
177                Log.debug("Heuristics say that for "+numCompiles+" concurrent compiles we need "+usage+"MiB");
178                if (usage > numMBytes) {
179                    // Ouch it does not fit. Reduce to a single chunk.
180                    numCompiles = 1;
181                    sourcesPerCompile = numSources;
182                    // What if the relationship betweem number of compile_chunks and num_required_mbytes
183                    // is not linear? Then perhaps 2 chunks would fit where 3 does not. Well, this is
184                    // something to experiment upon in the future.
185                    Log.debug("Limiting compile to a single thread to stay within heap size limitations!");
186                }
187            }
188        }
189
190        Log.debug("Compiling sources in "+numCompiles+" chunk(s)");
191
192        // Create the chunks to be compiled.
193        final CompileChunk[] compileChunks = createCompileChunks(pkgSrcs, oldPackageDependents,
194                numCompiles, sourcesPerCompile);
195
196        if (Log.isDebugging()) {
197            int cn = 1;
198            for (CompileChunk cc : compileChunks) {
199                Log.debug("Chunk "+cn+" for "+id+" ---------------");
200                cn++;
201                for (URI u : cc.srcs) {
202                    Log.debug(""+u);
203                }
204            }
205        }
206
207        // The return values for each chunked compile.
208        final CompilationResult[] rn = new CompilationResult[numCompiles];
209        // The requets, might or might not run as a background thread.
210        final Thread[] requests  = new Thread[numCompiles];
211
212        long start = System.currentTimeMillis();
213
214        for (int i=0; i<numCompiles; ++i) {
215            final int ii = i;
216            final CompileChunk cc = compileChunks[i];
217
218            // Pass the num_cores and the id (appended with the chunk number) to the server.
219            Object lock = new Object();
220            requests[i] = new Thread() {
221                @Override
222                public void run() {
223                    rn[ii] = sjavac.compile("n/a",
224                                            id + "-" + ii,
225                                            args.prepJavacArgs(),
226                                            Collections.<File>emptyList(),
227                                            cc.srcs,
228                                            visibleSources);
229                    // In the code below we have to keep in mind that two
230                    // different compilation results may include results for
231                    // the same package.
232                    synchronized (lock) {
233
234                        for (String pkg : rn[ii].packageArtifacts.keySet()) {
235                            Set<URI> pkgArtifacts = rn[ii].packageArtifacts.get(pkg);
236                            packageArtifacts.merge(pkg, pkgArtifacts, Util::union);
237                        }
238
239                        for (String pkg : rn[ii].packageDependencies.keySet()) {
240                            packageDependencies.putIfAbsent(pkg, new HashMap<>());
241                            packageDependencies.get(pkg).putAll(rn[ii].packageDependencies.get(pkg));
242                        }
243
244                        for (String pkg : rn[ii].packageCpDependencies.keySet()) {
245                            packageCpDependencies.putIfAbsent(pkg, new HashMap<>());
246                            packageCpDependencies.get(pkg).putAll(rn[ii].packageCpDependencies.get(pkg));
247                        }
248
249                        for (String pkg : rn[ii].packagePubapis.keySet()) {
250                            packagePubapis.merge(pkg, rn[ii].packagePubapis.get(pkg), PubApi::mergeTypes);
251                        }
252
253                        for (String pkg : rn[ii].dependencyPubapis.keySet()) {
254                            dependencyPubapis.merge(pkg, rn[ii].dependencyPubapis.get(pkg), PubApi::mergeTypes);
255                        }
256                    }
257                }
258            };
259
260            if (cc.srcs.size() > 0) {
261                String numdeps = "";
262                if (cc.numDependents > 0) numdeps = "(with "+cc.numDependents+" dependents) ";
263                if (!incremental || cc.numPackages > 16) {
264                    String info = "("+cc.pkgFromTos+")";
265                    if (info.equals("( to )")) {
266                        info = "";
267                    }
268                    Log.info("Compiling "+cc.srcs.size()+" files "+numdeps+"in "+cc.numPackages+" packages "+info);
269                } else {
270                    Log.info("Compiling "+cc.pkgNames+numdeps);
271                }
272                if (concurrentCompiles) {
273                    requests[ii].start();
274                }
275                else {
276                    requests[ii].run();
277                    // If there was an error, then stop early when running single threaded.
278                    if (rn[i].returnCode != 0) {
279                        Log.info(rn[i].stdout);
280                        Log.error(rn[i].stderr);
281                        return false;
282                    }
283                }
284            }
285        }
286        if (concurrentCompiles) {
287            // If there are background threads for the concurrent compiles, then join them.
288            for (int i=0; i<numCompiles; ++i) {
289                try { requests[i].join(); } catch (InterruptedException e) { }
290            }
291        }
292
293        // Check the return values.
294        for (int i=0; i<numCompiles; ++i) {
295            if (compileChunks[i].srcs.size() > 0) {
296                if (rn[i].returnCode != 0) {
297                    Log.info(rn[i].stdout);
298                    Log.error(rn[i].stderr);
299                    rc = false;
300                }
301            }
302        }
303        long duration = System.currentTimeMillis() - start;
304        long minutes = duration/60000;
305        long seconds = (duration-minutes*60000)/1000;
306        Log.debug("Compilation of "+numSources+" source files took "+minutes+"m "+seconds+"s");
307
308        return rc;
309    }
310
311    /**
312     * Split up the sources into compile chunks. If old package dependents information
313     * is available, sort the order of the chunks into the most dependent first!
314     * (Typically that chunk contains the java.lang package.) In the future
315     * we could perhaps improve the heuristics to put the sources into even more sensible chunks.
316     * Now the package are simple sorted in alphabetical order and chunked, then the chunks
317     * are sorted on how dependent they are.
318     *
319     * @param pkgSrcs The sources to compile.
320     * @param oldPackageDependents Old package dependents, if non-empty, used to sort the chunks.
321     * @param numCompiles The number of chunks.
322     * @param sourcesPerCompile The number of sources per chunk.
323     * @return
324     */
325    CompileChunk[] createCompileChunks(Map<String,Set<URI>> pkgSrcs,
326                                       Map<String,Set<String>> oldPackageDependents,
327                                       int numCompiles,
328                                       int sourcesPerCompile) {
329
330        CompileChunk[] compileChunks = new CompileChunk[numCompiles];
331        for (int i=0; i<compileChunks.length; ++i) {
332            compileChunks[i] = new CompileChunk();
333        }
334
335        // Now go through the packages and spread out the source on the different chunks.
336        int ci = 0;
337        // Sort the packages
338        String[] packageNames = pkgSrcs.keySet().toArray(new String[0]);
339        Arrays.sort(packageNames);
340        String from = null;
341        for (String pkgName : packageNames) {
342            CompileChunk cc = compileChunks[ci];
343            Set<URI> s = pkgSrcs.get(pkgName);
344            if (cc.srcs.size()+s.size() > sourcesPerCompile && ci < numCompiles-1) {
345                from = null;
346                ci++;
347                cc = compileChunks[ci];
348            }
349            cc.numPackages++;
350            cc.srcs.addAll(s);
351
352            // Calculate nice package names to use as information when compiling.
353            String justPkgName = Util.justPackageName(pkgName);
354            // Fetch how many packages depend on this package from the old build state.
355            Set<String> ss = oldPackageDependents.get(pkgName);
356            if (ss != null) {
357                // Accumulate this information onto this chunk.
358                cc.numDependents += ss.size();
359            }
360            if (from == null || from.trim().equals("")) from = justPkgName;
361            cc.pkgNames.append(justPkgName+"("+s.size()+") ");
362            cc.pkgFromTos = from+" to "+justPkgName;
363        }
364        // If we are compiling serially, sort the chunks, so that the chunk (with the most dependents) (usually the chunk
365        // containing java.lang.Object, is to be compiled first!
366        // For concurrent compilation, this does not matter.
367        Arrays.sort(compileChunks);
368        return compileChunks;
369    }
370}
371