-
Notifications
You must be signed in to change notification settings - Fork 279
Expand file tree
/
Copy pathSonarBuildWrapper.java
More file actions
329 lines (275 loc) · 11.5 KB
/
SonarBuildWrapper.java
File metadata and controls
329 lines (275 loc) · 11.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
/*
* 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.cloudbees.plugins.credentials.CredentialsMatchers;
import com.cloudbees.plugins.credentials.CredentialsProvider;
import com.cloudbees.plugins.credentials.common.StandardListBoxModel;
import com.cloudbees.plugins.credentials.common.StandardUsernameCredentials;
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.EnvVars;
import hudson.Extension;
import hudson.FilePath;
import hudson.Launcher;
import hudson.Util;
import hudson.console.ConsoleLogFilter;
import hudson.model.AbstractProject;
import hudson.model.FreeStyleProject;
import hudson.model.Item;
import hudson.model.ItemGroup;
import hudson.model.Queue;
import hudson.model.Run;
import hudson.model.TaskListener;
import hudson.model.TopLevelItem;
import hudson.model.queue.Tasks;
import hudson.plugins.sonar.action.SonarMarkerAction;
import hudson.plugins.sonar.client.HttpClient;
import hudson.plugins.sonar.client.OkHttpClientSingleton;
import hudson.plugins.sonar.utils.Logger;
import hudson.plugins.sonar.utils.MaskPasswordsOutputStream;
import hudson.plugins.sonar.utils.SonarUtils;
import hudson.security.ACL;
import hudson.tasks.BuildWrapperDescriptor;
import hudson.util.ArgumentListBuilder;
import hudson.util.FormValidation;
import hudson.util.ListBoxModel;
import java.io.IOException;
import java.io.OutputStream;
import java.io.Serializable;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import jenkins.model.Jenkins;
import jenkins.tasks.SimpleBuildWrapper;
import org.apache.commons.lang3.StringUtils;
import org.jenkinsci.Symbol;
import org.jenkinsci.plugins.plaincredentials.StringCredentials;
import org.kohsuke.stapler.AncestorInPath;
import org.kohsuke.stapler.DataBoundConstructor;
import org.kohsuke.stapler.DataBoundSetter;
import org.kohsuke.stapler.QueryParameter;
import static org.apache.commons.lang3.StringEscapeUtils.escapeJson;
public class SonarBuildWrapper extends SimpleBuildWrapper {
private String installationName;
private String credentialsId;
private boolean envOnly = false;
@DataBoundConstructor
public SonarBuildWrapper(@Nullable String installationName) {
this.installationName = installationName;
}
@CheckForNull
public String getCredentialsId() {
return credentialsId;
}
@DataBoundSetter
public void setCredentialsId(String credentialsId) {
this.credentialsId = Util.fixEmpty(credentialsId);
}
public boolean isEnvOnly() {
return envOnly;
}
@DataBoundSetter
public void setEnvOnly(boolean envOnly) {
this.envOnly = envOnly;
}
@Override
public void setUp(Context context, Run<?, ?> build, FilePath workspace, Launcher launcher, TaskListener listener, EnvVars initialEnvironment)
throws IOException, InterruptedException {
SonarInstallation.checkValid(getInstallationName());
SonarInstallation installation = SonarInstallation.get(getInstallationName());
String msg = Messages.SonarBuildWrapper_Injecting(installation.getName());
Logger.LOG.info(msg);
listener.getLogger().println(msg);
context.getEnv().putAll(createVars(installation, getCredentialsId(), initialEnvironment, build, new HttpClient(OkHttpClientSingleton.getInstance())));
if (envOnly) {
return;
}
context.setDisposer(new AddBuildInfo(installation, getCredentialsId()));
build.addAction(new SonarMarkerAction());
}
@VisibleForTesting
static Map<String, String> createVars(SonarInstallation inst, @Nullable String credentialsId, EnvVars initialEnvironment, Run<?, ?> build, HttpClient client) {
Map<String, String> map = new HashMap<>();
map.put("SONAR_CONFIG_NAME", inst.getName());
String hostUrl = getOrDefault(initialEnvironment.expand(inst.getServerUrl()), "http://localhost:9000");
map.put("SONAR_HOST_URL", hostUrl);
String token = getOrDefault(SonarUtils.getAuthenticationToken(build, inst, credentialsId), "");
map.put("SONAR_AUTH_TOKEN", token);
String mojoVersion = inst.getMojoVersion();
if (StringUtils.isEmpty(mojoVersion)) {
map.put("SONAR_MAVEN_GOAL", "sonar:sonar");
} else {
map.put("SONAR_MAVEN_GOAL", SonarUtils.getMavenGoal(mojoVersion));
}
map.put("SONAR_EXTRA_PROPS", getOrDefault(initialEnvironment.expand(getAdditionalProps(inst)), ""));
// resolve variables against each other
EnvVars.resolve(map);
StringBuilder sb = new StringBuilder();
sb.append("{ \"sonar.host.url\" : \"").append(escapeJson(hostUrl)).append("\"");
if (!token.isEmpty()) {
sb.append(", \"").append(SonarUtils.getTokenProperty(inst, client)).append("\" : \"").append(escapeJson(token)).append("\"");
}
String additionalAnalysisProperties = inst.getAdditionalAnalysisProperties();
if (additionalAnalysisProperties != null) {
for (String pair : StringUtils.split(additionalAnalysisProperties)) {
String[] keyValue = StringUtils.split(pair, "=");
if (keyValue.length == 2) {
sb.append(", \"").append(escapeJson(keyValue[0])).append("\" : \"").append(escapeJson(initialEnvironment.expand(keyValue[1]))).append("\"");
}
}
}
sb.append("}");
map.put("SONARQUBE_SCANNER_PARAMS", sb.toString());
return map;
}
private static String getAdditionalProps(SonarInstallation inst) {
ArgumentListBuilder builder = new ArgumentListBuilder();
// no need to tokenize since we need a String anyway
builder.add(inst.getAdditionalAnalysisPropertiesUnix());
builder.add(inst.getAdditionalProperties());
return StringUtils.join(builder.toList(), ' ');
}
private static String getOrDefault(@Nullable String value, String defaultValue) {
return !StringUtils.isEmpty(value) ? value : defaultValue;
}
@Override
public ConsoleLogFilter createLoggerDecorator(Run<?, ?> build) {
SonarInstallation inst = SonarInstallation.get(getInstallationName());
if (inst == null) {
return null;
}
Logger.LOG.info(Messages.SonarBuildWrapper_MaskingPasswords());
List<String> passwords = new ArrayList<>();
String token = getOrDefault(SonarUtils.getAuthenticationToken(build, inst, credentialsId), "");
if (!StringUtils.isBlank(token)) {
passwords.add(token);
}
return new SonarQubePasswordLogFilter(passwords, build.getCharset().name());
}
private static final class AddBuildInfo extends Disposer {
private static final long serialVersionUID = 1L;
private final SonarInstallation installation;
private final String credentialsId;
public AddBuildInfo(SonarInstallation installation, @Nullable String credentialsId) {
this.installation = installation;
this.credentialsId = credentialsId;
}
@Override
public void tearDown(Run<?, ?> build, FilePath workspace, Launcher launcher, TaskListener listener) throws IOException, InterruptedException {
// null result means success so far. If no logs are found, it's probably because it was simply skipped
SonarUtils.addBuildInfoTo(build, listener, workspace, installation, credentialsId, build.getResult() == null);
}
}
private static class SonarQubePasswordLogFilter extends ConsoleLogFilter implements Serializable {
private static final long serialVersionUID = 1L;
private final List<String> passwords;
private final String consoleCharset;
public SonarQubePasswordLogFilter(List<String> passwords, String consoleCharset) {
this.passwords = passwords;
this.consoleCharset = consoleCharset;
}
@Override
public OutputStream decorateLogger(Run ignore, OutputStream logger) throws IOException, InterruptedException {
return new MaskPasswordsOutputStream(logger, Charset.forName(consoleCharset), passwords);
}
}
/**
* @return name of {@link hudson.plugins.sonar.SonarInstallation}
*/
@Nullable
public String getInstallationName() {
return installationName;
}
public void setInstallationName(@Nullable String installationName) {
this.installationName = installationName;
}
@Symbol("withSonarQubeEnv")
@Extension
public static final class DescriptorImpl extends BuildWrapperDescriptor {
@NonNull
@Override
public String getDisplayName() {
return Messages.SonarBuildWrapper_DisplayName();
}
public static ListBoxModel doFillCredentialsIdItems(@Nullable @AncestorInPath Item project,
@QueryParameter String credentialsId) {
if (project == null ? !Jenkins.get().hasPermission(Jenkins.ADMINISTER) : !project.hasPermission(Item.EXTENDED_READ)) {
return new StandardListBoxModel().includeCurrentValue(credentialsId);
}
if (project == null) {
/* Construct a fake project */
project = new FreeStyleProject((ItemGroup<TopLevelItem>) Jenkins.get(), "fake-" + UUID.randomUUID());
}
return new StandardListBoxModel()
.includeEmptyValue()
.includeMatchingAs(
project instanceof Queue.Task
? Tasks.getAuthenticationOf2((Queue.Task) project)
: ACL.SYSTEM2,
project,
StringCredentials.class,
Collections.emptyList(),
CredentialsMatchers.always())
.includeCurrentValue(credentialsId);
}
public static FormValidation doCheckCredentialsId(@Nullable @AncestorInPath Item project,
@QueryParameter String value) {
if (project == null ? !Jenkins.get().hasPermission(Jenkins.ADMINISTER) : !project.hasPermission(Item.EXTENDED_READ)) {
return FormValidation.ok();
}
value = Util.fixEmptyAndTrim(value);
if (value == null) {
return FormValidation.ok();
}
for (ListBoxModel.Option o : CredentialsProvider
.listCredentialsInItem(StandardUsernameCredentials.class, project, project instanceof Queue.Task
? Tasks.getAuthenticationOf2((Queue.Task) project)
: ACL.SYSTEM2,
Collections.emptyList(),
CredentialsMatchers.always())) {
if (StringUtils.equals(value, o.value)) {
return FormValidation.ok();
}
}
// no credentials available, can't check
return FormValidation.warning("Cannot find any credentials with id " + value);
}
@Override
public boolean isApplicable(AbstractProject<?, ?> item) {
return SonarGlobalConfiguration.get().isBuildWrapperEnabled();
}
/**
* @return all configured {@link hudson.plugins.sonar.SonarInstallation}
*/
public SonarInstallation[] getSonarInstallations() {
return SonarInstallation.all();
}
@Override
public String getHelpFile() {
return "/plugin/sonar/help-buildWrapper.html";
}
}
}