You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

BulkApplyTemplateAction.java 11KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276
  1. /*
  2. * SonarQube
  3. * Copyright (C) 2009-2021 SonarSource SA
  4. * mailto:info AT sonarsource DOT com
  5. *
  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.
  10. *
  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.
  15. *
  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.
  19. */
  20. package org.sonar.server.permission.ws.template;
  21. import java.util.Collection;
  22. import java.util.HashSet;
  23. import java.util.List;
  24. import javax.annotation.CheckForNull;
  25. import javax.annotation.Nullable;
  26. import org.sonar.api.resources.Qualifiers;
  27. import org.sonar.api.resources.ResourceTypes;
  28. import org.sonar.api.server.ws.Change;
  29. import org.sonar.api.server.ws.Request;
  30. import org.sonar.api.server.ws.Response;
  31. import org.sonar.api.server.ws.WebService;
  32. import org.sonar.api.server.ws.WebService.Param;
  33. import org.sonar.core.i18n.I18n;
  34. import org.sonar.db.DatabaseUtils;
  35. import org.sonar.db.DbClient;
  36. import org.sonar.db.DbSession;
  37. import org.sonar.db.component.ComponentDto;
  38. import org.sonar.db.component.ComponentQuery;
  39. import org.sonar.db.permission.template.PermissionTemplateDto;
  40. import org.sonar.server.permission.PermissionTemplateService;
  41. import org.sonar.server.permission.ws.PermissionWsSupport;
  42. import org.sonar.server.permission.ws.PermissionsWsAction;
  43. import org.sonar.server.permission.ws.WsParameters;
  44. import org.sonar.server.project.Visibility;
  45. import org.sonar.server.user.UserSession;
  46. import static java.lang.String.format;
  47. import static java.util.Collections.singleton;
  48. import static java.util.Objects.requireNonNull;
  49. import static java.util.Optional.ofNullable;
  50. import static org.sonar.api.utils.DateUtils.parseDateOrDateTime;
  51. import static org.sonar.server.permission.PermissionPrivilegeChecker.checkGlobalAdmin;
  52. import static org.sonar.server.permission.ws.template.WsTemplateRef.newTemplateRef;
  53. import static org.sonar.server.ws.KeyExamples.KEY_PROJECT_EXAMPLE_001;
  54. import static org.sonar.server.ws.KeyExamples.KEY_PROJECT_EXAMPLE_002;
  55. import static org.sonar.server.ws.WsParameterBuilder.createRootQualifiersParameter;
  56. import static org.sonar.server.ws.WsParameterBuilder.QualifierParameterContext.newQualifierParameterContext;
  57. import static org.sonarqube.ws.client.permission.PermissionsWsParameters.PARAM_TEMPLATE_ID;
  58. import static org.sonarqube.ws.client.permission.PermissionsWsParameters.PARAM_TEMPLATE_NAME;
  59. import static org.sonarqube.ws.client.project.ProjectsWsParameters.PARAM_ANALYZED_BEFORE;
  60. import static org.sonarqube.ws.client.project.ProjectsWsParameters.PARAM_ON_PROVISIONED_ONLY;
  61. import static org.sonarqube.ws.client.project.ProjectsWsParameters.PARAM_PROJECTS;
  62. import static org.sonarqube.ws.client.project.ProjectsWsParameters.PARAM_QUALIFIERS;
  63. import static org.sonarqube.ws.client.project.ProjectsWsParameters.PARAM_VISIBILITY;
  64. public class BulkApplyTemplateAction implements PermissionsWsAction {
  65. private final DbClient dbClient;
  66. private final UserSession userSession;
  67. private final PermissionTemplateService permissionTemplateService;
  68. private final PermissionWsSupport wsSupport;
  69. private final I18n i18n;
  70. private final ResourceTypes resourceTypes;
  71. public BulkApplyTemplateAction(DbClient dbClient, UserSession userSession, PermissionTemplateService permissionTemplateService, PermissionWsSupport wsSupport, I18n i18n,
  72. ResourceTypes resourceTypes) {
  73. this.dbClient = dbClient;
  74. this.userSession = userSession;
  75. this.permissionTemplateService = permissionTemplateService;
  76. this.wsSupport = wsSupport;
  77. this.i18n = i18n;
  78. this.resourceTypes = resourceTypes;
  79. }
  80. @Override
  81. public void define(WebService.NewController context) {
  82. WebService.NewAction action = context.createAction("bulk_apply_template")
  83. .setDescription("Apply a permission template to several projects.<br />" +
  84. "The template id or name must be provided.<br />" +
  85. "Requires the following permission: 'Administer System'.")
  86. .setPost(true)
  87. .setSince("5.5")
  88. .setChangelog(new Change("6.7.2", format("Parameter %s accepts maximum %d values", PARAM_PROJECTS, DatabaseUtils.PARTITION_SIZE_FOR_ORACLE)))
  89. .setHandler(this);
  90. action.createParam(Param.TEXT_QUERY)
  91. .setDescription("Limit search to: <ul>" +
  92. "<li>project names that contain the supplied string</li>" +
  93. "<li>project keys that are exactly the same as the supplied string</li>" +
  94. "</ul>")
  95. .setExampleValue("apac");
  96. createRootQualifiersParameter(action, newQualifierParameterContext(i18n, resourceTypes))
  97. .setDefaultValue(Qualifiers.PROJECT);
  98. WsParameters.createTemplateParameters(action);
  99. action
  100. .createParam(PARAM_PROJECTS)
  101. .setDescription("Comma-separated list of project keys")
  102. .setSince("6.6")
  103. // Limitation of ComponentDao#selectByQuery(), max 1000 values are accepted.
  104. // Restricting size of HTTP parameter allows to not fail with SQL error
  105. .setMaxValuesAllowed(DatabaseUtils.PARTITION_SIZE_FOR_ORACLE)
  106. .setExampleValue(String.join(",", KEY_PROJECT_EXAMPLE_001, KEY_PROJECT_EXAMPLE_002));
  107. action.createParam(PARAM_VISIBILITY)
  108. .setDescription("Filter the projects that should be visible to everyone (%s), or only specific user/groups (%s).<br/>" +
  109. "If no visibility is specified, the default project visibility will be used.",
  110. Visibility.PUBLIC.getLabel(), Visibility.PRIVATE.getLabel())
  111. .setRequired(false)
  112. .setInternal(true)
  113. .setSince("6.6")
  114. .setPossibleValues(Visibility.getLabels());
  115. action.createParam(PARAM_ANALYZED_BEFORE)
  116. .setDescription("Filter the projects for which last analysis is older than the given date (exclusive).<br> " +
  117. "Either a date (server timezone) or datetime can be provided.")
  118. .setSince("6.6")
  119. .setExampleValue("2017-10-19 or 2017-10-19T13:00:00+0200");
  120. action.createParam(PARAM_ON_PROVISIONED_ONLY)
  121. .setDescription("Filter the projects that are provisioned")
  122. .setBooleanPossibleValues()
  123. .setDefaultValue("false")
  124. .setSince("6.6");
  125. }
  126. @Override
  127. public void handle(Request request, Response response) throws Exception {
  128. doHandle(toBulkApplyTemplateWsRequest(request));
  129. response.noContent();
  130. }
  131. private void doHandle(BulkApplyTemplateRequest request) {
  132. try (DbSession dbSession = dbClient.openSession(false)) {
  133. PermissionTemplateDto template = wsSupport.findTemplate(dbSession, newTemplateRef(
  134. request.getTemplateId(), request.getTemplateName()));
  135. checkGlobalAdmin(userSession);
  136. ComponentQuery componentQuery = buildDbQuery(request);
  137. List<ComponentDto> projects = dbClient.componentDao().selectByQuery(dbSession, componentQuery, 0, Integer.MAX_VALUE);
  138. permissionTemplateService.applyAndCommit(dbSession, template, projects);
  139. }
  140. }
  141. private static BulkApplyTemplateRequest toBulkApplyTemplateWsRequest(Request request) {
  142. return new BulkApplyTemplateRequest()
  143. .setTemplateId(request.param(PARAM_TEMPLATE_ID))
  144. .setTemplateName(request.param(PARAM_TEMPLATE_NAME))
  145. .setQualifiers(request.mandatoryParamAsStrings(PARAM_QUALIFIERS))
  146. .setQuery(request.param(Param.TEXT_QUERY))
  147. .setVisibility(request.param(PARAM_VISIBILITY))
  148. .setOnProvisionedOnly(request.mandatoryParamAsBoolean(PARAM_ON_PROVISIONED_ONLY))
  149. .setAnalyzedBefore(request.param(PARAM_ANALYZED_BEFORE))
  150. .setProjects(request.paramAsStrings(PARAM_PROJECTS));
  151. }
  152. private static ComponentQuery buildDbQuery(BulkApplyTemplateRequest request) {
  153. Collection<String> qualifiers = request.getQualifiers();
  154. ComponentQuery.Builder query = ComponentQuery.builder()
  155. .setQualifiers(qualifiers.toArray(new String[qualifiers.size()]));
  156. ofNullable(request.getQuery()).ifPresent(q -> {
  157. query.setNameOrKeyQuery(q);
  158. query.setPartialMatchOnKey(true);
  159. });
  160. ofNullable(request.getVisibility()).ifPresent(v -> query.setPrivate(Visibility.isPrivate(v)));
  161. ofNullable(request.getAnalyzedBefore()).ifPresent(d -> query.setAnalyzedBefore(parseDateOrDateTime(d).getTime()));
  162. query.setOnProvisionedOnly(request.isOnProvisionedOnly());
  163. ofNullable(request.getProjects()).ifPresent(keys -> query.setComponentKeys(new HashSet<>(keys)));
  164. return query.build();
  165. }
  166. private static class BulkApplyTemplateRequest {
  167. private String templateId;
  168. private String templateName;
  169. private String query;
  170. private Collection<String> qualifiers = singleton(Qualifiers.PROJECT);
  171. private String visibility;
  172. private String analyzedBefore;
  173. private boolean onProvisionedOnly = false;
  174. private Collection<String> projects;
  175. @CheckForNull
  176. public String getTemplateId() {
  177. return templateId;
  178. }
  179. public BulkApplyTemplateRequest setTemplateId(@Nullable String templateId) {
  180. this.templateId = templateId;
  181. return this;
  182. }
  183. @CheckForNull
  184. public String getTemplateName() {
  185. return templateName;
  186. }
  187. public BulkApplyTemplateRequest setTemplateName(@Nullable String templateName) {
  188. this.templateName = templateName;
  189. return this;
  190. }
  191. @CheckForNull
  192. public String getQuery() {
  193. return query;
  194. }
  195. public BulkApplyTemplateRequest setQuery(@Nullable String query) {
  196. this.query = query;
  197. return this;
  198. }
  199. public Collection<String> getQualifiers() {
  200. return qualifiers;
  201. }
  202. public BulkApplyTemplateRequest setQualifiers(Collection<String> qualifiers) {
  203. this.qualifiers = requireNonNull(qualifiers);
  204. return this;
  205. }
  206. @CheckForNull
  207. public String getVisibility() {
  208. return visibility;
  209. }
  210. public BulkApplyTemplateRequest setVisibility(@Nullable String visibility) {
  211. this.visibility = visibility;
  212. return this;
  213. }
  214. @CheckForNull
  215. public String getAnalyzedBefore() {
  216. return analyzedBefore;
  217. }
  218. public BulkApplyTemplateRequest setAnalyzedBefore(@Nullable String analyzedBefore) {
  219. this.analyzedBefore = analyzedBefore;
  220. return this;
  221. }
  222. public boolean isOnProvisionedOnly() {
  223. return onProvisionedOnly;
  224. }
  225. public BulkApplyTemplateRequest setOnProvisionedOnly(boolean onProvisionedOnly) {
  226. this.onProvisionedOnly = onProvisionedOnly;
  227. return this;
  228. }
  229. @CheckForNull
  230. public Collection<String> getProjects() {
  231. return projects;
  232. }
  233. public BulkApplyTemplateRequest setProjects(@Nullable Collection<String> projects) {
  234. this.projects = projects;
  235. return this;
  236. }
  237. }
  238. }