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;
55 public class QProfileBackuperImpl implements QProfileBackuper {
57 private final DbClient db;
58 private final QProfileReset profileReset;
59 private final QProfileFactory profileFactory;
60 private final RuleCreator ruleCreator;
61 private final QProfileParser qProfileParser;
63 public QProfileBackuperImpl(DbClient db, QProfileReset profileReset, QProfileFactory profileFactory,
64 RuleCreator ruleCreator, QProfileParser qProfileParser) {
66 this.profileReset = profileReset;
67 this.profileFactory = profileFactory;
68 this.ruleCreator = ruleCreator;
69 this.qProfileParser = qProfileParser;
73 public void backup(DbSession dbSession, QProfileDto profile, Writer writer) {
74 List<ExportRuleDto> rulesToExport = db.qualityProfileExportDao().selectRulesByProfile(dbSession, profile);
75 rulesToExport.sort(BackupActiveRuleComparator.INSTANCE);
76 qProfileParser.writeXml(writer, profile, rulesToExport.iterator());
80 public QProfileRestoreSummary copy(DbSession dbSession, QProfileDto from, QProfileDto to) {
81 List<ExportRuleDto> rulesToExport = db.qualityProfileExportDao().selectRulesByProfile(dbSession, from);
82 rulesToExport.sort(BackupActiveRuleComparator.INSTANCE);
84 ImportedQProfile qProfile = toImportedQProfile(rulesToExport, to.getName(), to.getLanguage());
85 return restore(dbSession, qProfile, name -> to);
88 private static ImportedQProfile toImportedQProfile(List<ExportRuleDto> exportRules, String profileName, String profileLang) {
89 List<ImportedRule> importedRules = new ArrayList<>(exportRules.size());
91 for (ExportRuleDto exportRuleDto : exportRules) {
92 var ruleKey = exportRuleDto.getRuleKey();
93 ImportedRule importedRule = new ImportedRule();
94 importedRule.setName(exportRuleDto.getName());
95 importedRule.setRepository(ruleKey.repository());
96 importedRule.setKey(ruleKey.rule());
97 importedRule.setSeverity(exportRuleDto.getSeverityString());
98 if (exportRuleDto.isCustomRule()) {
99 importedRule.setTemplate(exportRuleDto.getTemplateRuleKey().rule());
100 importedRule.setDescription(exportRuleDto.getDescriptionOrThrow());
102 importedRule.setType(exportRuleDto.getRuleType().name());
103 importedRule.setParameters(exportRuleDto.getParams().stream().collect(Collectors.toMap(ExportRuleParamDto::getKey, ExportRuleParamDto::getValue)));
104 importedRules.add(importedRule);
107 return new ImportedQProfile(profileName, profileLang, importedRules);
111 public QProfileRestoreSummary restore(DbSession dbSession, Reader backup, @Nullable String overriddenProfileName) {
112 return restore(dbSession, backup, nameInBackup -> {
113 QProfileName targetName = nameInBackup;
114 if (overriddenProfileName != null) {
115 targetName = new QProfileName(nameInBackup.getLanguage(), overriddenProfileName);
117 return profileFactory.getOrCreateCustom(dbSession, targetName);
122 public QProfileRestoreSummary restore(DbSession dbSession, Reader backup, QProfileDto profile) {
123 return restore(dbSession, backup, nameInBackup -> {
124 checkArgument(profile.getLanguage().equals(nameInBackup.getLanguage()),
125 "Can't restore %s backup on %s profile with key [%s]. Languages are different.", nameInBackup.getLanguage(), profile.getLanguage(), profile.getKee());
130 private QProfileRestoreSummary restore(DbSession dbSession, Reader backup, Function<QProfileName, QProfileDto> profileLoader) {
131 ImportedQProfile qProfile = qProfileParser.readXml(backup);
132 return restore(dbSession, qProfile, profileLoader);
135 private QProfileRestoreSummary restore(DbSession dbSession, ImportedQProfile qProfile, Function<QProfileName, QProfileDto> profileLoader) {
136 QProfileName targetName = new QProfileName(qProfile.getProfileLang(), qProfile.getProfileName());
137 QProfileDto targetProfile = profileLoader.apply(targetName);
139 List<ImportedRule> importedRules = qProfile.getRules();
141 Map<RuleKey, RuleDto> ruleKeyToDto = getImportedRulesDtos(dbSession, importedRules);
142 checkIfRulesFromExternalEngines(ruleKeyToDto.values());
144 Map<RuleKey, RuleDto> customRulesDefinitions = createCustomRulesIfNotExist(dbSession, importedRules, ruleKeyToDto);
145 ruleKeyToDto.putAll(customRulesDefinitions);
147 List<RuleActivation> ruleActivations = toRuleActivations(importedRules, ruleKeyToDto);
149 BulkChangeResult changes = profileReset.reset(dbSession, targetProfile, ruleActivations);
150 return new QProfileRestoreSummary(targetProfile, changes);
154 * Returns map of rule definition for an imported rule key.
155 * 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).
157 private Map<RuleKey, RuleDto> getImportedRulesDtos(DbSession dbSession, List<ImportedRule> rules) {
158 Set<RuleKey> ruleKeys = rules.stream()
159 .map(ImportedRule::getRuleKey)
161 Map<RuleKey, RuleDto> ruleDtos = db.ruleDao().selectByKeys(dbSession, ruleKeys).stream()
162 .collect(Collectors.toMap(RuleDto::getKey, identity()));
164 Set<RuleKey> unrecognizedRuleKeys = ruleKeys.stream()
165 .filter(r -> !ruleDtos.containsKey(r))
168 if (!unrecognizedRuleKeys.isEmpty()) {
169 Map<String, DeprecatedRuleKeyDto> deprecatedRuleKeysByUuid = db.ruleDao().selectAllDeprecatedRuleKeys(dbSession).stream()
170 .filter(r -> r.getNewRepositoryKey() != null && r.getNewRuleKey() != null)
171 .filter(r -> unrecognizedRuleKeys.contains(RuleKey.of(r.getOldRepositoryKey(), r.getOldRuleKey())))
172 // ignore deprecated rule if the new rule key was already found in the list of imported rules
173 .filter(r -> !ruleKeys.contains(RuleKey.of(r.getNewRepositoryKey(), r.getNewRuleKey())))
174 .collect(Collectors.toMap(DeprecatedRuleKeyDto::getRuleUuid, identity()));
176 List<RuleDto> rulesBasedOnDeprecatedKeys = db.ruleDao().selectByUuids(dbSession, deprecatedRuleKeysByUuid.keySet());
177 for (RuleDto rule : rulesBasedOnDeprecatedKeys) {
178 DeprecatedRuleKeyDto deprecatedRuleKey = deprecatedRuleKeysByUuid.get(rule.getUuid());
179 RuleKey oldRuleKey = RuleKey.of(deprecatedRuleKey.getOldRepositoryKey(), deprecatedRuleKey.getOldRuleKey());
180 ruleDtos.put(oldRuleKey, rule);
187 private static void checkIfRulesFromExternalEngines(Collection<RuleDto> ruleDefinitions) {
188 List<RuleDto> externalRules = ruleDefinitions.stream()
189 .filter(RuleDto::isExternal)
192 if (!externalRules.isEmpty()) {
193 throw new IllegalArgumentException("The quality profile cannot be restored as it contains rules from external rule engines: "
194 + externalRules.stream().map(r -> r.getKey().toString()).collect(Collectors.joining(", ")));
198 private Map<RuleKey, RuleDto> createCustomRulesIfNotExist(DbSession dbSession, List<ImportedRule> rules, Map<RuleKey, RuleDto> ruleDefinitionsByKey) {
199 List<NewCustomRule> customRulesToCreate = rules.stream()
200 .filter(r -> ruleDefinitionsByKey.get(r.getRuleKey()) == null && r.isCustomRule())
201 .map(QProfileBackuperImpl::importedRuleToNewCustomRule)
204 if (!customRulesToCreate.isEmpty()) {
205 return db.ruleDao().selectByKeys(dbSession, ruleCreator.create(dbSession, customRulesToCreate).stream().map(RuleDto::getKey).toList())
207 .collect(Collectors.toMap(RuleDto::getKey, identity()));
209 return Collections.emptyMap();
212 private static NewCustomRule importedRuleToNewCustomRule(ImportedRule r) {
213 return NewCustomRule.createForCustomRule(r.getRuleKey(), r.getTemplateKey())
214 .setName(r.getName())
215 .setSeverity(r.getSeverity())
216 .setStatus(RuleStatus.READY)
217 .setPreventReactivation(true)
218 .setType(RuleType.valueOf(r.getType()))
219 .setMarkdownDescription(r.getDescription())
220 .setParameters(r.getParameters());
223 private static List<RuleActivation> toRuleActivations(List<ImportedRule> rules, Map<RuleKey, RuleDto> ruleDefinitionsByKey) {
224 List<RuleActivation> activatedRule = new ArrayList<>();
226 for (ImportedRule r : rules) {
227 RuleDto ruleDto = ruleDefinitionsByKey.get(r.getRuleKey());
228 if (ruleDto == null) {
231 activatedRule.add(RuleActivation.create(ruleDto.getUuid(), r.getSeverity(), r.getParameters()));
233 return activatedRule;
236 private enum BackupActiveRuleComparator implements Comparator<ExportRuleDto> {
240 public int compare(ExportRuleDto o1, ExportRuleDto o2) {
241 RuleKey rk1 = o1.getRuleKey();
242 RuleKey rk2 = o2.getRuleKey();
243 return new CompareToBuilder()
244 .append(rk1.repository(), rk2.repository())
245 .append(rk1.rule(), rk2.rule())