PERF: avoid shelling to get hostname aggressively

Previously we had many places in the app that called `hostname` to get
hostname of a server. This commit replaces the pattern in 2 ways

1. We cache the result in `Discourse.os_hostname` so it is only ever called once

2. We prefer to use Socket.gethostname which avoids making a shell command

This improves performance as we are not spawning hostname processes throughout
the app lifetime
This commit is contained in:
Sam Saffron
2020-02-18 15:11:30 +11:00
parent cfd56e9159
commit 28292d2759
9 changed files with 26 additions and 8 deletions

View File

@ -312,6 +312,24 @@ module Discourse
end
end
# hostname of the server, operating system level
# called os_hostname so we do no confuse it with current_hostname
def self.os_hostname
@os_hostname ||=
begin
require 'socket'
Socket.gethostname
rescue => e
warn_exception(e, message: 'Socket.gethostname is not working')
begin
`hostname`.strip
rescue => e
warn_exception(e, message: 'hostname command is not working')
'unknown_host'
end
end
end
# Get the current base URL for the current site
def self.current_hostname
SiteSetting.force_hostname.presence || RailsMultisite::ConnectionManagement.current_hostname