|
| 1 | +/* |
| 2 | + * Copyright 2012-2023 the original author or authors. |
| 3 | + * |
| 4 | + * Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | + * you may not use this file except in compliance with the License. |
| 6 | + * You may obtain a copy of the License at |
| 7 | + * |
| 8 | + * https://www.apache.org/licenses/LICENSE-2.0 |
| 9 | + * |
| 10 | + * Unless required by applicable law or agreed to in writing, software |
| 11 | + * distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | + * See the License for the specific language governing permissions and |
| 14 | + * limitations under the License. |
| 15 | + */ |
| 16 | + |
| 17 | +package org.springframework.boot.autoconfigure.ssl; |
| 18 | + |
| 19 | +import java.io.Closeable; |
| 20 | +import java.io.IOException; |
| 21 | +import java.io.UncheckedIOException; |
| 22 | +import java.nio.file.ClosedWatchServiceException; |
| 23 | +import java.nio.file.FileSystems; |
| 24 | +import java.nio.file.Files; |
| 25 | +import java.nio.file.Path; |
| 26 | +import java.nio.file.StandardWatchEventKinds; |
| 27 | +import java.nio.file.WatchEvent; |
| 28 | +import java.nio.file.WatchKey; |
| 29 | +import java.nio.file.WatchService; |
| 30 | +import java.time.Duration; |
| 31 | +import java.util.HashSet; |
| 32 | +import java.util.List; |
| 33 | +import java.util.Map; |
| 34 | +import java.util.Set; |
| 35 | +import java.util.concurrent.ConcurrentHashMap; |
| 36 | +import java.util.concurrent.CopyOnWriteArrayList; |
| 37 | +import java.util.concurrent.TimeUnit; |
| 38 | +import java.util.stream.Collectors; |
| 39 | + |
| 40 | +import org.apache.commons.logging.Log; |
| 41 | +import org.apache.commons.logging.LogFactory; |
| 42 | + |
| 43 | +import org.springframework.core.log.LogMessage; |
| 44 | +import org.springframework.util.Assert; |
| 45 | + |
| 46 | +/** |
| 47 | + * Watches files and directories and triggers a callback on change. |
| 48 | + * |
| 49 | + * @author Moritz Halbritter |
| 50 | + * @author Phillip Webb |
| 51 | + */ |
| 52 | +class FileWatcher implements Closeable { |
| 53 | + |
| 54 | + private static final Log logger = LogFactory.getLog(FileWatcher.class); |
| 55 | + |
| 56 | + private final Duration quietPeriod; |
| 57 | + |
| 58 | + private final Object lock = new Object(); |
| 59 | + |
| 60 | + private WatcherThread thread; |
| 61 | + |
| 62 | + /** |
| 63 | + * Create a new {@link FileWatcher} instance. |
| 64 | + * @param quietPeriod the duration that no file changes should occur before triggering |
| 65 | + * actions |
| 66 | + */ |
| 67 | + FileWatcher(Duration quietPeriod) { |
| 68 | + Assert.notNull(quietPeriod, "QuietPeriod must not be null"); |
| 69 | + this.quietPeriod = quietPeriod; |
| 70 | + } |
| 71 | + |
| 72 | + /** |
| 73 | + * Watch the given files or directories for changes. |
| 74 | + * @param paths the files or directories to watch |
| 75 | + * @param action the action to take when changes are detected |
| 76 | + */ |
| 77 | + void watch(Set<Path> paths, Runnable action) { |
| 78 | + Assert.notNull(paths, "Paths must not be null"); |
| 79 | + Assert.notNull(action, "Action must not be null"); |
| 80 | + if (paths.isEmpty()) { |
| 81 | + return; |
| 82 | + } |
| 83 | + synchronized (this.lock) { |
| 84 | + try { |
| 85 | + if (this.thread == null) { |
| 86 | + this.thread = new WatcherThread(); |
| 87 | + this.thread.start(); |
| 88 | + } |
| 89 | + this.thread.register(new Registration(paths, action)); |
| 90 | + } |
| 91 | + catch (IOException ex) { |
| 92 | + throw new UncheckedIOException("Failed to register paths for watching: " + paths, ex); |
| 93 | + } |
| 94 | + } |
| 95 | + } |
| 96 | + |
| 97 | + @Override |
| 98 | + public void close() throws IOException { |
| 99 | + synchronized (this.lock) { |
| 100 | + if (this.thread != null) { |
| 101 | + this.thread.close(); |
| 102 | + this.thread.interrupt(); |
| 103 | + try { |
| 104 | + this.thread.join(); |
| 105 | + } |
| 106 | + catch (InterruptedException ex) { |
| 107 | + Thread.currentThread().interrupt(); |
| 108 | + } |
| 109 | + this.thread = null; |
| 110 | + } |
| 111 | + } |
| 112 | + } |
| 113 | + |
| 114 | + /** |
| 115 | + * The watcher thread used to check for changes. |
| 116 | + */ |
| 117 | + private class WatcherThread extends Thread implements Closeable { |
| 118 | + |
| 119 | + private final WatchService watchService = FileSystems.getDefault().newWatchService(); |
| 120 | + |
| 121 | + private final Map<WatchKey, List<Registration>> registrations = new ConcurrentHashMap<>(); |
| 122 | + |
| 123 | + private volatile boolean running = true; |
| 124 | + |
| 125 | + WatcherThread() throws IOException { |
| 126 | + setName("ssl-bundle-watcher"); |
| 127 | + setDaemon(true); |
| 128 | + setUncaughtExceptionHandler(this::onThreadException); |
| 129 | + } |
| 130 | + |
| 131 | + private void onThreadException(Thread thread, Throwable throwable) { |
| 132 | + logger.error("Uncaught exception in file watcher thread", throwable); |
| 133 | + } |
| 134 | + |
| 135 | + void register(Registration registration) throws IOException { |
| 136 | + for (Path path : registration.paths()) { |
| 137 | + if (!Files.isRegularFile(path) && !Files.isDirectory(path)) { |
| 138 | + throw new IOException("'%s' is neither a file nor a directory".formatted(path)); |
| 139 | + } |
| 140 | + Path directory = Files.isDirectory(path) ? path : path.getParent(); |
| 141 | + WatchKey watchKey = register(directory); |
| 142 | + this.registrations.computeIfAbsent(watchKey, (key) -> new CopyOnWriteArrayList<>()).add(registration); |
| 143 | + } |
| 144 | + } |
| 145 | + |
| 146 | + private WatchKey register(Path directory) throws IOException { |
| 147 | + logger.debug(LogMessage.format("Registering '%s'", directory)); |
| 148 | + return directory.register(this.watchService, StandardWatchEventKinds.ENTRY_CREATE, |
| 149 | + StandardWatchEventKinds.ENTRY_MODIFY, StandardWatchEventKinds.ENTRY_DELETE); |
| 150 | + } |
| 151 | + |
| 152 | + @Override |
| 153 | + public void run() { |
| 154 | + logger.debug("Watch thread started"); |
| 155 | + Set<Runnable> actions = new HashSet<>(); |
| 156 | + while (this.running) { |
| 157 | + try { |
| 158 | + long timeout = FileWatcher.this.quietPeriod.toMillis(); |
| 159 | + WatchKey key = this.watchService.poll(timeout, TimeUnit.MILLISECONDS); |
| 160 | + if (key == null) { |
| 161 | + actions.forEach(this::runSafely); |
| 162 | + actions.clear(); |
| 163 | + } |
| 164 | + else { |
| 165 | + accumulate(key, actions); |
| 166 | + key.reset(); |
| 167 | + } |
| 168 | + } |
| 169 | + catch (InterruptedException ex) { |
| 170 | + Thread.currentThread().interrupt(); |
| 171 | + } |
| 172 | + catch (ClosedWatchServiceException ex) { |
| 173 | + logger.debug("File watcher has been closed"); |
| 174 | + this.running = false; |
| 175 | + } |
| 176 | + } |
| 177 | + logger.debug("Watch thread stopped"); |
| 178 | + } |
| 179 | + |
| 180 | + private void runSafely(Runnable action) { |
| 181 | + try { |
| 182 | + action.run(); |
| 183 | + } |
| 184 | + catch (Throwable ex) { |
| 185 | + logger.error("Unexpected SSL reload error", ex); |
| 186 | + } |
| 187 | + } |
| 188 | + |
| 189 | + private void accumulate(WatchKey key, Set<Runnable> actions) { |
| 190 | + List<Registration> registrations = this.registrations.get(key); |
| 191 | + Path directory = (Path) key.watchable(); |
| 192 | + for (WatchEvent<?> event : key.pollEvents()) { |
| 193 | + Path file = directory.resolve((Path) event.context()); |
| 194 | + for (Registration registration : registrations) { |
| 195 | + if (registration.manages(file)) { |
| 196 | + actions.add(registration.action()); |
| 197 | + } |
| 198 | + } |
| 199 | + } |
| 200 | + } |
| 201 | + |
| 202 | + @Override |
| 203 | + public void close() throws IOException { |
| 204 | + this.running = false; |
| 205 | + this.watchService.close(); |
| 206 | + } |
| 207 | + |
| 208 | + } |
| 209 | + |
| 210 | + /** |
| 211 | + * An individual watch registration. |
| 212 | + */ |
| 213 | + private record Registration(Set<Path> paths, Runnable action) { |
| 214 | + |
| 215 | + Registration { |
| 216 | + paths = paths.stream().map(Path::toAbsolutePath).collect(Collectors.toSet()); |
| 217 | + } |
| 218 | + |
| 219 | + boolean manages(Path file) { |
| 220 | + Path absolutePath = file.toAbsolutePath(); |
| 221 | + return this.paths.contains(absolutePath) || isInDirectories(absolutePath); |
| 222 | + } |
| 223 | + |
| 224 | + private boolean isInDirectories(Path file) { |
| 225 | + return this.paths.stream().filter(Files::isDirectory).anyMatch(file::startsWith); |
| 226 | + } |
| 227 | + } |
| 228 | + |
| 229 | +} |
0 commit comments