diff --git a/src/build/run.cr b/src/build/run.cr index a7cee4f..89ed74e 100644 --- a/src/build/run.cr +++ b/src/build/run.cr @@ -5,6 +5,7 @@ require "socket" require "./module" require "./config" +require "../common/network" module DocMachine::Build class Run @@ -19,7 +20,6 @@ module DocMachine::Build @process = nil end - # cleanup environment # create directories # setup permissions @@ -32,22 +32,6 @@ module DocMachine::Build self._avoid_duplicates() unless @config.enable_multiple end - private def _find_port(port_base) - (port_base..65535).each do |port| - return port if _port_available?(port) - end - raise "No port available" - end - - private def _port_available?(port) - sock = Socket.new(Socket::Family::INET, Socket::Type::STREAM) - sock.bind(Socket::IPAddress.new("0.0.0.0", port)) - sock.close - return true - rescue ex : Socket::BindError - return false - end - private def _avoid_duplicates Log.info { "Multiple Instances: stopping duplicate containers (for #{@docker_name})" } docker_cid = %x{docker ps -f "name=#{@docker_name}" -q}.strip @@ -161,7 +145,7 @@ module DocMachine::Build ## Detect docs if Dir.exists?("#{@config.data_dir}/docs") Log.info { "Docs: detected docs directory." } - mkdocs_port = _find_port(@config.port) + mkdocs_port = Network.find_port(@config.port) docker_opt_mkdocs_port = ["-p", "#{mkdocs_port}:5100"] docker_opts.concat docker_opt_mkdocs_port Log.notice { "Using port #{mkdocs_port} for docs" } @@ -173,7 +157,7 @@ module DocMachine::Build ## Detect slides if Dir.exists?("#{@config.data_dir}/slides") Log.info { "Slides: detected slides directory." } - marp_port = _find_port(@config.port+100) + marp_port = Network.find_port(@config.port+100) docker_opt_marp_port = ["-p", "#{marp_port}:5200"] docker_opts.concat docker_opt_marp_port Log.info { "Slides: Adding option to command line (#{docker_opt_marp_port})" } diff --git a/src/common/network.cr b/src/common/network.cr new file mode 100644 index 0000000..eee02e8 --- /dev/null +++ b/src/common/network.cr @@ -0,0 +1,19 @@ + +class Network + + def self.find_port(port_base) + (port_base..65535).each do |port| + return port if self.port_available?(port) + end + raise "No port available" + end + + def self.port_available?(port) + sock = Socket.new(Socket::Family::INET, Socket::Type::STREAM) + sock.bind(Socket::IPAddress.new("0.0.0.0", port)) + sock.close + return true + rescue ex : Socket::BindError + return false + end +end