-
Notifications
You must be signed in to change notification settings - Fork 176
/
NodeCommandBuilderImpl.java
315 lines (282 loc) · 10.4 KB
/
NodeCommandBuilderImpl.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
/*
* SonarQube JavaScript Plugin
* Copyright (C) 2011-2024 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.plugins.javascript.nodejs;
import static java.util.Arrays.asList;
import static java.util.Collections.emptyMap;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.attribute.PosixFilePermission;
import java.util.ArrayList;
import java.util.EnumSet;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.function.Consumer;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.sonar.api.config.Configuration;
import org.sonar.api.utils.Version;
import org.sonar.api.utils.log.Logger;
import org.sonar.api.utils.log.Loggers;
import org.sonar.plugins.javascript.bridge.EmbeddedNode;
public class NodeCommandBuilderImpl implements NodeCommandBuilder {
private static final Logger LOG = Loggers.get(NodeCommandBuilderImpl.class);
public static final String NODE_EXECUTABLE_DEFAULT = "node";
private static final String NODE_EXECUTABLE_DEFAULT_MACOS =
"package/node_modules/run-node/run-node";
public static final String NODE_EXECUTABLE_PROPERTY = "sonar.nodejs.executable";
private static final String NODE_FORCE_HOST_PROPERTY = "sonar.nodejs.forceHost";
private static final Pattern NODEJS_VERSION_PATTERN = Pattern.compile(
"v?(\\d+)\\.(\\d+)\\.(\\d+)"
);
private final ProcessWrapper processWrapper;
private EmbeddedNode embeddedNode;
private Version minNodeVersion;
private Configuration configuration;
private List<String> args = new ArrayList<>();
private List<String> nodeJsArgs = new ArrayList<>();
private Consumer<String> outputConsumer = LOG::info;
private Consumer<String> errorConsumer = LOG::error;
private String scriptFilename;
private BundlePathResolver pathResolver;
private Version actualNodeVersion;
private Map<String, String> env = Map.of();
public NodeCommandBuilderImpl(ProcessWrapper processWrapper) {
this.processWrapper = processWrapper;
}
@Override
public NodeCommandBuilder minNodeVersion(Version minNodeVersion) {
this.minNodeVersion = minNodeVersion;
return this;
}
@Override
public NodeCommandBuilder configuration(Configuration configuration) {
this.configuration = configuration;
return this;
}
@Override
public NodeCommandBuilder maxOldSpaceSize(int maxOldSpaceSize) {
nodeJsArgs("--max-old-space-size=" + maxOldSpaceSize);
LOG.info("Configured Node.js --max-old-space-size={}.", maxOldSpaceSize);
return this;
}
@Override
public NodeCommandBuilder nodeJsArgs(String... nodeJsArgs) {
this.nodeJsArgs.addAll(asList(nodeJsArgs));
return this;
}
@Override
public NodeCommandBuilder script(String scriptFilename) {
this.scriptFilename = scriptFilename;
return this;
}
@Override
public NodeCommandBuilder scriptArgs(String... args) {
this.args = asList(args);
return this;
}
@Override
public NodeCommandBuilder outputConsumer(Consumer<String> consumer) {
this.outputConsumer = consumer;
return this;
}
@Override
public NodeCommandBuilder errorConsumer(Consumer<String> consumer) {
this.errorConsumer = consumer;
return this;
}
@Override
public NodeCommandBuilder pathResolver(BundlePathResolver pathResolver) {
this.pathResolver = pathResolver;
return this;
}
@Override
public NodeCommandBuilder env(Map<String, String> env) {
this.env = Map.copyOf(env);
return this;
}
@Override
public NodeCommandBuilder embeddedNode(EmbeddedNode embeddedNode) {
this.embeddedNode = embeddedNode;
return this;
}
/**
* Retrieves node executable from sonar.node.executable property or using default if absent.
* Then will check Node.js version by running {@code node -v}, then
* returns {@link NodeCommand} instance.
*
* @throws NodeCommandException when actual Node.js version doesn't satisfy minimum version requested,
* or if failed to run {@code node -v}
*/
@Override
public NodeCommand build() throws NodeCommandException, IOException {
String nodeExecutable = retrieveNodeExecutable(configuration);
checkNodeCompatibility(nodeExecutable);
if (nodeJsArgs.isEmpty() && scriptFilename == null && args.isEmpty()) {
throw new IllegalArgumentException("Missing arguments for Node.js.");
}
if (scriptFilename == null && !args.isEmpty()) {
throw new IllegalArgumentException("No script provided, but script arguments found.");
}
return new NodeCommand(
processWrapper,
nodeExecutable,
actualNodeVersion,
nodeJsArgs,
scriptFilename,
args,
outputConsumer,
errorConsumer,
env
);
}
private void checkNodeCompatibility(String nodeExecutable) throws NodeCommandException {
if (minNodeVersion == null) {
return;
}
LOG.debug("Checking Node.js version");
String versionString = NodeVersion.getVersion(processWrapper, nodeExecutable);
actualNodeVersion = nodeVersion(versionString);
if (!actualNodeVersion.isGreaterThanOrEqual(minNodeVersion)) {
throw new NodeCommandException(
String.format(
"Only Node.js v%s or later is supported, got %s.",
minNodeVersion,
actualNodeVersion
)
);
}
LOG.debug("Using Node.js {}.", versionString);
}
// Visible for testing
static Version nodeVersion(String versionString) throws NodeCommandException {
Matcher versionMatcher = NODEJS_VERSION_PATTERN.matcher(versionString);
if (versionMatcher.lookingAt()) {
return Version.create(
Integer.parseInt(versionMatcher.group(1)),
Integer.parseInt(versionMatcher.group(2)),
Integer.parseInt(versionMatcher.group(3))
);
} else {
throw new NodeCommandException(
"Failed to parse Node.js version, got '" + versionString + "'"
);
}
}
/**
* Finds a node runtime by looking into:
* 1. sonar.nodejs.executable
* 2. an embedded runtime bundled with the analyzer
* 3. a runtime on the host
* If sonar.nodejs.forceHost is enabled, 2. is ignored
*
* @param configuration
* @return
* @throws NodeCommandException
* @throws IOException
*/
private String retrieveNodeExecutable(Configuration configuration)
throws NodeCommandException, IOException {
if (configuration.hasKey(NODE_EXECUTABLE_PROPERTY)) {
String nodeExecutable = configuration.get(NODE_EXECUTABLE_PROPERTY).get();
File file = new File(nodeExecutable);
if (file.exists()) {
LOG.info(
"Using Node.js executable {} from property {}.",
file.getAbsoluteFile(),
NODE_EXECUTABLE_PROPERTY
);
return nodeExecutable;
} else {
LOG.error(
"Provided Node.js executable file does not exist. Property '{}' was set to '{}'",
NODE_EXECUTABLE_PROPERTY,
nodeExecutable
);
throw new NodeCommandException("Provided Node.js executable file does not exist.");
}
}
return locateNode(isForceHost(configuration));
}
private String locateNode(boolean isForceHost) throws IOException {
var defaultNode = NODE_EXECUTABLE_DEFAULT;
if (embeddedNode.isAvailable() && !isForceHost) {
LOG.info("Using embedded Node.js runtime");
defaultNode = embeddedNode.binary().toString();
} else if (processWrapper.isMac()) {
defaultNode = locateNodeOnMac();
} else if (processWrapper.isWindows()) {
defaultNode = locateNodeOnWindows();
}
LOG.info("Using Node.js executable: '{}'.", defaultNode);
return defaultNode;
}
private static boolean isForceHost(Configuration configuration) {
return configuration.getBoolean(NODE_FORCE_HOST_PROPERTY).orElse(false);
}
private String locateNodeOnMac() throws IOException {
// on Mac when e.g. IntelliJ is launched from dock, node will often not be available via PATH, because PATH is configured
// in .bashrc or similar, thus we launch node via 'run-node', which should load required configuration
LOG.debug("Looking for Node.js in the PATH using run-node (macOS)");
String defaultNode = pathResolver.resolve(NODE_EXECUTABLE_DEFAULT_MACOS);
File file = new File(defaultNode);
if (!file.exists()) {
LOG.error(
"Default Node.js executable for MacOS does not exist. Value '{}'. Consider setting Node.js location through property '{}'",
defaultNode,
NODE_EXECUTABLE_PROPERTY
);
throw new NodeCommandException("Default Node.js executable for MacOS does not exist.");
} else {
Files.setPosixFilePermissions(
file.toPath(),
EnumSet.of(PosixFilePermission.OWNER_EXECUTE, PosixFilePermission.OWNER_READ)
);
}
return defaultNode;
}
private String locateNodeOnWindows() throws IOException {
// Windows will search current directory in addition to the PATH variable, which is unsecure.
// To avoid it we use where.exe to find node binary only in PATH. See SSF-181
LOG.debug("Looking for Node.js in the PATH using where.exe (Windows)");
List<String> stdOut = new ArrayList<>();
Process whereTool = processWrapper.startProcess(
asList("C:\\Windows\\System32\\where.exe", "$PATH:node.exe"),
emptyMap(),
stdOut::add,
LOG::error
);
try {
processWrapper.waitFor(whereTool, 5, TimeUnit.SECONDS);
if (!stdOut.isEmpty()) {
String out = stdOut.get(0);
LOG.debug("Found node.exe at {}", out);
return out;
}
} catch (InterruptedException e) {
processWrapper.interrupt();
LOG.error("Interrupted while waiting for 'where.exe' to terminate.");
}
throw new NodeCommandException(
"Node.js not found in PATH. PATH value was: " + processWrapper.getenv("PATH")
);
}
}