-
Notifications
You must be signed in to change notification settings - Fork 1.9k
/
QualityGates.java
415 lines (369 loc) · 15.4 KB
/
QualityGates.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
/*
* SonarQube
* Copyright (C) 2009-2016 SonarSource SA
* mailto:contact 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.server.qualitygate;
import com.google.common.base.Predicate;
import com.google.common.base.Strings;
import com.google.common.collect.Collections2;
import java.util.Collection;
import javax.annotation.CheckForNull;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import org.apache.commons.lang.BooleanUtils;
import org.apache.commons.lang.ObjectUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.ibatis.session.SqlSession;
import org.sonar.api.config.Settings;
import org.sonar.api.measures.CoreMetrics;
import org.sonar.api.measures.Metric;
import org.sonar.api.measures.Metric.ValueType;
import org.sonar.api.measures.MetricFinder;
import org.sonar.api.web.UserRole;
import org.sonar.core.permission.GlobalPermissions;
import org.sonar.db.DbSession;
import org.sonar.db.MyBatis;
import org.sonar.db.component.ComponentDao;
import org.sonar.db.component.ComponentDto;
import org.sonar.db.property.PropertiesDao;
import org.sonar.db.property.PropertyDto;
import org.sonar.db.qualitygate.QualityGateConditionDao;
import org.sonar.db.qualitygate.QualityGateConditionDto;
import org.sonar.db.qualitygate.QualityGateDao;
import org.sonar.db.qualitygate.QualityGateDto;
import org.sonar.server.exceptions.BadRequestException;
import org.sonar.server.exceptions.Errors;
import org.sonar.server.exceptions.ForbiddenException;
import org.sonar.server.exceptions.Message;
import org.sonar.server.exceptions.NotFoundException;
import org.sonar.server.exceptions.ServerException;
import org.sonar.server.user.UserSession;
import org.sonar.server.util.Validation;
import static com.google.common.collect.FluentIterable.from;
import static java.lang.String.format;
/**
* @since 4.3
*/
public class QualityGates {
public static final String SONAR_QUALITYGATE_PROPERTY = "sonar.qualitygate";
private final QualityGateDao dao;
private final QualityGateConditionDao conditionDao;
private final MetricFinder metricFinder;
private final PropertiesDao propertiesDao;
private final ComponentDao componentDao;
private final MyBatis myBatis;
private final UserSession userSession;
private final Settings settings;
public QualityGates(QualityGateDao dao, QualityGateConditionDao conditionDao, MetricFinder metricFinder, PropertiesDao propertiesDao, ComponentDao componentDao,
MyBatis myBatis, UserSession userSession, Settings settings) {
this.dao = dao;
this.conditionDao = conditionDao;
this.metricFinder = metricFinder;
this.propertiesDao = propertiesDao;
this.componentDao = componentDao;
this.myBatis = myBatis;
this.userSession = userSession;
this.settings = settings;
}
public QualityGateDto create(String name) {
checkPermission();
validateQualityGate(null, name);
QualityGateDto newQualityGate = new QualityGateDto().setName(name);
dao.insert(newQualityGate);
return newQualityGate;
}
public QualityGateDto get(Long qGateId) {
return getNonNullQgate(qGateId);
}
public QualityGateDto get(String qGateName) {
return getNonNullQgate(qGateName);
}
public QualityGateDto rename(long idToRename, String name) {
checkPermission();
QualityGateDto toRename = getNonNullQgate(idToRename);
validateQualityGate(idToRename, name);
toRename.setName(name);
dao.update(toRename);
return toRename;
}
public QualityGateDto copy(long sourceId, String destinationName) {
checkPermission();
getNonNullQgate(sourceId);
validateQualityGate(null, destinationName);
QualityGateDto destinationGate = new QualityGateDto().setName(destinationName);
SqlSession session = myBatis.openSession(false);
try {
dao.insert(destinationGate, session);
for (QualityGateConditionDto sourceCondition : conditionDao.selectForQualityGate(sourceId, session)) {
conditionDao.insert(new QualityGateConditionDto().setQualityGateId(destinationGate.getId())
.setMetricId(sourceCondition.getMetricId()).setOperator(sourceCondition.getOperator())
.setWarningThreshold(sourceCondition.getWarningThreshold()).setErrorThreshold(sourceCondition.getErrorThreshold()).setPeriod(sourceCondition.getPeriod()),
session);
}
session.commit();
} finally {
MyBatis.closeQuietly(session);
}
return destinationGate;
}
public Collection<QualityGateDto> list() {
return dao.selectAll();
}
public void delete(long idToDelete) {
checkPermission();
QualityGateDto qGate = getNonNullQgate(idToDelete);
DbSession session = myBatis.openSession(false);
try {
if (isDefault(qGate)) {
propertiesDao.deleteGlobalProperty(SONAR_QUALITYGATE_PROPERTY, session);
}
propertiesDao.deleteProjectProperties(SONAR_QUALITYGATE_PROPERTY, Long.toString(idToDelete), session);
dao.delete(qGate, session);
session.commit();
} finally {
MyBatis.closeQuietly(session);
}
}
public void setDefault(@Nullable Long idToUseAsDefault) {
checkPermission();
if (idToUseAsDefault == null) {
propertiesDao.deleteGlobalProperty(SONAR_QUALITYGATE_PROPERTY);
settings.removeProperty(SONAR_QUALITYGATE_PROPERTY);
} else {
QualityGateDto newDefault = getNonNullQgate(idToUseAsDefault);
propertiesDao.insertProperty(new PropertyDto().setKey(SONAR_QUALITYGATE_PROPERTY).setValue(newDefault.getId().toString()));
settings.setProperty(SONAR_QUALITYGATE_PROPERTY, idToUseAsDefault);
}
}
@CheckForNull
public QualityGateDto getDefault() {
Long defaultId = getDefaultId();
if (defaultId == null) {
return null;
} else {
return dao.selectById(defaultId);
}
}
public QualityGateConditionDto createCondition(long qGateId, String metricKey, String operator,
@Nullable String warningThreshold, @Nullable String errorThreshold, @Nullable Integer period) {
checkPermission();
getNonNullQgate(qGateId);
Metric metric = getNonNullMetric(metricKey);
validateCondition(qGateId, metric, operator, warningThreshold, errorThreshold, period);
QualityGateConditionDto newCondition = new QualityGateConditionDto().setQualityGateId(qGateId)
.setMetricId(metric.getId()).setMetricKey(metric.getKey())
.setOperator(operator)
.setWarningThreshold(warningThreshold)
.setErrorThreshold(errorThreshold)
.setPeriod(period);
conditionDao.insert(newCondition);
return newCondition;
}
public QualityGateConditionDto updateCondition(long condId, String metricKey, String operator,
@Nullable String warningThreshold, @Nullable String errorThreshold, @Nullable Integer period) {
checkPermission();
QualityGateConditionDto condition = getNonNullCondition(condId);
Metric metric = getNonNullMetric(metricKey);
validateCondition(condition.getQualityGateId(), metric, operator, warningThreshold, errorThreshold, period);
condition
.setMetricId(metric.getId())
.setMetricKey(metric.getKey())
.setOperator(operator)
.setWarningThreshold(warningThreshold)
.setErrorThreshold(errorThreshold)
.setPeriod(period);
conditionDao.update(condition);
return condition;
}
public Collection<QualityGateConditionDto> listConditions(long qGateId) {
Collection<QualityGateConditionDto> conditionsForGate = conditionDao.selectForQualityGate(qGateId);
for (QualityGateConditionDto condition : conditionsForGate) {
Metric metric = metricFinder.findById((int) condition.getMetricId());
if (metric == null) {
throw new IllegalStateException("Could not find metric with id " + condition.getMetricId());
}
condition.setMetricKey(metric.getKey());
}
return conditionsForGate;
}
public void deleteCondition(Long condId) {
checkPermission();
conditionDao.delete(getNonNullCondition(condId));
}
public void associateProject(Long qGateId, Long projectId) {
DbSession session = myBatis.openSession(false);
try {
getNonNullQgate(qGateId);
checkPermission(projectId, session);
propertiesDao.insertProperty(new PropertyDto().setKey(SONAR_QUALITYGATE_PROPERTY).setResourceId(projectId).setValue(qGateId.toString()));
} finally {
MyBatis.closeQuietly(session);
}
}
public void dissociateProject(Long qGateId, Long projectId) {
DbSession session = myBatis.openSession(false);
try {
getNonNullQgate(qGateId);
checkPermission(projectId, session);
propertiesDao.deleteProjectProperty(SONAR_QUALITYGATE_PROPERTY, projectId);
} finally {
MyBatis.closeQuietly(session);
}
}
public Collection<Metric> gateMetrics() {
return Collections2.filter(metricFinder.findAll(), new Predicate<Metric>() {
@Override
public boolean apply(Metric metric) {
return isAvailableForInit(metric);
}
});
}
public boolean currentUserHasWritePermission() {
boolean hasWritePermission = false;
try {
checkPermission();
hasWritePermission = true;
} catch (ServerException unallowed) {
// Ignored
}
return hasWritePermission;
}
private void validateCondition(long qGateId, Metric metric, String operator, @Nullable String warningThreshold, @Nullable String errorThreshold, @Nullable Integer period) {
Errors errors = new Errors();
validateMetric(metric, errors);
checkOperator(metric, operator, errors);
checkThresholds(warningThreshold, errorThreshold, errors);
checkPeriod(metric, period, errors);
checkConditionDoesNotAlreadyExistOnSameMetricAndPeriod(qGateId, metric, period, errors);
if (!errors.isEmpty()) {
throw new BadRequestException(errors);
}
}
private void checkConditionDoesNotAlreadyExistOnSameMetricAndPeriod(long qGateId, Metric metric, @Nullable final Integer period, Errors errors) {
Collection<QualityGateConditionDto> conditions = conditionDao.selectForQualityGate(qGateId);
if (conditions.isEmpty()) {
return;
}
boolean conditionExists = from(conditions).anyMatch(new MatchMetricAndPeriod(metric.getId(), period));
String errorMessage = period == null
? format("Condition on metric '%s' already exists.", metric.getName())
: format("Condition on metric '%s' over leak period already exists.", metric.getName());
errors.check(!conditionExists, errorMessage);
}
private void checkPeriod(Metric metric, @Nullable Integer period, Errors errors) {
if (period == null) {
errors.check(!metric.getKey().startsWith("new_"), "A period must be selected for differential metrics.");
} else {
errors.check(period == 1, "The only valid quality gate period is 1, the leak period.");
}
}
private void checkThresholds(@Nullable String warningThreshold, @Nullable String errorThreshold, Errors errors) {
errors.check(warningThreshold != null || errorThreshold != null, "At least one threshold (warning, error) must be set.");
}
private void checkOperator(Metric metric, String operator, Errors errors) {
errors
.check(QualityGateConditionDto.isOperatorAllowed(operator, metric.getType()), format("Operator %s is not allowed for metric type %s.", operator, metric.getType()));
}
private void validateMetric(Metric metric, Errors errors) {
errors.check(isAlertable(metric), format("Metric '%s' cannot be used to define a condition.", metric.getKey()));
}
private boolean isAvailableForInit(Metric metric) {
return !metric.isDataType() && !CoreMetrics.ALERT_STATUS.equals(metric) && ValueType.RATING != metric.getType();
}
private boolean isAlertable(Metric metric) {
return isAvailableForInit(metric) && BooleanUtils.isFalse(metric.isHidden());
}
private boolean isDefault(QualityGateDto qGate) {
return qGate.getId().equals(getDefaultId());
}
private Long getDefaultId() {
PropertyDto defaultQgate = propertiesDao.selectGlobalProperty(SONAR_QUALITYGATE_PROPERTY);
if (defaultQgate == null || StringUtils.isBlank(defaultQgate.getValue())) {
return null;
} else {
return Long.valueOf(defaultQgate.getValue());
}
}
private QualityGateDto getNonNullQgate(long id) {
QualityGateDto qGate = dao.selectById(id);
if (qGate == null) {
throw new NotFoundException("There is no quality gate with id=" + id);
}
return qGate;
}
private QualityGateDto getNonNullQgate(String name) {
QualityGateDto qGate = dao.selectByName(name);
if (qGate == null) {
throw new NotFoundException("There is no quality gate with name=" + name);
}
return qGate;
}
private Metric getNonNullMetric(String metricKey) {
Metric metric = metricFinder.findByKey(metricKey);
if (metric == null) {
throw new NotFoundException("There is no metric with key=" + metricKey);
}
return metric;
}
private QualityGateConditionDto getNonNullCondition(long id) {
QualityGateConditionDto condition = conditionDao.selectById(id);
if (condition == null) {
throw new NotFoundException("There is no condition with id=" + id);
}
return condition;
}
private void validateQualityGate(@Nullable Long updatingQgateId, @Nullable String name) {
Errors errors = new Errors();
if (Strings.isNullOrEmpty(name)) {
errors.add(Message.of(Validation.CANT_BE_EMPTY_MESSAGE, "Name"));
} else {
checkQgateNotAlreadyExists(updatingQgateId, name, errors);
}
if (!errors.isEmpty()) {
throw new BadRequestException(errors);
}
}
private void checkQgateNotAlreadyExists(@Nullable Long updatingQgateId, String name, Errors errors) {
QualityGateDto existingQgate = dao.selectByName(name);
boolean isModifyingCurrentQgate = updatingQgateId != null && existingQgate != null && existingQgate.getId().equals(updatingQgateId);
errors.check(isModifyingCurrentQgate || existingQgate == null, Validation.IS_ALREADY_USED_MESSAGE, "Name");
}
private void checkPermission() {
userSession.checkPermission(GlobalPermissions.QUALITY_GATE_ADMIN);
}
private void checkPermission(Long projectId, DbSession session) {
ComponentDto project = componentDao.selectOrFailById(session, projectId);
if (!userSession.hasPermission(GlobalPermissions.QUALITY_GATE_ADMIN) && !userSession.hasComponentPermission(UserRole.ADMIN, project.key())) {
throw new ForbiddenException("Insufficient privileges");
}
}
private static class MatchMetricAndPeriod implements Predicate<QualityGateConditionDto> {
private final int metricId;
@CheckForNull
private final Integer period;
public MatchMetricAndPeriod(int metricId, @Nullable Integer period) {
this.metricId = metricId;
this.period = period;
}
@Override
public boolean apply(@Nonnull QualityGateConditionDto input) {
return input.getMetricId() == metricId &&
ObjectUtils.equals(input.getPeriod(), period);
}
}
}