GH-9381: Introduce Control Bus commands management

Fixes: #9381

Currently, there is no way to know in one place what Control Bus commands are available and with what arguments

* Add `ControlBusCommandRegistry` infrastructure bean to gather control bus commands from beans and expose them for invocation
* Add `ControlBusController` to expose a `/control-bus` REST service against the mentioned `ControlBusCommandRegistry`
* Add `@EnableIntegrationManagement(loadControlBusCommands)` to be able to load all the Control Bus commands from the application context instead of on demand by default
* Deprecated existing SpEL(and Groovy)-based Control Bus functionality in favor of new, more manageable, logic
This commit is contained in:
Artem Bilan
2024-08-08 11:07:56 -04:00
parent 77e3b08d16
commit 4d787554b8
81 changed files with 1826 additions and 855 deletions

View File

@@ -0,0 +1,63 @@
/*
* Copyright 2024 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.integration.http.config;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Role;
import org.springframework.format.support.FormattingConversionService;
import org.springframework.integration.http.management.ControlBusController;
import org.springframework.integration.support.management.ControlBusCommandRegistry;
/**
* Registers the {@link ControlBusController} bean.
* <p>
* Also calls {@link ControlBusCommandRegistry#setEagerInitialization(boolean)} with {@code true}
* to load all the available commands in the application context.
*
* @author Artem Bilan
*
* @since 6.4
*/
@Configuration(proxyBeanMethods = false)
@Role(BeanDefinition.ROLE_INFRASTRUCTURE)
public class ControlBusControllerConfiguration {
private static final Log LOGGER = LogFactory.getLog(IntegrationGraphControllerRegistrar.class);
@Bean
ControlBusController controlBusController(ControlBusCommandRegistry controlBusCommandRegistry,
@Qualifier("mvcConversionService") FormattingConversionService conversionService) {
if (!HttpContextUtils.WEB_MVC_PRESENT && !HttpContextUtils.WEB_FLUX_PRESENT) {
LOGGER.warn("The 'IntegrationGraphController' isn't registered with the application context because" +
" there is no 'org.springframework.web.servlet.DispatcherServlet' or" +
" 'org.springframework.web.reactive.DispatcherHandler' in the classpath.");
return null;
}
controlBusCommandRegistry.setEagerInitialization(true);
return new ControlBusController(controlBusCommandRegistry, conversionService);
}
}

View File

@@ -0,0 +1,45 @@
/*
* Copyright 2016-2024 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.integration.http.config;
import java.lang.annotation.ElementType;
import java.lang.annotation.Inherited;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import org.springframework.context.annotation.Import;
/**
* Enables the
* {@link org.springframework.integration.http.management.ControlBusController} if
* {@code org.springframework.web.servlet.DispatcherServlet} or
* {@code org.springframework.web.reactive.DispatcherHandler} is present in the classpath.
*
* @author Artem Bilan
*
* @since 6.4
*
* @see org.springframework.integration.http.management.ControlBusController
*/
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Inherited
@Import(ControlBusControllerConfiguration.class)
public @interface EnableControlBusController {
}

View File

@@ -0,0 +1,149 @@
/*
* Copyright 2024 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.integration.http.management;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.BeanFactoryAware;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.expression.EvaluationContext;
import org.springframework.expression.Expression;
import org.springframework.format.support.FormattingConversionService;
import org.springframework.integration.context.IntegrationContextUtils;
import org.springframework.integration.support.management.ControlBusCommandRegistry;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
/**
* The REST Controller to provide the management API for Control Bus pattern.
*
* @author Artem Bilan
*
* @since 4.3
*/
@RestController
@RequestMapping("/control-bus")
public class ControlBusController implements BeanFactoryAware, InitializingBean {
private final ControlBusCommandRegistry controlBusCommandRegistry;
private final FormattingConversionService conversionService;
private BeanFactory beanFactory;
private EvaluationContext evaluationContext;
public ControlBusController(ControlBusCommandRegistry controlBusCommandRegistry,
@Qualifier("mvcConversionService") FormattingConversionService conversionService) {
this.controlBusCommandRegistry = controlBusCommandRegistry;
this.conversionService = conversionService;
}
@Override
public void setBeanFactory(BeanFactory beanFactory) throws BeansException {
this.beanFactory = beanFactory;
}
@Override
public void afterPropertiesSet() throws Exception {
this.evaluationContext = IntegrationContextUtils.getEvaluationContext(this.beanFactory);
}
@GetMapping(name = "getCommands")
public List<ControlBusBean> getCommands() {
return this.controlBusCommandRegistry.getCommands()
.entrySet()
.stream()
.map((beanEntry) -> createControlBusBean(beanEntry.getKey(), beanEntry.getValue()))
.toList();
}
@GetMapping(name = "getCommandsForBean", path = "/{beanName}")
public ControlBusBean getCommandsForBean(@PathVariable String beanName) {
Map<ControlBusCommandRegistry.CommandMethod, String> commandsForBean =
this.controlBusCommandRegistry.getCommands()
.get(beanName);
return createControlBusBean(beanName, commandsForBean);
}
private ControlBusBean createControlBusBean(String beanName,
Map<ControlBusCommandRegistry.CommandMethod, String> commandsForBean) {
List<ControlBusCommand> commands =
commandsForBean.keySet()
.stream()
.map(this::converControlBusCommand)
.toList();
return new ControlBusBean(beanName, commands);
}
private ControlBusCommand converControlBusCommand(ControlBusCommandRegistry.CommandMethod commandMethod) {
return new ControlBusCommand(commandMethod.getBeanName() + '.' + commandMethod.getMethodName(),
commandMethod.getDescription(),
Arrays.asList(commandMethod.getParameterTypes()));
}
@PostMapping(name = "invokeCommand", path = "/{command}")
public Object invokeCommand(@PathVariable String command,
@RequestBody(required = false) List<CommandArgument> arguments) {
Class<?>[] parameterTypes = new Class<?>[0];
if (!CollectionUtils.isEmpty(arguments)) {
parameterTypes = arguments.stream()
.map(CommandArgument::parameterType)
.toArray(Class<?>[]::new);
}
Expression commandExpression = this.controlBusCommandRegistry.getExpressionForCommand(command, parameterTypes);
Object[] parameterValues = null;
if (!CollectionUtils.isEmpty(arguments)) {
parameterValues = arguments.stream()
.map((arg) -> this.conversionService.convert(arg.value, arg.parameterType))
.toArray(Object[]::new);
}
return commandExpression.getValue(this.evaluationContext, parameterValues);
}
public record ControlBusBean(String beanName, List<ControlBusCommand> commands) {
}
public record ControlBusCommand(String command, String description, List<Class<?>> parameterTypes) {
}
public record CommandArgument(String value, Class<?> parameterType) {
}
}

