SjavacClient.java revision 2697:10100ecb0c97
1/*
2 * Copyright (c) 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
26package com.sun.tools.sjavac.client;
27
28import java.io.File;
29import java.io.FileNotFoundException;
30import java.io.IOException;
31import java.io.ObjectInputStream;
32import java.io.ObjectOutputStream;
33import java.io.PrintStream;
34import java.io.PrintWriter;
35import java.io.StringWriter;
36import java.net.InetAddress;
37import java.net.InetSocketAddress;
38import java.net.Socket;
39import java.net.URI;
40import java.util.ArrayList;
41import java.util.Arrays;
42import java.util.List;
43import java.util.Scanner;
44import java.util.Set;
45
46import com.sun.tools.sjavac.Log;
47import com.sun.tools.sjavac.Util;
48import com.sun.tools.sjavac.options.OptionHelper;
49import com.sun.tools.sjavac.options.Options;
50import com.sun.tools.sjavac.server.CompilationResult;
51import com.sun.tools.sjavac.server.PortFile;
52import com.sun.tools.sjavac.server.Sjavac;
53import com.sun.tools.sjavac.server.SjavacServer;
54import com.sun.tools.sjavac.server.SysInfo;
55
56/**
57 * Sjavac implementation that delegates requests to a SjavacServer.
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 risk.
61 *  This code and its internal interfaces are subject to change or
62 *  deletion without notice.</b>
63 */
64public class SjavacClient implements Sjavac {
65
66    // The id can perhaps be used in the future by the javac server to reuse the
67    // JavaCompiler instance for several compiles using the same id.
68    private final String id;
69    private final PortFile portFile;
70    private final String logfile;
71    private final String stdouterrfile;
72
73    // Default keepalive for server is 120 seconds.
74    // I.e. it will accept 120 seconds of inactivity before quitting.
75    private final int keepalive;
76    private final int poolsize;
77
78    // The sjavac option specifies how the server part of sjavac is spawned.
79    // If you have the experimental sjavac in your path, you are done. If not, you have
80    // to point to a com.sun.tools.sjavac.Main that supports --startserver
81    // for example by setting: sjavac=java%20-jar%20...javac.jar%com.sun.tools.sjavac.Main
82    private final String sjavacForkCmd;
83
84    // Wait 2 seconds for response, before giving up on javac server.
85    static int CONNECTION_TIMEOUT = 2000;
86    static int MAX_CONNECT_ATTEMPTS = 3;
87    static int WAIT_BETWEEN_CONNECT_ATTEMPTS = 2000;
88
89    // Store the server conf settings here.
90    private final String settings;
91
92    // This constructor should not throw FileNotFoundException (to be resolved
93    // in JDK-8060030)
94    public SjavacClient(Options options) throws FileNotFoundException {
95        String tmpServerConf = options.getServerConf();
96        String serverConf = (tmpServerConf!=null)? tmpServerConf : "";
97        String tmpId = Util.extractStringOption("id", serverConf);
98        id = (tmpId!=null) ? tmpId : "id"+(((new java.util.Random()).nextLong())&Long.MAX_VALUE);
99        String defaultPortfile = options.getStateDir()
100                                        .resolve("javac_server")
101                                        .toAbsolutePath()
102                                        .toString();
103        String portfileName = Util.extractStringOption("portfile", serverConf, defaultPortfile);
104        try {
105            portFile = SjavacServer.getPortFile(portfileName);
106        } catch (FileNotFoundException e) {
107            // Reached for instance if directory of port file does not exist
108            Log.error("Port file inaccessable: " + e);
109            throw e;
110        }
111        logfile = Util.extractStringOption("logfile", serverConf, portfileName + ".javaclog");
112        stdouterrfile = Util.extractStringOption("stdouterrfile", serverConf, portfileName + ".stdouterr");
113        sjavacForkCmd = Util.extractStringOption("sjavac", serverConf, "sjavac");
114        int poolsize = Util.extractIntOption("poolsize", serverConf);
115        keepalive = Util.extractIntOption("keepalive", serverConf, 120);
116
117        this.poolsize = poolsize > 0 ? poolsize : Runtime.getRuntime().availableProcessors();
118        settings = (serverConf.equals("")) ? "id="+id+",portfile="+portfileName : serverConf;
119    }
120
121    /**
122     * Hand out the server settings.
123     * @return The server settings, possibly a default value.
124     */
125    public String serverSettings() {
126        return settings;
127    }
128
129    /**
130     * Make a request to the server only to get the maximum possible heap size to use for compilations.
131     *
132     * @param port_file The port file used to synchronize creation of this server.
133     * @param id The identify of the compilation.
134     * @param out Standard out information.
135     * @param err Standard err information.
136     * @return The maximum heap size in bytes.
137     */
138    @Override
139    public SysInfo getSysInfo() {
140        try (Socket socket = tryConnect()) {
141            // The ObjectInputStream constructor will block until the
142            // corresponding ObjectOutputStream has written and flushed the
143            // header, so it is important that the ObjectOutputStreams on server
144            // and client are opened before the ObjectInputStreams.
145            ObjectOutputStream oos = new ObjectOutputStream(socket.getOutputStream());
146            ObjectInputStream ois = new ObjectInputStream(socket.getInputStream());
147            oos.writeObject(id);
148            oos.writeObject(SjavacServer.CMD_SYS_INFO);
149            oos.flush();
150            return (SysInfo) ois.readObject();
151        } catch (IOException | ClassNotFoundException ex) {
152            Log.error("[CLIENT] Exception caught: " + ex);
153            Log.debug(Util.getStackTrace(ex));
154        } catch (InterruptedException ie) {
155            Thread.currentThread().interrupt(); // Restore interrupt
156            Log.error("[CLIENT] getSysInfo interrupted.");
157            Log.debug(Util.getStackTrace(ie));
158        }
159        return null;
160    }
161
162    @Override
163    public CompilationResult compile(String protocolId,
164                                     String invocationId,
165                                     String[] args,
166                                     List<File> explicitSources,
167                                     Set<URI> sourcesToCompile,
168                                     Set<URI> visibleSources) {
169        CompilationResult result;
170        try (Socket socket = tryConnect()) {
171            // The ObjectInputStream constructor will block until the
172            // corresponding ObjectOutputStream has written and flushed the
173            // header, so it is important that the ObjectOutputStreams on server
174            // and client are opened before the ObjectInputStreams.
175            ObjectOutputStream oos = new ObjectOutputStream(socket.getOutputStream());
176            ObjectInputStream ois = new ObjectInputStream(socket.getInputStream());
177            oos.writeObject(id);
178            oos.writeObject(SjavacServer.CMD_COMPILE);
179            oos.writeObject(protocolId);
180            oos.writeObject(invocationId);
181            oos.writeObject(args);
182            oos.writeObject(explicitSources);
183            oos.writeObject(sourcesToCompile);
184            oos.writeObject(visibleSources);
185            oos.flush();
186            result = (CompilationResult) ois.readObject();
187        } catch (IOException | ClassNotFoundException ex) {
188            Log.error("[CLIENT] Exception caught: " + ex);
189            result = new CompilationResult(CompilationResult.ERROR_FATAL);
190            result.stderr = Util.getStackTrace(ex);
191        } catch (InterruptedException ie) {
192            Thread.currentThread().interrupt(); // Restore interrupt
193            Log.error("[CLIENT] compile interrupted.");
194            result = new CompilationResult(CompilationResult.ERROR_FATAL);
195            result.stderr = Util.getStackTrace(ie);
196        }
197        return result;
198    }
199
200    /*
201     * Makes MAX_CONNECT_ATTEMPTS attepmts to connect to server.
202     */
203    private Socket tryConnect() throws IOException, InterruptedException {
204        makeSureServerIsRunning(portFile);
205        int attempt = 0;
206        while (true) {
207            Log.info("Trying to connect. Attempt " + (++attempt) + " of " + MAX_CONNECT_ATTEMPTS);
208            try {
209                return makeConnectionAttempt();
210            } catch (IOException ex) {
211                Log.error("Connection attempt failed: " + ex.getMessage());
212                if (attempt >= MAX_CONNECT_ATTEMPTS) {
213                    Log.error("Giving up");
214                    throw new IOException("Could not connect to server", ex);
215                }
216            }
217            Thread.sleep(WAIT_BETWEEN_CONNECT_ATTEMPTS);
218        }
219    }
220
221    private Socket makeConnectionAttempt() throws IOException {
222        Socket socket = new Socket();
223        InetAddress localhost = InetAddress.getByName(null);
224        InetSocketAddress address = new InetSocketAddress(localhost, portFile.getPort());
225        socket.connect(address, CONNECTION_TIMEOUT);
226        Log.info("Connected");
227        return socket;
228    }
229
230    /*
231     * Will return immediately if a server already seems to be running,
232     * otherwise fork a new server and block until it seems to be running.
233     */
234    private void makeSureServerIsRunning(PortFile portFile)
235            throws IOException, InterruptedException {
236
237        portFile.lock();
238        portFile.getValues();
239        portFile.unlock();
240
241        if (portFile.containsPortInfo()) {
242            // Server seems to already be running
243            return;
244        }
245
246        // Fork a new server and wait for it to start
247        SjavacClient.fork(sjavacForkCmd,
248                          portFile,
249                          logfile,
250                          poolsize,
251                          keepalive,
252                          System.err,
253                          stdouterrfile);
254    }
255
256    @Override
257    public void shutdown() {
258        // Nothing to clean up
259    }
260
261    /*
262     * Fork a server process process and wait for server to come around
263     */
264    public static void fork(String sjavacCmd,
265                            PortFile portFile,
266                            String logfile,
267                            int poolsize,
268                            int keepalive,
269                            final PrintStream err,
270                            String stdouterrfile)
271                                    throws IOException, InterruptedException {
272        List<String> cmd = new ArrayList<>();
273        cmd.addAll(Arrays.asList(OptionHelper.unescapeCmdArg(sjavacCmd).split(" ")));
274        cmd.add("--startserver:"
275              + "portfile=" + portFile.getFilename()
276              + ",logfile=" + logfile
277              + ",stdouterrfile=" + stdouterrfile
278              + ",poolsize=" + poolsize
279              + ",keepalive="+ keepalive);
280
281        Process p = null;
282        Log.info("Starting server. Command: " + String.join(" ", cmd));
283        try {
284            // If the cmd for some reason can't be executed (file not found, or
285            // is not executable) this will throw an IOException with a decent
286            // error message.
287            p = new ProcessBuilder(cmd)
288                        .redirectErrorStream(true)
289                        .redirectOutput(new File(stdouterrfile))
290                        .start();
291
292            // Throws an IOException if no valid values materialize
293            portFile.waitForValidValues();
294
295        } catch (IOException ex) {
296            // Log and rethrow exception
297            Log.error("Faild to launch server.");
298            Log.error("    Message: " + ex.getMessage());
299            String rc = p == null || p.isAlive() ? "n/a" : "" + p.exitValue();
300            Log.error("    Server process exit code: " + rc);
301            Log.error("Server log:");
302            Log.error("------- Server log start -------");
303            try (Scanner s = new Scanner(new File(stdouterrfile))) {
304                while (s.hasNextLine())
305                    Log.error(s.nextLine());
306            }
307            Log.error("------- Server log end ---------");
308            throw ex;
309        }
310    }
311}
312