1
+ package ucles .weblab .common .config ;
2
+
3
+ import org .slf4j .Logger ;
4
+ import org .slf4j .LoggerFactory ;
5
+ import org .springframework .boot .actuate .health .AbstractHealthIndicator ;
6
+ import org .springframework .boot .actuate .health .Health ;
7
+ import org .springframework .boot .actuate .health .Health .Builder ;
8
+ import org .springframework .core .env .Environment ;
9
+
10
+ import java .util .List ;
11
+
12
+ import static java .util .stream .Collectors .toList ;
13
+ import static org .springframework .boot .actuate .health .Status .UP ;
14
+
15
+ /**
16
+ * Fail health check if configuration is missing.
17
+ * If the configuration is missing at startup, then an exception will be thrown to prevent startup. If after
18
+ * startup a configuration variable is removed dynamically (e.g. when using Spring Cloud), then the heath check
19
+ * will change from UP to DOWN.
20
+ * To see details, the property management.endpoint.health.show-details must be set to 'when_authorized' or 'always'
21
+ * */
22
+ public class ConfigurationHealthCheck extends AbstractHealthIndicator {
23
+
24
+ private final Logger log = LoggerFactory .getLogger (getClass ());
25
+
26
+ private final Environment environment ;
27
+
28
+ /** e.g. ["spring.datasource.hikari.maximum-pool-size", "suppress.errors"] */
29
+ private final List <String > requiredProperties ;
30
+
31
+
32
+ public ConfigurationHealthCheck (Environment environment , List <String > requiredProperties ) {
33
+ this .environment = environment ;
34
+ this .requiredProperties = requiredProperties ;
35
+
36
+ Builder bldr = new Builder ();
37
+ doHealthCheck (bldr );
38
+ Health health = bldr .build ();
39
+
40
+ if (health .getStatus () != UP ) {
41
+ throw new RuntimeException ("System failed configuration healthcheck: " + health .toString ());
42
+ }
43
+ }
44
+
45
+
46
+ @ Override
47
+ protected void doHealthCheck (Builder bldr ) {
48
+
49
+ List <String > missing = requiredProperties .stream ()
50
+ .filter (key -> !environment .containsProperty (key ))
51
+ .collect (toList ());
52
+
53
+ if (missing .isEmpty ()) {
54
+ bldr .up ();
55
+ } else {
56
+ log .error ("Environment health check failed. The following properties are not configured: {}" , missing );
57
+ bldr
58
+ .withDetail ("missing-properties" , missing )
59
+ .down ();
60
+ }
61
+ }
62
+ }
0 commit comments