Provide remote restart auto-configuration

Provide auto-configuration for remote application update and restart.
Local classpath changes are now monitored via RemoteSpringApplication
and pushed to the remote server.

See gh-3086
This commit is contained in:
Phillip Webb
2015-06-01 13:23:41 -07:00
parent 6ac08aba04
commit 05ea2d77ef
8 changed files with 624 additions and 1 deletions

View File

@@ -20,6 +20,8 @@ import java.util.Collection;
import javax.servlet.Filter;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
@@ -33,6 +35,10 @@ import org.springframework.boot.developertools.remote.server.Handler;
import org.springframework.boot.developertools.remote.server.HandlerMapper;
import org.springframework.boot.developertools.remote.server.HttpStatusHandler;
import org.springframework.boot.developertools.remote.server.UrlHandlerMapper;
import org.springframework.boot.developertools.restart.server.DefaultSourceFolderUrlFilter;
import org.springframework.boot.developertools.restart.server.HttpRestartServer;
import org.springframework.boot.developertools.restart.server.HttpRestartServerHandler;
import org.springframework.boot.developertools.restart.server.SourceFolderUrlFilter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.server.ServerHttpRequest;
@@ -50,6 +56,9 @@ import org.springframework.http.server.ServerHttpRequest;
@EnableConfigurationProperties(DeveloperToolsProperties.class)
public class RemoteDeveloperToolsAutoConfiguration {
private static final Log logger = LogFactory
.getLog(RemoteDeveloperToolsAutoConfiguration.class);
@Autowired
private DeveloperToolsProperties properties;
@@ -67,4 +76,37 @@ public class RemoteDeveloperToolsAutoConfiguration {
return new DispatcherFilter(dispatcher);
}
/**
* Configuration for remote update and restarts.
*/
@ConditionalOnProperty(prefix = "spring.developertools.remote.restart", name = "enabled", matchIfMissing = true)
static class RemoteRestartConfiguration {
@Autowired
private DeveloperToolsProperties properties;
@Bean
@ConditionalOnMissingBean
public SourceFolderUrlFilter remoteRestartSourceFolderUrlFilter() {
return new DefaultSourceFolderUrlFilter();
}
@Bean
@ConditionalOnMissingBean
public HttpRestartServer remoteRestartHttpRestartServer(
SourceFolderUrlFilter sourceFolderUrlFilter) {
return new HttpRestartServer(sourceFolderUrlFilter);
}
@Bean
@ConditionalOnMissingBean(name = "remoteRestartHanderMapper")
public UrlHandlerMapper remoteRestartHanderMapper(HttpRestartServer server) {
String url = this.properties.getRemote().getContextPath() + "/restart";
logger.warn("Listening for remote restart updates on " + url);
Handler handler = new HttpRestartServerHandler(server);
return new UrlHandlerMapper(url, handler);
}
}
}

View File

@@ -16,7 +16,6 @@
package org.springframework.boot.developertools.autoconfigure;
/**
* Configuration properties for remote Spring Boot applications.
*
@@ -34,6 +33,8 @@ public class RemoteDeveloperToolsProperties {
*/
private String contextPath = DEFAULT_CONTEXT_PATH;
private Restart restart = new Restart();
public String getContextPath() {
return this.contextPath;
}
@@ -42,4 +43,25 @@ public class RemoteDeveloperToolsProperties {
this.contextPath = contextPath;
}
public Restart getRestart() {
return this.restart;
}
public static class Restart {
/**
* Enable remote restart
*/
private boolean enabled = true;
public boolean isEnabled() {
return this.enabled;
}
public void setEnabled(boolean enabled) {
this.enabled = enabled;
}
}
}

View File

