3 * Copyright (C) 2009-2024 SonarSource SA
4 * mailto:info AT sonarsource DOT com
6 * This program is free software; you can redistribute it and/or
7 * modify it under the terms of the GNU Lesser General Public
8 * License as published by the Free Software Foundation; either
9 * version 3 of the License, or (at your option) any later version.
11 * This program is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 * Lesser General Public License for more details.
16 * You should have received a copy of the GNU Lesser General Public License
17 * along with this program; if not, write to the Free Software Foundation,
18 * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
20 package org.sonar.server.qualityprofile;
22 import java.io.Reader;
23 import java.io.Writer;
24 import java.util.ArrayList;
25 import java.util.Collection;
26 import java.util.Collections;
27 import java.util.Comparator;
28 import java.util.List;
31 import java.util.function.Function;
32 import java.util.stream.Collectors;
33 import javax.annotation.Nullable;
34 import org.apache.commons.lang3.builder.CompareToBuilder;
35 import org.sonar.api.rule.RuleKey;
36 import org.sonar.api.rule.RuleStatus;
37 import org.sonar.api.rules.RuleType;
38 import org.sonar.api.server.ServerSide;
39 import org.sonar.db.DbClient;
40 import org.sonar.db.DbSession;
41 import org.sonar.db.qualityprofile.ExportRuleDto;
42 import org.sonar.db.qualityprofile.ExportRuleParamDto;
43 import org.sonar.db.qualityprofile.QProfileDto;
44 import org.sonar.db.rule.DeprecatedRuleKeyDto;
45 import org.sonar.db.rule.RuleDto;
46 import org.sonar.server.common.rule.RuleCreator;
47 import org.sonar.server.common.rule.service.NewCustomRule;
48 import org.sonar.server.qualityprofile.builtin.QProfileName;
50 import static com.google.common.base.Preconditions.checkArgument;
51 import static java.util.function.Function.identity;
52 import static java.util.stream.Collectors.toSet;
53 import static org.sonar.server.qualityprofile.QProfileUtils.parseImpactsToMap;
56 public class QProfileBackuperImpl implements QProfileBackuper {
58 private final DbClient db;
59 private final QProfileReset profileReset;
60 private final QProfileFactory profileFactory;
61 private final RuleCreator ruleCreator;
62 private final QProfileParser qProfileParser;
64 public QProfileBackuperImpl(DbClient db, QProfileReset profileReset, QProfileFactory profileFactory,
65 RuleCreator ruleCreator, QProfileParser qProfileParser) {
67 this.profileReset = profileReset;
68 this.profileFactory = profileFactory;
69 this.ruleCreator = ruleCreator;
70 this.qProfileParser = qProfileParser;
74 public void backup(DbSession dbSession, QProfileDto profile, Writer writer) {
75 List<ExportRuleDto> rulesToExport = db.qualityProfileExportDao().selectRulesByProfile(dbSession, profile);
76 rulesToExport.sort(BackupActiveRuleComparator.INSTANCE);
77 qProfileParser.writeXml(writer, profile, rulesToExport.iterator());
81 public QProfileRestoreSummary copy(DbSession dbSession, QProfileDto from, QProfileDto to) {
82 List<ExportRuleDto> rulesToExport = db.qualityProfileExportDao().selectRulesByProfile(dbSession, from);
83 rulesToExport.sort(BackupActiveRuleComparator.INSTANCE);
85 ImportedQProfile qProfile = toImportedQProfile(rulesToExport, to.getName(), to.getLanguage());
86 return restore(dbSession, qProfile, name -> to);
89 private static ImportedQProfile toImportedQProfile(List<ExportRuleDto> exportRules, String profileName, String profileLang) {
90 List<ImportedRule> importedRules = new ArrayList<>(exportRules.size());
92 for (ExportRuleDto exportRuleDto : exportRules) {
93 var ruleKey = exportRuleDto.getRuleKey();
94 ImportedRule importedRule = new ImportedRule();
95 importedRule.setName(exportRuleDto.getName());
96 importedRule.setRepository(ruleKey.repository());
97 importedRule.setKey(ruleKey.rule());
98 importedRule.setSeverity(exportRuleDto.getSeverityString());
99 importedRule.setImpacts(exportRuleDto.getImpacts() != null ? parseImpactsToMap(exportRuleDto.getImpacts()) : Map.of());
100 if (exportRuleDto.isCustomRule()) {
101 importedRule.setTemplate(exportRuleDto.getTemplateRuleKey().rule());
102 importedRule.setDescription(exportRuleDto.getDescriptionOrThrow());
104 importedRule.setType(exportRuleDto.getRuleType().name());
105 importedRule.setParameters(exportRuleDto.getParams().stream().collect(Collectors.toMap(ExportRuleParamDto::getKey, ExportRuleParamDto::getValue)));
106 importedRules.add(importedRule);
109 return new ImportedQProfile(profileName, profileLang, importedRules);
113 public QProfileRestoreSummary restore(DbSession dbSession, Reader backup, @Nullable String overriddenProfileName) {
114 return restore(dbSession, backup, nameInBackup -> {
115 QProfileName targetName = nameInBackup;
116 if (overriddenProfileName != null) {
117 targetName = new QProfileName(nameInBackup.getLanguage(), overriddenProfileName);
119 return profileFactory.getOrCreateCustom(dbSession, targetName);
124 public QProfileRestoreSummary restore(DbSession dbSession, Reader backup, QProfileDto profile) {
125 return restore(dbSession, backup, nameInBackup -> {
126 checkArgument(profile.getLanguage().equals(nameInBackup.getLanguage()),
127 "Can't restore %s backup on %s profile with key [%s]. Languages are different.", nameInBackup.getLanguage(), profile.getLanguage(), profile.getKee());
132 private QProfileRestoreSummary restore(DbSession dbSession, Reader backup, Function<QProfileName, QProfileDto> profileLoader) {
133 ImportedQProfile qProfile = qProfileParser.readXml(backup);
134 return restore(dbSession, qProfile, profileLoader);
137 private QProfileRestoreSummary restore(DbSession dbSession, ImportedQProfile qProfile, Function<QProfileName, QProfileDto> profileLoader) {
138 QProfileName targetName = new QProfileName(qProfile.getProfileLang(), qProfile.getProfileName());
139 QProfileDto targetProfile = profileLoader.apply(targetName);
141 List<ImportedRule> importedRules = qProfile.getRules();
143 Map<RuleKey, RuleDto> ruleKeyToDto = getImportedRulesDtos(dbSession, importedRules);
144 checkIfRulesFromExternalEngines(ruleKeyToDto.values());
146 Map<RuleKey, RuleDto> customRulesDefinitions = createCustomRulesIfNotExist(dbSession, importedRules, ruleKeyToDto);
147 ruleKeyToDto.putAll(customRulesDefinitions);
149 List<RuleActivation> ruleActivations = toRuleActivations(importedRules, ruleKeyToDto);
151 BulkChangeResult changes = profileReset.reset(dbSession, targetProfile, ruleActivations);
152 return new QProfileRestoreSummary(targetProfile, changes);
156 * Returns map of rule definition for an imported rule key.
157 * The imported rule key may refer to a deprecated rule key, in which case the the RuleDto will correspond to a different key (the new key).
159 private Map<RuleKey, RuleDto> getImportedRulesDtos(DbSession dbSession, List<ImportedRule> rules) {
160 Set<RuleKey> ruleKeys = rules.stream()
161 .map(ImportedRule::getRuleKey)
163 Map<RuleKey, RuleDto> ruleDtos = db.ruleDao().selectByKeys(dbSession, ruleKeys).stream()
164 .collect(Collectors.toMap(RuleDto::getKey, identity()));
166 Set<RuleKey> unrecognizedRuleKeys = ruleKeys.stream()
167 .filter(r -> !ruleDtos.containsKey(r))
170 if (!unrecognizedRuleKeys.isEmpty()) {
171 Map<String, DeprecatedRuleKeyDto> deprecatedRuleKeysByUuid = db.ruleDao().selectAllDeprecatedRuleKeys(dbSession).stream()
172 .filter(r -> r.getNewRepositoryKey() != null && r.getNewRuleKey() != null)
173 .filter(r -> unrecognizedRuleKeys.contains(RuleKey.of(r.getOldRepositoryKey(), r.getOldRuleKey())))
174 // ignore deprecated rule if the new rule key was already found in the list of imported rules
175 .filter(r -> !ruleKeys.contains(RuleKey.of(r.getNewRepositoryKey(), r.getNewRuleKey())))
176 .collect(Collectors.toMap(DeprecatedRuleKeyDto::getRuleUuid, identity()));
178 List<RuleDto> rulesBasedOnDeprecatedKeys = db.ruleDao().selectByUuids(dbSession, deprecatedRuleKeysByUuid.keySet());
179 for (RuleDto rule : rulesBasedOnDeprecatedKeys) {
180 DeprecatedRuleKeyDto deprecatedRuleKey = deprecatedRuleKeysByUuid.get(rule.getUuid());
181 RuleKey oldRuleKey = RuleKey.of(deprecatedRuleKey.getOldRepositoryKey(), deprecatedRuleKey.getOldRuleKey());
182 ruleDtos.put(oldRuleKey, rule);
189 private static void checkIfRulesFromExternalEngines(Collection<RuleDto> ruleDefinitions) {
190 List<RuleDto> externalRules = ruleDefinitions.stream()
191 .filter(RuleDto::isExternal)
194 if (!externalRules.isEmpty()) {
195 throw new IllegalArgumentException("The quality profile cannot be restored as it contains rules from external rule engines: "
196 + externalRules.stream().map(r -> r.getKey().toString()).collect(Collectors.joining(", ")));
200 private Map<RuleKey, RuleDto> createCustomRulesIfNotExist(DbSession dbSession, List<ImportedRule> rules, Map<RuleKey, RuleDto> ruleDefinitionsByKey) {
201 List<NewCustomRule> customRulesToCreate = rules.stream()
202 .filter(r -> ruleDefinitionsByKey.get(r.getRuleKey()) == null && r.isCustomRule())
203 .map(QProfileBackuperImpl::importedRuleToNewCustomRule)
206 if (!customRulesToCreate.isEmpty()) {
207 return db.ruleDao().selectByKeys(dbSession, ruleCreator.create(dbSession, customRulesToCreate).stream().map(RuleDto::getKey).toList())
209 .collect(Collectors.toMap(RuleDto::getKey, identity()));
211 return Collections.emptyMap();
214 private static NewCustomRule importedRuleToNewCustomRule(ImportedRule r) {
215 return NewCustomRule.createForCustomRule(r.getRuleKey(), r.getTemplateKey())
216 .setName(r.getName())
217 .setSeverity(r.getSeverity())
218 .setImpacts(r.getImpacts().entrySet().stream().map(i -> new NewCustomRule.Impact(i.getKey(), i.getValue())).toList())
219 .setStatus(RuleStatus.READY)
220 .setPreventReactivation(true)
221 .setType(RuleType.valueOf(r.getType()))
222 .setMarkdownDescription(r.getDescription())
223 .setParameters(r.getParameters());
226 private static List<RuleActivation> toRuleActivations(List<ImportedRule> rules, Map<RuleKey, RuleDto> ruleDefinitionsByKey) {
227 List<RuleActivation> activatedRule = new ArrayList<>();
229 for (ImportedRule r : rules) {
230 RuleDto ruleDto = ruleDefinitionsByKey.get(r.getRuleKey());
231 if (ruleDto == null) {
234 activatedRule.add(RuleActivation.create(
238 r.getPrioritizedRule(),
241 return activatedRule;
244 private enum BackupActiveRuleComparator implements Comparator<ExportRuleDto> {
248 public int compare(ExportRuleDto o1, ExportRuleDto o2) {
249 RuleKey rk1 = o1.getRuleKey();
250 RuleKey rk2 = o2.getRuleKey();
251 return new CompareToBuilder()
252 .append(rk1.repository(), rk2.repository())
253 .append(rk1.rule(), rk2.rule())