-
Notifications
You must be signed in to change notification settings - Fork 279
Expand file tree
/
Copy pathSonarRunnerBuilder.java
More file actions
435 lines (377 loc) · 14.5 KB
/
SonarRunnerBuilder.java
File metadata and controls
435 lines (377 loc) · 14.5 KB
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
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
/*
* SonarQube Scanner for Jenkins
* Copyright (C) 2007-2025 SonarSource Sàrl
* 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 hudson.plugins.sonar;
import com.google.common.annotations.VisibleForTesting;
import edu.umd.cs.findbugs.annotations.CheckForNull;
import edu.umd.cs.findbugs.annotations.NonNull;
import edu.umd.cs.findbugs.annotations.Nullable;
import hudson.AbortException;
import hudson.EnvVars;
import hudson.Extension;
import hudson.FilePath;
import hudson.Launcher;
import hudson.Util;
import hudson.model.AbstractBuild;
import hudson.model.AbstractProject;
import hudson.model.Action;
import hudson.model.BuildListener;
import hudson.model.Computer;
import hudson.model.JDK;
import hudson.model.Run;
import hudson.model.TaskListener;
import hudson.plugins.sonar.action.SonarMarkerAction;
import hudson.plugins.sonar.client.HttpClient;
import hudson.plugins.sonar.client.OkHttpClientSingleton;
import hudson.plugins.sonar.utils.BuilderUtils;
import hudson.plugins.sonar.utils.ExtendedArgumentListBuilder;
import hudson.plugins.sonar.utils.JenkinsRouter;
import hudson.plugins.sonar.utils.Logger;
import hudson.plugins.sonar.utils.SonarUtils;
import hudson.tasks.BuildStepDescriptor;
import hudson.tasks.Builder;
import hudson.util.ArgumentListBuilder;
import java.io.IOException;
import java.io.StringReader;
import java.util.Map.Entry;
import java.util.Properties;
import jenkins.model.Jenkins;
import org.apache.commons.lang3.StringUtils;
import org.kohsuke.stapler.DataBoundConstructor;
import org.kohsuke.stapler.DataBoundSetter;
/**
* @since 1.7
*/
public class SonarRunnerBuilder extends Builder {
/**
* Identifies {@link SonarInstallation} to be used.
*/
private String installationName;
private String project;
private String properties;
private String javaOpts;
private String additionalArguments;
/**
* Identifies {@link JDK} to be used.
* Null if no explicit configuration is required.
*
* <p>
* Can't store {@link JDK} directly because {@link jenkins.model.Jenkins} and {@link hudson.model.Project}
* are saved independently.
*
* @see jenkins.model.Jenkins#getJDK(String)
*/
private String jdk;
/**
* Identifies {@link SonarRunnerInstallation} to be used.
* @since 2.5
*/
private String sonarScannerName;
@DataBoundConstructor
public SonarRunnerBuilder() {
// all fields are optional
}
/**
* @deprecated We're moving to using @DataBoundSetter instead and a much leaner @DataBoundConstructor
*/
@Deprecated
public SonarRunnerBuilder(String installationName, String sonarScannerName, String project, String properties, String javaOpts, String jdk,
String additionalArguments) {
this.installationName = installationName;
this.sonarScannerName = sonarScannerName;
this.javaOpts = javaOpts;
this.project = project;
this.properties = properties;
this.jdk = jdk;
this.additionalArguments = additionalArguments;
}
/**
* @return name of {@link hudson.plugins.sonar.SonarInstallation}
*/
public String getInstallationName() {
return Util.fixNull(installationName);
}
@DataBoundSetter
public void setInstallationName(String installationName) {
this.installationName = installationName;
}
/**
* @return name of {@link hudson.plugins.sonar.SonarRunnerInstallation}
*/
public String getSonarScannerName() {
return Util.fixNull(sonarScannerName);
}
@DataBoundSetter
public void setSonarScannerName(String sonarScannerName) {
this.sonarScannerName = sonarScannerName;
}
/**
* Gets the JDK that this Sonar builder is configured with, or null.
*/
@CheckForNull
public JDK getJdkFromJenkins() {
return Jenkins.get().getJDK(jdk);
}
public String getJdk() {
return jdk != null && !jdk.isEmpty() ? jdk : "(Inherit From Job)";
}
@DataBoundSetter
public void setJdk(String jdk) {
this.jdk = jdk;
}
/**
* @return path to a file with properties for project, never null
*/
public String getProject() {
return Util.fixNull(project);
}
@DataBoundSetter
public void setProject(String project) {
this.project = project;
}
/**
* @return additional properties, never null
*/
public String getProperties() {
return Util.fixNull(properties);
}
@DataBoundSetter
public void setProperties(String properties) {
this.properties = properties;
}
/**
* @return Java options, never null
*/
public String getJavaOpts() {
return Util.fixNull(javaOpts);
}
@DataBoundSetter
public void setJavaOpts(String javaOpts) {
this.javaOpts = javaOpts;
}
public String getAdditionalArguments() {
return Util.fixNull(additionalArguments);
}
@DataBoundSetter
public void setAdditionalArguments(String additionalArguments) {
this.additionalArguments = additionalArguments;
}
public SonarInstallation getSonarInstallation() {
return SonarInstallation.get(getInstallationName());
}
@Override
public DescriptorImpl getDescriptor() {
return (DescriptorImpl) super.getDescriptor();
}
public SonarRunnerInstallation getSonarRunnerInstallation() {
for (SonarRunnerInstallation sri : getDescriptor().getSonarRunnerInstallations()) {
if (sonarScannerName != null && sonarScannerName.equals(sri.getName())) {
return sri;
}
}
// If no installation match then take the first one
if (getDescriptor().getSonarRunnerInstallations().length > 0) {
return getDescriptor().getSonarRunnerInstallations()[0];
}
return null;
}
@Override
public boolean perform(AbstractBuild<?, ?> build, Launcher launcher, BuildListener listener) throws InterruptedException, IOException {
FilePath workspace = build.getWorkspace();
if (workspace == null) {
throw new AbortException("no workspace for " + build);
}
perform(build, workspace, launcher, listener);
return true;
}
private void perform(Run<?, ?> run, FilePath workspace, Launcher launcher, TaskListener listener) throws InterruptedException, IOException {
if (!SonarInstallation.isValid(getInstallationName(), listener)) {
throw new AbortException("Invalid SonarQube server installation");
}
ArgumentListBuilder args = new ArgumentListBuilder();
EnvVars env = BuilderUtils.getEnvAndBuildVars(run, listener);
SonarRunnerInstallation sri = getSonarRunnerInstallation();
if (sri == null) {
// No idea if the path contains old sonar-runner or new sonar-scanner, so prefer the new one
args.add(launcher.isUnix() ? "sonar-scanner" : "sonar-scanner.bat");
} else {
sri = BuilderUtils.getBuildTool(sri, env, listener, workspace);
String exe = sri.getExecutable(launcher);
if (exe == null) {
Logger.printFailureMessage(listener);
String msg = Messages.SonarScanner_ExecutableNotFound(sri.getName());
listener.fatalError(msg);
throw new AbortException(msg);
}
args.add(exe);
}
SonarInstallation sonarInst = getSonarInstallation();
addAdditionalArguments(args, sonarInst);
ExtendedArgumentListBuilder argsBuilder = new ExtendedArgumentListBuilder(args, launcher.isUnix());
populateConfiguration(argsBuilder, run, workspace, listener, env, sonarInst, new HttpClient(OkHttpClientSingleton.getInstance()));
// Java
computeJdkToUse(run, workspace, listener, env);
// Java options
env.put("SONAR_SCANNER_OPTS", getJavaOpts());
// For backward compatibility with old sonar-runner
env.put("SONAR_RUNNER_OPTS", getJavaOpts());
long startTime = System.currentTimeMillis();
int exitCode;
try {
exitCode = executeSonarQubeScanner(run, workspace, launcher, listener, args, env);
} catch (IOException e) {
handleErrors(listener, sri, startTime, e);
exitCode = -1;
}
// with workflows, we don't have realtime access to build logs, so url might be null
// if the analyis doesn't succeed, it will also be null
SonarUtils.addBuildInfoTo(run, listener, workspace, sonarInst);
if (exitCode != 0) {
throw new AbortException("SonarQube scanner exited with non-zero code: " + exitCode);
}
}
private void handleErrors(TaskListener listener, @Nullable SonarRunnerInstallation sri, long startTime, IOException e) {
Logger.printFailureMessage(listener);
Util.displayIOException(e, listener);
String errorMessage = Messages.SonarScanner_ExecFailed();
if (sri == null && (System.currentTimeMillis() - startTime) < 1000 && getDescriptor().getSonarRunnerInstallations() == null) {
// looks like the user didn't configure any SonarQube Scanner installation
errorMessage += Messages.SonarScanner_GlobalConfigNeeded();
}
e.printStackTrace(listener.fatalError(errorMessage));
}
private static int executeSonarQubeScanner(Run<?, ?> build, FilePath workspace, Launcher launcher, TaskListener listener, ArgumentListBuilder args, EnvVars env)
throws IOException, InterruptedException {
return launcher.launch().cmds(args).envs(env).stdout(listener).pwd(BuilderUtils.getModuleRoot(build, workspace)).join();
}
private static AbstractProject<?, ?> getProject(Run<?, ?> run) {
AbstractProject<?, ?> project = null;
if (run instanceof AbstractBuild) {
AbstractBuild<?, ?> build = (AbstractBuild<?, ?>) run;
project = build.getProject();
}
return project;
}
private void computeJdkToUse(Run<?, ?> build, FilePath workspace, TaskListener listener, EnvVars env) throws IOException, InterruptedException {
JDK jdkToUse = getJdkToUse(getProject(build));
if (jdkToUse != null) {
Computer computer = workspace.toComputer();
// just in case we are not in a build
if (computer != null) {
jdkToUse = jdkToUse.forNode(computer.getNode(), listener);
}
jdkToUse.buildEnvVars(env);
}
}
@VisibleForTesting
void addAdditionalArguments(ArgumentListBuilder args, SonarInstallation inst) {
args.addTokenized(inst.getAdditionalProperties());
args.add(inst.getAdditionalAnalysisPropertiesUnix());
args.addTokenized(additionalArguments);
}
@VisibleForTesting
void populateConfiguration(ExtendedArgumentListBuilder args, Run<?, ?> build, FilePath workspace,
TaskListener listener, EnvVars env, @Nullable SonarInstallation si, HttpClient client) throws IOException, InterruptedException {
if (si != null) {
args.append("sonar.host.url", si.getServerUrl());
String token = si.getServerAuthenticationToken(build);
if (StringUtils.isNotBlank(token)) {
args.appendMasked(SonarUtils.getTokenProperty(si, client), token);
}
}
// Project properties
if (StringUtils.isNotBlank(getProject())) {
String projectSettingsFile = env.expand(getProject());
FilePath projectSettingsFilePath = BuilderUtils.getModuleRoot(build, workspace).child(projectSettingsFile);
if (!projectSettingsFilePath.exists()) {
// because of the poor choice of getModuleRoot() with CVS/Subversion, people often get confused
// with where the build file path is relative to. Now it's too late to change this behavior
// due to compatibility issue, but at least we can make this less painful by looking for errors
// and diagnosing it nicely. See HUDSON-1782
// first check if this appears to be a valid relative path from workspace root
FilePath projectSettingsFilePath2 = workspace.child(projectSettingsFile);
if (projectSettingsFilePath2.exists()) {
// This must be what the user meant. Let it continue.
projectSettingsFilePath = projectSettingsFilePath2;
} else {
// neither file exists. So this now really does look like an error.
String msg = "Unable to find SonarQube project settings at " + projectSettingsFilePath;
listener.fatalError(msg);
throw new AbortException(msg);
}
}
args.append("project.settings", projectSettingsFilePath.getRemote());
}
// Additional properties
Properties p = new Properties();
p.load(new StringReader(env.expand(getProperties())));
loadProperties(args, p);
if (!p.containsKey("sonar.projectBaseDir")) {
FilePath moduleRoot = BuilderUtils.getModuleRoot(build, workspace);
args.append("sonar.projectBaseDir", moduleRoot.getRemote());
}
}
private static void loadProperties(ExtendedArgumentListBuilder args, Properties p) {
for (Entry<Object, Object> entry : p.entrySet()) {
args.append(entry.getKey().toString(), entry.getValue().toString());
}
}
/**
* @return JDK to be used with this project.
*/
private JDK getJdkToUse(@Nullable AbstractProject<?, ?> project) {
JDK jdkToUse = getJdkFromJenkins();
if (jdkToUse == null && project != null) {
jdkToUse = project.getJDK();
}
return jdkToUse;
}
@Override
public Action getProjectAction(AbstractProject<?, ?> project) {
return new SonarMarkerAction();
}
@Extension
public static final class DescriptorImpl extends BuildStepDescriptor<Builder> {
// Used in jelly configuration for conditional display of the UI
public static final boolean BEFORE_V2 = JenkinsRouter.BEFORE_V2;
public String getGlobalToolConfigUrl() {
return JenkinsRouter.getGlobalToolConfigUrl();
}
/**
* This method is used in UI, so signature and location of this method is important.
*
* @return all configured {@link hudson.plugins.sonar.SonarInstallation}
*/
public SonarInstallation[] getSonarInstallations() {
return SonarInstallation.all();
}
@Override
public boolean isApplicable(Class<? extends AbstractProject> jobType) {
return true;
}
@NonNull
@Override
public String getDisplayName() {
return Messages.SonarScannerBuilder_DisplayName();
}
public SonarRunnerInstallation[] getSonarRunnerInstallations() {
return Jenkins.get().getDescriptorByType(SonarRunnerInstallation.DescriptorImpl.class).getInstallations();
}
}
}