@@ -0,0 +1,145 @@
/*
* Copyright 2012-2015 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
*
* http://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.boot.developertools.remote.client;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.boot.developertools.classpath.ClassPathChangedEvent;
import org.springframework.boot.developertools.filewatch.ChangedFile;
import org.springframework.boot.developertools.filewatch.ChangedFiles;
import org.springframework.boot.developertools.restart.classloader.ClassLoaderFile;
import org.springframework.boot.developertools.restart.classloader.ClassLoaderFile.Kind;
import org.springframework.boot.developertools.restart.classloader.ClassLoaderFiles;
import org.springframework.context.ApplicationListener;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.client.ClientHttpRequest;
import org.springframework.http.client.ClientHttpRequestFactory;
import org.springframework.http.client.ClientHttpResponse;
import org.springframework.util.Assert;
import org.springframework.util.FileCopyUtils;
/**
* Listens and pushes any classpath updates to a remote endpoint.
*
* @author Phillip Webb
* @since 1.3.0
*/
public class ClassPathChangeUploader implements
ApplicationListener<ClassPathChangedEvent> {
private static final Map<ChangedFile.Type, ClassLoaderFile.Kind> TYPE_MAPPINGS;
static {
Map<ChangedFile.Type, ClassLoaderFile.Kind> map = new HashMap<ChangedFile.Type, ClassLoaderFile.Kind>();
map.put(ChangedFile.Type.ADD, ClassLoaderFile.Kind.ADDED);
map.put(ChangedFile.Type.DELETE, ClassLoaderFile.Kind.DELETED);
map.put(ChangedFile.Type.MODIFY, ClassLoaderFile.Kind.MODIFIED);
TYPE_MAPPINGS = Collections.unmodifiableMap(map);
}
private static final Log logger = LogFactory.getLog(ClassPathChangeUploader.class);
private final URI uri;
private final ClientHttpRequestFactory requestFactory;
public ClassPathChangeUploader(String url, ClientHttpRequestFactory requestFactory) {
Assert.hasLength(url, "URL must not be empty");
Assert.notNull(requestFactory, "RequestFactory must not be null");
try {
this.uri = new URL(url).toURI();
}
catch (URISyntaxException ex) {
throw new IllegalArgumentException("Malformed URL '" + url + "'");
}
catch (MalformedURLException ex) {
throw new IllegalArgumentException("Malformed URL '" + url + "'");
}
this.requestFactory = requestFactory;
}
@Override
public void onApplicationEvent(ClassPathChangedEvent event) {
try {
ClassLoaderFiles classLoaderFiles = getClassLoaderFiles(event);
ClientHttpRequest request = this.requestFactory.createRequest(this.uri,
HttpMethod.POST);
byte[] bytes = serialize(classLoaderFiles);
HttpHeaders headers = request.getHeaders();
headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
headers.setContentLength(bytes.length);
FileCopyUtils.copy(bytes, request.getBody());
logUpload(classLoaderFiles);
ClientHttpResponse response = request.execute();
Assert.state(response.getStatusCode() == HttpStatus.OK, "Unexpected "
+ response.getStatusCode() + " response uploading class files");
}
catch (IOException ex) {
throw new IllegalStateException(ex);
}
}
private void logUpload(ClassLoaderFiles classLoaderFiles) {
int size = classLoaderFiles.size();
logger.info("Uploaded " + size + " class "
+ (size == 1 ? "resource" : "resources"));
}
private byte[] serialize(ClassLoaderFiles classLoaderFiles) throws IOException {
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
ObjectOutputStream objectOutputStream = new ObjectOutputStream(outputStream);
objectOutputStream.writeObject(classLoaderFiles);
objectOutputStream.close();
return outputStream.toByteArray();
}
private ClassLoaderFiles getClassLoaderFiles(ClassPathChangedEvent event)
throws IOException {
ClassLoaderFiles files = new ClassLoaderFiles();
for (ChangedFiles changedFiles : event.getChangeSet()) {
String sourceFolder = changedFiles.getSourceFolder().getAbsolutePath();
for (ChangedFile changedFile : changedFiles) {
files.addFile(sourceFolder, changedFile.getRelativeName(),
asClassLoaderFile(changedFile));
}
}
return files;
}
private ClassLoaderFile asClassLoaderFile(ChangedFile changedFile) throws IOException {
ClassLoaderFile.Kind kind = TYPE_MAPPINGS.get(changedFile.getType());
byte[] bytes = (kind == Kind.DELETED ? null : FileCopyUtils
.copyToByteArray(changedFile.getFile()));
long lastModified = (kind == Kind.DELETED ? System.currentTimeMillis()
: changedFile.getFile().lastModified());
return new ClassLoaderFile(kind, lastModified, bytes);
}
}

View File

@@ -16,10 +16,22 @@
package org.springframework.boot.developertools.remote.client;
import java.net.URL;
import javax.annotation.PostConstruct;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.boot.developertools.autoconfigure.DeveloperToolsProperties;
import org.springframework.boot.developertools.autoconfigure.RemoteDeveloperToolsProperties;
import org.springframework.boot.developertools.classpath.ClassPathFileSystemWatcher;
import org.springframework.boot.developertools.classpath.ClassPathRestartStrategy;
import org.springframework.boot.developertools.classpath.PatternClassPathRestartStrategy;
import org.springframework.boot.developertools.restart.DefaultRestartInitializer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.support.PropertySourcesPlaceholderConfigurer;
@@ -37,6 +49,8 @@ import org.springframework.http.client.SimpleClientHttpRequestFactory;
@EnableConfigurationProperties(DeveloperToolsProperties.class)
public class RemoteClientConfiguration {
private static final Log logger = LogFactory.getLog(RemoteClientConfiguration.class);
@Autowired
private DeveloperToolsProperties properties;
@@ -53,4 +67,50 @@ public class RemoteClientConfiguration {
return new SimpleClientHttpRequestFactory();
}
@PostConstruct
private void logWarnings() {
RemoteDeveloperToolsProperties remoteProperties = this.properties.getRemote();
if (!remoteProperties.getRestart().isEnabled()) {
logger.warn("Remote restart is not enabled.");
}
}
/**
* Client configuration for remote update and restarts.
*/
@ConditionalOnProperty(prefix = "spring.developertools.remote.restart", name = "enabled", matchIfMissing = true)
static class RemoteRestartClientConfiguration {
@Autowired
private DeveloperToolsProperties properties;
@Value("${remoteUrl}")
private String remoteUrl;
@Bean
public ClassPathFileSystemWatcher classPathFileSystemWatcher() {
DefaultRestartInitializer restartInitializer = new DefaultRestartInitializer();
URL[] urls = restartInitializer.getInitialUrls(Thread.currentThread());
if (urls == null) {
urls = new URL[0];
}
return new ClassPathFileSystemWatcher(classPathRestartStrategy(), urls);
}
@Bean
public ClassPathRestartStrategy classPathRestartStrategy() {
return new PatternClassPathRestartStrategy(this.properties.getRestart()
.getExclude());
}
@Bean
public ClassPathChangeUploader classPathChangeUploader(
ClientHttpRequestFactory requestFactory) {
String url = this.remoteUrl + this.properties.getRemote().getContextPath()
+ "/restart";
return new ClassPathChangeUploader(url, requestFactory);
}
}
}