Provide deterministic behavior when management.server.port=0
As observed in https://github.com/spring-cloud/spring-cloud-consul/issues/555, when using management.server.port = 0 calls to ManagementServerPortUtils.getPort return 0, rather than the dynamic assigned address.
Not sure of the official solution for this, but can ManagementServerPortUtils be extended to add an ApplicationEvent listener and update the port if / when dynamic ports are being used.
Granted there is a potential for a sort-of-race condition here, where a caller might try and get the port value before the application event has fired, but in my experience, the actuator events usually fire before the main application starts.
I think that we need to align with what spring boot has done. ManagementServerPortUtils was copied from boot a long time ago. I don't think we want to build something that doesn't work all the time. Maybe @philwebb or @wilkinsona could comment on if there's anything in boot we could take advantage of. The reason for wanting the management port is to register it in service discovery.
We still have logic similar to your ManagementServerPortUtils but that's really intended for figuring out the port configuration and whether or not we need to create the child context for a separate management server. I suspect it's overkill for your needs.
For the purposes of registration with service discovery, I think I'd listen for the WebServerInitializedEvents to retrieve the ports from the events' web servers and the ApplicationReadyEvents to perform the registration. The port values can also be injected via @LocalServerPort and @LocalManagementPort or looked up from the environment using local.server.port and local.management.port but this can only be done safely once the WebServerInitializedEvent has been published. I suspect it's easier just to get the port straight from the event in your case.
There's a public class in Boot 2.0+ called ManagementPortType that looks very similar to ManagementServerPortUtils.ManagementServerPort but its job is to tell what type of port is needed, not return the actual port number in use. If you want to get the actual port in use you can use the @LocalManagementPort annotation. There's also @ConditionalOnManagementPort that might be useful for conditional beans.
Looks like we both got there at the same time!
I think @ConditionalOnManagementPort could get us part of the way for making decisions on if it is enabled.
Is there a way to tell if WebServerInitializedEvent is for management?
@spencergibb take a look at ServerPortInfoApplicationContextInitializer for an example. The context name is always management I think. See ManagementContextAutoConfiguration
Looks like this could go in Greenwich (so 2.1.x branch) and merged forward.