JAL-4373 Setting the jvmmempc and jvmmemmax strings from the Arg.getName() for consis...
[jalview.git] / src / jalview / bin / Launcher.java
1 /*
2  * Jalview - A Sequence Alignment Editor and Viewer ($$Version-Rel$$)
3  * Copyright (C) $$Year-Rel$$ The Jalview Authors
4  * 
5  * This file is part of Jalview.
6  * 
7  * Jalview is free software: you can redistribute it and/or
8  * modify it under the terms of the GNU General Public License 
9  * as published by the Free Software Foundation, either version 3
10  * of the License, or (at your option) any later version.
11  *  
12  * Jalview is distributed in the hope that it will be useful, but 
13  * WITHOUT ANY WARRANTY; without even the implied warranty 
14  * of MERCHANTABILITY or FITNESS FOR A PARTICULAR 
15  * PURPOSE.  See the GNU General Public License for more details.
16  * 
17  * You should have received a copy of the GNU General Public License
18  * along with Jalview.  If not, see <http://www.gnu.org/licenses/>.
19  * The Jalview Authors are detailed in the 'AUTHORS' file.
20  */
21 package jalview.bin;
22
23 import java.io.File;
24 import java.io.IOException;
25 import java.lang.management.ManagementFactory;
26 import java.util.ArrayList;
27 import java.util.List;
28 import java.util.Locale;
29 import java.util.concurrent.TimeUnit;
30
31 import jalview.bin.argparser.Arg;
32 import jalview.util.ChannelProperties;
33 import jalview.util.LaunchUtils;
34
35 /**
36  * A Launcher class for Jalview. This class is used to launch Jalview from the
37  * shadowJar when Getdown is not used or available. It attempts to take all the
38  * command line arguments to pass on to the jalview.bin.Jalview class, but to
39  * insert a -Xmx memory setting to a sensible default, using the --jvmmempc and
40  * -jvmmemmax application arguments if specified. If not specified then system
41  * properties will be looked for by jalview.bin.MemorySetting. If the user has
42  * provided the JVM with a -Xmx setting directly and not set --jvmmempc or
43  * --jvmmemmax then this setting will be used and system properties ignored. If
44  * -Xmx is set as well as --jvmmempc or --jvmmemmax as argument(s) then the -Xmx
45  * argument will NOT be passed on to the main application launch.
46  * 
47  * @author bsoares
48  *
49  */
50 public class Launcher
51 {
52   private final static String startClass = "jalview.bin.Jalview";
53
54   // not setting this yet due to problem with Jmol
55   private final static String headlessProperty = "java.awt.headless";
56
57   // used for headless macOS
58   private final static String macosHeadlessProperty = "apple.awt.UIElement";
59
60   // arguments that assume headless mode
61   private final static String[] assumeHeadlessArgs = { "headless", "output",
62       "image", "structureimage" };
63
64   /**
65    * main method for jalview.bin.Launcher. This restarts the same JRE's JVM with
66    * the same arguments but with memory adjusted based on extracted --jvmmempc
67    * and --jvmmemmax application arguments. If on a Mac then extra dock:icon and
68    * dock:name arguments are also set.
69    * 
70    * @param args
71    */
72   public static void main(String[] args)
73   {
74     if (!LaunchUtils.checkJavaVersion())
75     {
76       jalview.bin.Console
77               .errPrintln("WARNING - The Java version being used (Java "
78                       + LaunchUtils.getJavaVersion()
79                       + ") may lead to problems. This installation of Jalview should be used with Java "
80                       + LaunchUtils.getJavaCompileVersion() + ".");
81     }
82
83     String jvmmempc = null;
84     String jvmmemmax = null;
85     boolean debug = false;
86     boolean wait = true;
87     boolean quiet = false;
88     boolean headless = false;
89     boolean assumeheadless = false;
90     boolean gui = false;
91     boolean help = false;
92     boolean stdout = false;
93     // must set --debug before --launcher...
94     boolean launcherstop = false;
95     boolean launcherprint = false;
96     boolean launcherwait = false;
97     ArrayList<String> arguments = new ArrayList<>();
98     String previousArg = null;
99     // set debug first
100     for (String arg : args)
101     {
102       if (arg.equals("--debug"))
103       {
104         debug = true;
105       }
106     }
107     for (String arg : args)
108     {
109       if (arg.equals("--quiet"))
110       {
111         quiet = true;
112       }
113       else if (arg.equals("--gui"))
114       {
115         gui = true;
116       }
117       else if (arg.equals("--help"))
118       {
119         help = true;
120       }
121       else if (arg.equals("--version"))
122       {
123         help = true;
124       }
125
126       if (!assumeheadless)
127       {
128         for (String a : assumeHeadlessArgs)
129         {
130           if (arg.equals("--" + a) || arg.startsWith("--" + a + "="))
131           {
132             assumeheadless = true;
133           }
134         }
135       }
136
137       if (arg.equals("--output=-")
138               || (arg.equals("-") && "--output".equals(previousArg)))
139       {
140         stdout = true;
141       }
142
143       if (debug)
144       {
145         if (arg.equals("--launcherprint"))
146         {
147           launcherprint = true;
148         }
149         else if (arg.equals("--launcherstop"))
150         {
151           launcherstop = true;
152         }
153         else if (arg.equals("--launcherwait"))
154         {
155           launcherwait = true;
156         }
157         else
158         // this ends the launcher immediately
159         if (arg.equals("--launchernowait"))
160         {
161           wait = false;
162         }
163       }
164       previousArg = arg;
165       // Don't add the --launcher... args to Jalview launch
166       if (arg.startsWith("--launcher"))
167       {
168         continue;
169       }
170       // jvmmempc and jvmmemmax args used to set memory and are not passed on to
171       // startClass
172       final String jvmmempcArg = Arg.JVMMEMPC.getName();
173       final String jvmmemmaxArg = Arg.JVMMEMMAX.getName();
174       if (arg.startsWith("-" + jvmmempcArg + "="))
175       {
176         jvmmempc = arg.substring(jvmmempcArg.length() + 2);
177       }
178       else if (arg.startsWith("-" + jvmmemmaxArg + "="))
179       {
180         jvmmemmax = arg.substring(jvmmemmaxArg.length() + 2);
181       }
182       // --doubledash versions
183       else if (arg.startsWith("--" + jvmmempcArg + "="))
184       {
185         jvmmempc = arg.substring(jvmmempcArg.length() + 3);
186       }
187       else if (arg.startsWith("--" + jvmmemmaxArg + "="))
188       {
189         jvmmemmax = arg.substring(jvmmemmaxArg.length() + 3);
190       }
191       // retain arg
192       else
193       {
194         arguments.add(arg);
195       }
196     }
197     if (help)
198     {
199       // --help takes precedence over --gui
200       headless = true;
201     }
202     else if (gui)
203     {
204       // --gui takes precedence over --headless
205       headless = false;
206     }
207     else
208     {
209       // --output arguments assume headless mode
210       headless = assumeheadless;
211     }
212
213     final String appName = ChannelProperties.getProperty("app_name");
214
215     // if we're using jalview.bin.Launcher we always assume a console is in use
216     final String javaBin = LaunchUtils.findJavaBin(true);
217
218     List<String> command = new ArrayList<>();
219     command.add(javaBin);
220
221     String memSetting = null;
222
223     for (String jvmArg : ManagementFactory.getRuntimeMXBean()
224             .getInputArguments())
225     {
226       command.add(jvmArg);
227     }
228     command.add("-cp");
229     command.add(ManagementFactory.getRuntimeMXBean().getClassPath());
230
231     // use saved preferences if no cmdline args
232     boolean useCustomisedSettings = LaunchUtils
233             .getBooleanUserPreference(MemorySetting.CUSTOMISED_SETTINGS);
234     if (useCustomisedSettings)
235     {
236       if (jvmmempc == null)
237       {
238         jvmmempc = LaunchUtils
239                 .getUserPreference(MemorySetting.MEMORY_JVMMEMPC);
240       }
241       if (jvmmemmax == null)
242       {
243         jvmmemmax = LaunchUtils
244                 .getUserPreference(MemorySetting.MEMORY_JVMMEMMAX);
245       }
246     }
247
248     // add these settings if not already specified
249     boolean memSet = false;
250     boolean dockIcon = false;
251     boolean dockName = false;
252     boolean headlessProp = false;
253     boolean macosHeadlessProp = false;
254     for (int i = 0; i < command.size(); i++)
255     {
256       String arg = command.get(i);
257       if (arg.startsWith("-Xmx"))
258       {
259         // only use -Xmx if jvmmemmax and jvmmempc have not been set
260         if (jvmmempc == null && jvmmemmax == null)
261         {
262           memSetting = arg;
263           memSet = true;
264         }
265       }
266       else if (arg.startsWith("-Xdock:icon"))
267       {
268         dockIcon = true;
269       }
270       else if (arg.startsWith("-Xdock:name"))
271       {
272         dockName = true;
273       }
274       else if (arg.startsWith("-D" + headlessProperty + "="))
275       {
276         headlessProp = true;
277       }
278       else if (arg.startsWith("-D" + macosHeadlessProperty + "="))
279       {
280         macosHeadlessProp = true;
281       }
282     }
283
284     if (!memSet)
285     {
286       long maxMemLong = MemorySetting.getMemorySetting(jvmmemmax, jvmmempc);
287
288       if (maxMemLong > 0)
289       {
290         memSetting = "-Xmx" + Long.toString(maxMemLong);
291         memSet = true;
292         command.add(memSetting);
293       }
294     }
295
296     if (LaunchUtils.isMac)
297     {
298       if (!dockIcon)
299       {
300         String dockIconPath = System.getProperty("getdownappdir", ".")
301                 + File.separator + "resource/jalview_logo.png";
302         command.add("-Xdock:icon=" + dockIconPath);
303       }
304       if (!dockName)
305       {
306         // -Xdock:name=... doesn't actually work :(
307         // Leaving it in in case it gets fixed
308         command.add("-Xdock:name=" + appName);
309         // This also does not work for the dock
310         command.add("-Dcom.apple.mrj.application.apple.menu.about.name="
311                 + appName);
312       }
313     }
314     if (headless && !headlessProp)
315     {
316       System.setProperty(headlessProperty, "true");
317       /* not setting this in java invocation of running jalview due to problem with Jmol */
318       if (help)
319       {
320         command.add("-D" + headlessProperty + "=true");
321       }
322     }
323     if (headless && LaunchUtils.isMac && !macosHeadlessProp)
324     {
325       System.setProperty(macosHeadlessProperty, "true");
326       command.add("-D" + macosHeadlessProperty + "=true");
327     }
328
329     String scalePropertyArg = HiDPISetting.getScalePropertyArg();
330     if (scalePropertyArg != null)
331     {
332       syserr(debug, quiet, "Running " + startClass + " with scale setting "
333               + scalePropertyArg);
334       command.add(scalePropertyArg);
335     }
336
337     command.add(startClass);
338     command.addAll(arguments);
339
340     final ProcessBuilder builder = new ProcessBuilder(command);
341
342     if ((Boolean.parseBoolean(System.getProperty("launcherprint", "false"))
343             || launcherprint))
344     {
345       syserr(debug, quiet,
346               "LAUNCHER COMMAND: " + String.join(" ", builder.command()));
347     }
348     syserr(debug, quiet,
349             "Running " + startClass + " with "
350                     + (memSetting == null ? "no memory setting"
351                             : ("memory setting " + memSetting)));
352
353     if (Boolean.parseBoolean(System.getProperty("launcherstop", "false"))
354             || (debug && launcherstop))
355     {
356       syserr(debug, quiet,
357               "System property 'launcherstop' is set and not 'false'. Exiting.");
358       System.exit(0);
359     }
360     try
361     {
362       builder.inheritIO();
363       Process process = builder.start();
364       if (wait || launcherwait)
365       {
366         syserr(debug, quiet, "Launching application process");
367         process.waitFor();
368       }
369       else
370       {
371         int waitInt = 0;
372         syserr(debug, quiet,
373                 "Wait time for application process is " + waitInt + "ms");
374         process.waitFor(waitInt, TimeUnit.MILLISECONDS);
375       }
376       syserr(debug, quiet, "Launcher process ending");
377     } catch (IOException e)
378     {
379       if (e.getMessage().toLowerCase(Locale.ROOT).contains("memory"))
380       {
381         jalview.bin.Console
382                 .errPrintln("Caught a memory exception: " + e.getMessage());
383         // Probably the "Cannot allocate memory" error, try without the memory
384         // setting
385         ArrayList<String> commandNoMem = new ArrayList<>();
386         for (int i = 0; i < command.size(); i++)
387         {
388           if (!command.get(i).startsWith("-Xmx"))
389           {
390             commandNoMem.add(command.get(i));
391           }
392         }
393         final ProcessBuilder builderNoMem = new ProcessBuilder(
394                 commandNoMem);
395         jalview.bin.Console.errPrintln("Command without memory setting: "
396                 + String.join(" ", builderNoMem.command()));
397         try
398         {
399           builderNoMem.inheritIO();
400           Process processNoMem = builderNoMem.start();
401           processNoMem.waitFor();
402         } catch (Exception ex)
403         {
404           ex.printStackTrace();
405         }
406       }
407       else
408       {
409         e.printStackTrace();
410       }
411     } catch (Exception e)
412     {
413       e.printStackTrace();
414     }
415   }
416
417   private static void syserr(boolean debug, boolean quiet, String message)
418   {
419     if (debug && !quiet)
420     {
421       jalview.bin.Console.errPrintln("LAUNCHERDEBUG - " + message);
422     }
423   }
424
425 }