diff --git a/lib/ddtrace/configuration/agent_settings_resolver.rb b/lib/ddtrace/configuration/agent_settings_resolver.rb index 88cdef21668..1f5e5ec5d4a 100644 --- a/lib/ddtrace/configuration/agent_settings_resolver.rb +++ b/lib/ddtrace/configuration/agent_settings_resolver.rb @@ -130,35 +130,46 @@ def configured_hostname def configured_port return @configured_port if defined?(@configured_port) - port_from_env = ENV[Datadog::Ext::Transport::HTTP::ENV_DEFAULT_PORT] parsed_port_from_env = - if port_from_env - begin - Integer(port_from_env) - rescue ArgumentError - log_warning( - "Invalid value for #{Datadog::Ext::Transport::HTTP::ENV_DEFAULT_PORT} environment variable " \ - "('#{port_from_env}'). Ignoring this configuration." - ) - end - end + try_parsing_as_integer( + friendly_name: "#{Datadog::Ext::Transport::HTTP::ENV_DEFAULT_PORT} environment variable", + value: ENV[Datadog::Ext::Transport::HTTP::ENV_DEFAULT_PORT], + ) + + parsed_settings_tracer_port = + try_parsing_as_integer( + friendly_name: '"c.tracer.port"', + value: settings.tracer.port, + ) @configured_port = pick_from( DetectedConfiguration.new( friendly_name: '"c.tracer.port"', - value: settings.tracer.port + value: parsed_settings_tracer_port, ), DetectedConfiguration.new( friendly_name: "#{Datadog::Ext::Transport::HTTP::ENV_DEFAULT_URL} environment variable", - value: parsed_url && parsed_url.port + value: parsed_url && parsed_url.port, ), DetectedConfiguration.new( friendly_name: "#{Datadog::Ext::Transport::HTTP::ENV_DEFAULT_PORT} environment variable", - value: parsed_port_from_env + value: parsed_port_from_env, ) ) end + def try_parsing_as_integer(value:, friendly_name:) + return unless value + + begin + Integer(value) + rescue ArgumentError + log_warning("Invalid value for #{friendly_name} (#{value.inspect}). Ignoring this configuration.") + + nil + end + end + def ssl? !parsed_url.nil? && parsed_url.scheme == 'https' end diff --git a/spec/ddtrace/configuration/agent_settings_resolver_spec.rb b/spec/ddtrace/configuration/agent_settings_resolver_spec.rb index 81538268f66..b233334a9c3 100644 --- a/spec/ddtrace/configuration/agent_settings_resolver_spec.rb +++ b/spec/ddtrace/configuration/agent_settings_resolver_spec.rb @@ -199,6 +199,34 @@ resolver end end + + context 'when the port is specified as a string instead of a number' do + before do + ddtrace_settings.tracer.port = '1234' + end + + it 'contacts the agent using the http adapter, using the custom port' do + expect(resolver).to have_attributes(**settings, port: 1234) + end + end + + context 'when the port is an invalid value' do + before do + ddtrace_settings.tracer.port = 'kaboom' + + allow(logger).to receive(:warn) + end + + it 'logs a warning' do + expect(logger).to receive(:warn).with(/Invalid value/) + + resolver + end + + it 'falls back to the defaults' do + expect(resolver).to have_attributes settings + end + end end context 'when a custom port is specified via code using "tracer(port: ...)"' do