SjavacClient.java revision 3267:5282596d34b3
1/*
2 * Copyright (c) 2014, 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.client;
27
28import java.io.BufferedReader;
29import java.io.File;
30import java.io.IOException;
31import java.io.InputStreamReader;
32import java.io.OutputStreamWriter;
33import java.io.PrintStream;
34import java.io.PrintWriter;
35import java.io.Reader;
36import java.io.Writer;
37import java.net.InetAddress;
38import java.net.InetSocketAddress;
39import java.net.Socket;
40import java.util.ArrayList;
41import java.util.Arrays;
42import java.util.List;
43import java.util.Scanner;
44import java.util.stream.Stream;
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.CompilationSubResult;
51import com.sun.tools.sjavac.server.PortFile;
52import com.sun.tools.sjavac.server.Sjavac;
53import com.sun.tools.sjavac.server.SjavacServer;
54
55import static java.util.stream.Collectors.joining;
56
57/**
58 * Sjavac implementation that delegates requests to a SjavacServer.
59 *
60 *  <p><b>This is NOT part of any supported API.
61 *  If you write code that depends on this, you do so at your own risk.
62 *  This code and its internal interfaces are subject to change or
63 *  deletion without notice.</b>
64 */
65public class SjavacClient implements Sjavac {
66
67    // The id can perhaps be used in the future by the javac server to reuse the
68    // JavaCompiler instance for several compiles using the same id.
69    private final String id;
70    private final PortFile portFile;
71
72    // Default keepalive for server is 120 seconds.
73    // I.e. it will accept 120 seconds of inactivity before quitting.
74    private final int keepalive;
75    private final int poolsize;
76
77    // The sjavac option specifies how the server part of sjavac is spawned.
78    // If you have the experimental sjavac in your path, you are done. If not, you have
79    // to point to a com.sun.tools.sjavac.Main that supports --startserver
80    // for example by setting: sjavac=java%20-jar%20...javac.jar%com.sun.tools.sjavac.Main
81    private final String sjavacForkCmd;
82
83    // Wait 2 seconds for response, before giving up on javac server.
84    static int CONNECTION_TIMEOUT = 2000;
85    static int MAX_CONNECT_ATTEMPTS = 3;
86    static int WAIT_BETWEEN_CONNECT_ATTEMPTS = 2000;
87
88    // Store the server conf settings here.
89    private final String settings;
90
91    public SjavacClient(Options options) {
92        String tmpServerConf = options.getServerConf();
93        String serverConf = (tmpServerConf!=null)? tmpServerConf : "";
94        String tmpId = Util.extractStringOption("id", serverConf);
95        id = (tmpId!=null) ? tmpId : "id"+(((new java.util.Random()).nextLong())&Long.MAX_VALUE);
96        String defaultPortfile = options.getDestDir()
97                                        .resolve("javac_server")
98                                        .toAbsolutePath()
99                                        .toString();
100        String portfileName = Util.extractStringOption("portfile", serverConf, defaultPortfile);
101        portFile = SjavacServer.getPortFile(portfileName);
102        sjavacForkCmd = Util.extractStringOption("sjavac", serverConf, "sjavac");
103        int poolsize = Util.extractIntOption("poolsize", serverConf);
104        keepalive = Util.extractIntOption("keepalive", serverConf, 120);
105
106        this.poolsize = poolsize > 0 ? poolsize : Runtime.getRuntime().availableProcessors();
107        settings = (serverConf.equals("")) ? "id="+id+",portfile="+portfileName : serverConf;
108    }
109
110    /**
111     * Hand out the server settings.
112     * @return The server settings, possibly a default value.
113     */
114    public String serverSettings() {
115        return settings;
116    }
117
118    @Override
119    public int compile(String[] args) {
120        int result = -1;
121        try (Socket socket = tryConnect()) {
122            PrintWriter out = new PrintWriter(new OutputStreamWriter(socket.getOutputStream()));
123            BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
124
125            // Send args array to server
126            out.println(args.length);
127            for (String arg : args)
128                out.println(arg);
129            out.flush();
130
131            // Read server response line by line
132            String line;
133            while (null != (line = in.readLine())) {
134                if (!line.contains(":")) {
135                    throw new AssertionError("Could not parse protocol line: >>\"" + line + "\"<<");
136                }
137                String[] typeAndContent = line.split(":", 2);
138                String type = typeAndContent[0];
139                String content = typeAndContent[1];
140
141                try {
142                    Log.log(Log.Level.valueOf(type), "[server] " + content);
143                    continue;
144                } catch (IllegalArgumentException e) {
145                    // Parsing of 'type' as log level failed.
146                }
147
148                if (type.equals(SjavacServer.LINE_TYPE_RC)) {
149                    result = Integer.parseInt(content);
150                }
151            }
152        } catch (PortFileInaccessibleException e) {
153            Log.error("Port file inaccessible.");
154            result = CompilationSubResult.ERROR_FATAL;
155        } catch (IOException ioe) {
156            Log.error("IOException caught during compilation: " + ioe.getMessage());
157            Log.debug(ioe);
158            result = CompilationSubResult.ERROR_FATAL;
159        } catch (InterruptedException ie) {
160            Thread.currentThread().interrupt(); // Restore interrupt
161            Log.error("Compilation interrupted.");
162            Log.debug(ie);
163            result = CompilationSubResult.ERROR_FATAL;
164        }
165        return result;
166    }
167
168    /*
169     * Makes MAX_CONNECT_ATTEMPTS attepmts to connect to server.
170     */
171    private Socket tryConnect() throws IOException, InterruptedException {
172        makeSureServerIsRunning(portFile);
173        int attempt = 0;
174        while (true) {
175            Log.info("Trying to connect. Attempt " + (++attempt) + " of " + MAX_CONNECT_ATTEMPTS);
176            try {
177                return makeConnectionAttempt();
178            } catch (IOException ex) {
179                Log.error("Connection attempt failed: " + ex.getMessage());
180                if (attempt >= MAX_CONNECT_ATTEMPTS) {
181                    Log.error("Giving up");
182                    throw new IOException("Could not connect to server", ex);
183                }
184            }
185            Thread.sleep(WAIT_BETWEEN_CONNECT_ATTEMPTS);
186        }
187    }
188
189    private Socket makeConnectionAttempt() throws IOException {
190        Socket socket = new Socket();
191        InetAddress localhost = InetAddress.getByName(null);
192        InetSocketAddress address = new InetSocketAddress(localhost, portFile.getPort());
193        socket.connect(address, CONNECTION_TIMEOUT);
194        Log.info("Connected");
195        return socket;
196    }
197
198    /*
199     * Will return immediately if a server already seems to be running,
200     * otherwise fork a new server and block until it seems to be running.
201     */
202    private void makeSureServerIsRunning(PortFile portFile)
203            throws IOException, InterruptedException {
204
205        if (portFile.exists()) {
206            portFile.lock();
207            portFile.getValues();
208            portFile.unlock();
209
210            if (portFile.containsPortInfo()) {
211                // Server seems to already be running
212                return;
213            }
214        }
215
216        // Fork a new server and wait for it to start
217        SjavacClient.fork(sjavacForkCmd,
218                          portFile,
219                          poolsize,
220                          keepalive);
221    }
222
223    @Override
224    public void shutdown() {
225        // Nothing to clean up
226    }
227
228    /*
229     * Fork a server process process and wait for server to come around
230     */
231    public static void fork(String sjavacCmd, PortFile portFile, int poolsize, int keepalive)
232            throws IOException, InterruptedException {
233        List<String> cmd = new ArrayList<>();
234        cmd.addAll(Arrays.asList(OptionHelper.unescapeCmdArg(sjavacCmd).split(" ")));
235        cmd.add("--startserver:"
236              + "portfile=" + portFile.getFilename()
237              + ",poolsize=" + poolsize
238              + ",keepalive="+ keepalive);
239
240        Process serverProcess;
241        Log.info("Starting server. Command: " + String.join(" ", cmd));
242        try {
243            // If the cmd for some reason can't be executed (file is not found,
244            // or is not executable for instance) this will throw an
245            // IOException and p == null.
246            serverProcess = new ProcessBuilder(cmd)
247                    .redirectErrorStream(true)
248                    .start();
249        } catch (IOException ex) {
250            // Message is typically something like:
251            // Cannot run program "xyz": error=2, No such file or directory
252            Log.error("Failed to create server process: " + ex.getMessage());
253            Log.debug(ex);
254            throw new IOException(ex);
255        }
256
257        // serverProcess != null at this point.
258        try {
259            // Throws an IOException if no valid values materialize
260            portFile.waitForValidValues();
261        } catch (IOException ex) {
262            // Process was started, but server failed to initialize. This could
263            // for instance be due to the JVM not finding the server class,
264            // or the server running in to some exception early on.
265            Log.error("Sjavac server failed to initialize: " + ex.getMessage());
266            Log.error("Process output:");
267            Reader serverStdoutStderr = new InputStreamReader(serverProcess.getInputStream());
268            try (BufferedReader br = new BufferedReader(serverStdoutStderr)) {
269                br.lines().forEach(Log::error);
270            }
271            Log.error("<End of process output>");
272            try {
273                Log.error("Process exit code: " + serverProcess.exitValue());
274            } catch (IllegalThreadStateException e) {
275                // Server is presumably still running.
276            }
277            throw new IOException("Server failed to initialize: " + ex.getMessage(), ex);
278        }
279    }
280}
281