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