View File

@@ -0,0 +1,163 @@
/*
* Copyright 2024 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.integration.http.management;
import org.hamcrest.Matchers;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.MediaType;
import org.springframework.integration.config.EnableIntegration;
import org.springframework.integration.http.config.EnableControlBusController;
import org.springframework.jmx.export.annotation.ManagedOperation;
import org.springframework.jmx.export.annotation.ManagedResource;
import org.springframework.test.annotation.DirtiesContext;
import org.springframework.test.context.junit.jupiter.web.SpringJUnitWebConfig;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.verify;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.handler;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
/**
* @author Artem Bilan
*
* @since 6.4
*/
@SpringJUnitWebConfig
@DirtiesContext
public class ControlBusControllerTests {
@Autowired
WebApplicationContext wac;
MockMvc mockMvc;
@Autowired
TestManagementComponent testManagementComponent;
@BeforeEach
void setup() {
this.mockMvc = MockMvcBuilders.webAppContextSetup(this.wac).build();
}
@Test
void allCommandsAreRegistered() throws Exception {
this.mockMvc.perform(get("/control-bus")
.accept(MediaType.APPLICATION_JSON))
.andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON_VALUE))
.andExpect(handler().handlerType(ControlBusController.class))
.andExpect(handler().methodName("getCommands"))
.andExpect(content().string(Matchers.containsString("testManagementComponent.operation")))
.andExpect(content().string(Matchers.containsString("testManagementComponent.operation2")))
.andExpect(content().string(Matchers.containsString("taskScheduler.setPoolSize")))
.andExpect(content().string(Matchers.containsString("integrationHeaderChannelRegistry.runReaper")))
.andExpect(content().string(Matchers.containsString("_org.springframework.integration.errorLogger.isRunning")))
.andExpect(content().string(Matchers.containsString("The overloaded operation with int argument")))
.andExpect(content().string(Matchers.containsString("The overloaded operation with two arguments")));
}
@Test
void commandsForBean() throws Exception {
this.mockMvc.perform(get("/control-bus/testManagementComponent")
.accept(MediaType.APPLICATION_JSON))
.andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON_VALUE))
.andExpect(handler().handlerType(ControlBusController.class))
.andExpect(handler().methodName("getCommandsForBean"))
.andExpect(content().string(Matchers.containsString("testManagementComponent.operation")))
.andExpect(content().string(Matchers.containsString("testManagementComponent.operation2")));
}
@Test
void controlBusCommandIsPerformedOverRestCall() throws Exception {
this.mockMvc.perform(post("/control-bus/testManagementComponent.operation")
.contentType(MediaType.APPLICATION_JSON)
.content("""
[
{
"value": "1",
"parameterType": "int"
}
]
"""))
.andExpect(status().isOk())
.andExpect(handler().handlerType(ControlBusController.class))
.andExpect(handler().methodName("invokeCommand"));
verify(this.testManagementComponent).operation(eq(1));
this.mockMvc.perform(post("/control-bus/testManagementComponent.operation2"))
.andExpect(status().isOk())
.andExpect(handler().handlerType(ControlBusController.class))
.andExpect(handler().methodName("invokeCommand"))
.andExpect(content().string("123"));
verify(this.testManagementComponent).operation2();
}
@Configuration
@EnableWebMvc
@EnableIntegration
@EnableControlBusController
static class ContextConfiguration {
@Bean
TestManagementComponent testManagementComponent() {
return spy(new TestManagementComponent());
}
}
@ManagedResource
private static class TestManagementComponent {
@ManagedOperation
public void operation() {
}
@ManagedOperation(description = "The overloaded operation with int argument")
public void operation(int input) {
}
@ManagedOperation(description = "The overloaded operation with two arguments")
public void operation(int input1, String input2) {
}
@ManagedOperation
public int operation2() {
return 123;
}
}
}