-
Notifications
You must be signed in to change notification settings - Fork 26
/
AdvisorGlobalConfiguration.java
461 lines (392 loc) · 13.3 KB
/
AdvisorGlobalConfiguration.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
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
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
package com.cloudbees.jenkins.plugins.advisor;
import com.cloudbees.jenkins.plugins.advisor.client.AdvisorClient;
import com.cloudbees.jenkins.plugins.advisor.client.model.Recipient;
import com.cloudbees.jenkins.plugins.advisor.utils.EmailUtil;
import com.cloudbees.jenkins.plugins.advisor.utils.EmailValidator;
import com.cloudbees.jenkins.plugins.advisor.utils.FormValidationHelper;
import com.cloudbees.jenkins.support.SupportAction;
import com.cloudbees.jenkins.support.SupportPlugin;
import com.cloudbees.jenkins.support.api.Component;
import hudson.BulkChange;
import hudson.Extension;
import hudson.ExtensionPoint;
import hudson.Functions;
import hudson.PluginWrapper;
import hudson.XmlFile;
import hudson.model.Describable;
import hudson.model.Descriptor;
import hudson.model.Descriptor.FormException;
import hudson.model.ManagementLink;
import hudson.model.Saveable;
import hudson.model.listeners.SaveableListener;
import hudson.util.FormValidation;
import jenkins.model.Jenkins;
import jenkins.util.io.OnMaster;
import net.sf.json.JSONObject;
import org.apache.commons.lang.StringUtils;
import org.kohsuke.accmod.Restricted;
import org.kohsuke.accmod.restrictions.NoExternalUse;
import org.kohsuke.stapler.DataBoundConstructor;
import org.kohsuke.stapler.HttpResponse;
import org.kohsuke.stapler.HttpResponses;
import org.kohsuke.stapler.QueryParameter;
import org.kohsuke.stapler.StaplerRequest;
import org.kohsuke.stapler.interceptor.RequirePOST;
import javax.annotation.CheckForNull;
import javax.annotation.Nonnull;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Optional;
import java.util.Set;
import java.util.logging.Level;
import java.util.logging.Logger;
@Extension
public class AdvisorGlobalConfiguration
extends ManagementLink
implements Describable<AdvisorGlobalConfiguration>, ExtensionPoint, Saveable, OnMaster {
public static final String PLUGIN_NAME = "cloudbees-jenkins-advisor";
public static final String SEND_ALL_COMPONENTS = "SENDALL";
private static final Logger LOG = Logger.getLogger(AdvisorGlobalConfiguration.class.getName());
private String email;
private String cc;
private Set<String> excludedComponents;
private boolean isValid;
private boolean nagDisabled;
private boolean acceptToS;
private String lastBundleResult;
public AdvisorGlobalConfiguration() {
load();
}
@DataBoundConstructor
public AdvisorGlobalConfiguration(String email, String cc, Set<String> excludedComponents) {
this.setEmail(email);
this.setCc(cc);
this.excludedComponents = excludedComponents;
this.lastBundleResult = "";
}
public static AdvisorGlobalConfiguration getInstance() {
return Jenkins.get().getExtensionList(AdvisorGlobalConfiguration.class).get(0);
}
@CheckForNull
@Override
public String getIconFileName() {
return "/plugin/cloudbees-jenkins-advisor/icons/advisor.svg";
}
@CheckForNull
@Override
public String getUrlName() {
return PLUGIN_NAME;
}
@CheckForNull
@Override
public String getDisplayName() {
return Messages.Insights_DisplayName();
}
@CheckForNull
@Override
public String getDescription() {
return Messages.Insights_Description();
}
public String getActionTitle() {
return Messages.Insights_Title();
}
public String getActionDisclaimer() {
return Messages.Insights_Disclaimer();
}
public String getDisclaimer() {
return Messages.Insights_Disclaimer();
}
public boolean isNagDisabled() {
return nagDisabled;
}
public void setNagDisabled(boolean nagDisabled) {
if (this.nagDisabled != nagDisabled) {
this.nagDisabled = nagDisabled;
}
}
public boolean isAcceptToS() {
return acceptToS;
}
public void setAcceptToS(boolean acceptToS) {
if (this.acceptToS != acceptToS) {
this.acceptToS = acceptToS;
}
}
public String getLastBundleResult() {
return lastBundleResult;
}
public void setLastBundleResult(String lastBundleResult) {
this.lastBundleResult = lastBundleResult;
}
/**
* Handles the form submission
*
* @param req the request.
* @return the response.
*/
@RequirePOST
@Nonnull
@Restricted(NoExternalUse.class)
public HttpResponse doConfigure(@Nonnull StaplerRequest req) {
Jenkins jenkins = Jenkins.get();
jenkins.checkPermission(Jenkins.ADMINISTER);
try {
isValid = configureDescriptor(req, req.getSubmittedForm(), getDescriptor());
save();
// We want to refresh the page to reload the status even when we click on "Apply"
if (!isValid || StringUtils.isNotBlank(req.getParameter("advisor:apply"))) {
return HttpResponses.redirectToDot();
} else {
return HttpResponses.redirectTo(req.getContextPath() + "/manage");
}
} catch (Exception e) {
isValid = false;
LOG.severe("Unable to save Jenkins Health Advisor by CloudBees configuration: " + Functions.printThrowable(e));
return FormValidation.error("Unable to save configuration: " + e.getMessage());
}
}
/**
* Performs the configuration of a specific {@link Descriptor}.
*
* @param req the request.
* @param json the JSON object.
* @param d the {@link Descriptor}.
* @return {@code false} to keep the client in the same config page.
* @throws FormException if something goes wrong.
*/
private boolean configureDescriptor(StaplerRequest req, JSONObject json, Descriptor<?> d) throws FormException {
req.bindJSON(this, json);
return d.configure(req, json);
}
/**
* {@inheritDoc}
*/
@Override
public Descriptor<AdvisorGlobalConfiguration> getDescriptor() {
return Jenkins.get().getDescriptorOrDie(getClass());
}
public String getEmail() {
return email;
}
public void setEmail(@CheckForNull String email) {
this.email = EmailUtil.fixEmptyAndTrimAllSpaces(email);
}
public String getCc() {
return cc;
}
public void setCc(@CheckForNull String cc) {
this.cc = EmailUtil.fixEmptyAndTrimAllSpaces(cc);
}
public Set<String> getExcludedComponents() {
return excludedComponents != null ? excludedComponents : Collections.emptySet();
}
public void setExcludedComponents(Set<String> excludedComponents) {
this.excludedComponents = excludedComponents;
}
public List<Component> getIncludedComponents() {
List<Component> included = new ArrayList<>();
if (getExcludedComponents().isEmpty()) {
for (Component c : getComponents()) {
if (c.isSelectedByDefault()) {
included.add(c);
}
}
} else {
for (Component c : getComponents()) {
if (!getExcludedComponents().contains(c.getId())) {
included.add(c);
}
}
}
return included;
}
public boolean selectedByDefault(Component c) {
if (getExcludedComponents().isEmpty()) {
return c.isSelectedByDefault();
}
return !getExcludedComponents().contains(c.getId());
}
public List<Component> getComponents() {
return SupportPlugin.getComponents();
}
public boolean isValid() {
return isValid;
}
public void setValid(boolean valid) {
isValid = valid;
}
boolean isPluginEnabled() {
boolean lastEnabledState;
try {
PluginWrapper plugin = Jenkins.get().getPluginManager().getPlugin(PLUGIN_NAME);
if (plugin == null) {
LOG.severe("Expected to find plugin: [" + PLUGIN_NAME + "] but none found");
return false;
}
lastEnabledState = plugin.isEnabled();
} catch (NullPointerException e) {
return false;
}
return lastEnabledState;
}
@Override
public synchronized void save() {
if (BulkChange.contains(this)) {
return;
}
try {
getConfigFile().write(this);
SaveableListener.fireOnChange(this, getConfigFile());
} catch (IOException e) {
LOG.log(Level.WARNING, "Failed to save " + getConfigFile(), e);
}
}
public synchronized void load() {
XmlFile file = getConfigFile();
if (!file.exists()) {
return;
}
try {
file.unmarshal(this);
} catch (IOException e) {
LOG.log(Level.WARNING, "Failed to load " + file, e);
}
}
private XmlFile getConfigFile() {
return new XmlFile(new File(Jenkins.get().getRootDir(), getClass().getName() + ".xml"));
}
@Extension
public static final class DescriptorImpl extends Descriptor<AdvisorGlobalConfiguration> {
public DescriptorImpl() {
super.load();
}
/**
* {@inheritDoc}
*/
@Nonnull
@Override
public String getDisplayName() {
return Messages.Insights_DisplayName();
}
public FormValidation doCheckEmail(@QueryParameter String value) {
String emailAddress = EmailUtil.fixEmptyAndTrimAllSpaces(value);
if (emailAddress == null || emailAddress.isEmpty()) {
return FormValidation.error("Email cannot be blank");
}
if (emailAddress.contains(";") || emailAddress.contains(",")) {
return FormValidation.error(
"Email cannot contain illegal character ';' or ','. Consider using the CC field if multiple recipients are required");
}
EmailValidator validator = EmailValidator.getInstance();
if (!validator.isValid(emailAddress)) {
return FormValidation.error("Invalid email");
}
return FormValidation.ok();
}
public FormValidation doCheckCc(@QueryParameter String value) {
String emailAddress = EmailUtil.fixEmptyAndTrimAllSpaces(value);
if (emailAddress == null || emailAddress.isEmpty()) {
return FormValidation.ok();
}
if (emailAddress.contains(";")) {
return FormValidation
.error("Email cannot contain illegal character ';'. Use ',' if multiple recipients are required.");
}
for (String cc : emailAddress.split(",")) {
EmailValidator validator = EmailValidator.getInstance();
if (!validator.isValid(cc)) {
return FormValidation.error(String.format("Invalid email [%s]", cc));
}
}
return FormValidation.ok();
}
public FormValidation doTestConnection(@QueryParameter("email") final String email,
@QueryParameter("cc") final String cc) {
try {
if (email.isEmpty()) {
return FormValidation.error("Missing email");
}
Optional<FormValidation> ccErrors = FormValidationHelper.validateCC(cc);
if (ccErrors.isPresent()) {
return ccErrors.get();
}
AdvisorClient advisorClient = new AdvisorClient(new Recipient(email.trim()));
advisorClient.doCheckHealth();
return FormValidation.ok("Success");
} catch (Exception e) {
return FormValidation.error("Client error : " + e.getMessage());
}
}
// Used from validateOnLoad.jelly
public String connectionTest(String email) {
AdvisorGlobalConfiguration config = AdvisorGlobalConfiguration.getInstance();
if (!config.isAcceptToS()) {
return "tos-not-accepted";
}
try {
AdvisorClient advisorClient = new AdvisorClient(new Recipient(email));
advisorClient.doCheckHealth();
return "service-operational";
} catch (Exception e) {
return "" + e.getMessage();
}
}
public FormValidation doTestSendEmail(@QueryParameter("email") final String email,
@QueryParameter("cc") final String cc) {
try {
if (email.isEmpty()) {
return FormValidation.error("Missing email");
}
Optional<FormValidation> ccErrors = FormValidationHelper.validateCC(cc);
if (ccErrors.isPresent()) {
return ccErrors.get();
}
AdvisorClient advisorClient = new AdvisorClient(new Recipient(email.trim()));
advisorClient.doTestEmail();
return FormValidation.ok("Sending email. Please check your inbox and filters.");
} catch (Exception e) {
return FormValidation.error("Client error : " + e.getMessage());
}
}
@Override
public boolean configure(StaplerRequest req, JSONObject json) {
String email = json.getString("email");
String cc = json.getString("cc");
JSONObject advanced = json.getJSONObject("advanced");
boolean acceptToS = json.getBoolean("acceptToS");
// Have to accept the Terms of Service to have a valid configuration
if (!acceptToS) {
return false;
}
Set<String> remove = new HashSet<>();
for (SupportAction.Selection s : req.bindJSONToList(SupportAction.Selection.class, advanced.get("components"))) {
if (!s.isSelected()) {
LOG.log(Level.FINER, "Excluding ''{0}'' from list of components to include", s.getName());
remove.add(s.getName());
}
}
// Note that we're not excluding anything
if (remove.isEmpty()) {
remove.add(SEND_ALL_COMPONENTS);
}
final AdvisorGlobalConfiguration insights = AdvisorGlobalConfiguration.getInstance();
if (insights != null) {
insights.setExcludedComponents(remove);
}
try {
if (doCheckEmail(email).kind.equals(FormValidation.Kind.ERROR) ||
doCheckCc(cc).kind.equals(FormValidation.Kind.ERROR)) {
return false;
}
} catch (Exception e) {
LOG.severe("Unexpected error while validating form: " + Functions.printThrowable(e));
return false;
}
return true;
}
}
}