require 'highline/import' require 'docker' require 'uri' require 'socket' require 'json' module Lux module_function # Determine the IPv4 address of the current Docker host # Used to avoid long reverse DNS lookups on .local names # Returns an array of four items: # - the IPv4 address as a string or '127.0.0.1' if it was a Unix socket # - Used to indicate ENV var, now empty # - a URI object # - a hash containing the Docker version information # Note that DOCKER_URL is used by the docker-api client, but # as Docker uses the misleading DOCKER_HOST we fallback to that. # def dockerip uri = URI.parse(Docker.url) case uri.scheme when 'unix' addr = '127.0.0.1' info = Docker.version when 'tcp' Addrinfo.tcp(uri.host, uri.port).connect(timeout: 5) {|s| addr = s.remote_address.ip_address s.print "GET /version HTTP/1.0\r\nHost: localhost\r\n\r\n" response, emptyline, body = s.read.partition(/(\r\n){2}/) info = JSON.parse(body, symbolize_names: true) } rescue nil else raise "Can't handle #{uri.scheme}" end return addr, '', uri, info end # Get the current list of images and make a guess at which one it is... # def findimage image local_images = `docker images`.strip.split("\n")[1..-1].map{|l| l.gsub!(/^(\S+)\s+(\S+).*/,'\1:\2')}.sort matching_images = local_images.select{|l| l.include? image } if matching_images.size > 0 if image.count(':') == 0 and image.count('/') > 0 matching_image = matching_images.select{|l| l.end_with? ':latest' }.first end unless matching_image if matching_images.size == 1 matching_image = matching_images[0] else matching_image = HighLine.choose do |menu| menu.header = 'List of matching (local) images' menu.choices(*matching_images) menu.choice('None of the above') { nil } end exit 2 unless matching_image end end else matching_image = image end return matching_image end # Return two elements: # - user name (defaults to current user), and # - a bash script setup command # def user_setup_cmd user = `id -nu`.strip [user, <<-COMMAND.gsub(/^\s*/,'').gsub(/\n/,' ; ')] uid=$(echo $(stat -c %u:%g #{ENV['HOME']}) | cut -d: -f2) useradd -M -d #{ENV['HOME']} -u $uid -s #{ENV['SHELL']} #{user} mkdir -p /etc/sudoers.d echo "#{user} ALL=(ALL:ALL) NOPASSWD: ALL" > /etc/sudoers.d/#{user} COMMAND end def die msg, rc = 1 error msg exit rc end def error msg HighLine.new(STDIN, STDERR).say HighLine.color(msg, HighLine::RED) end def info msg HighLine.new(STDIN, STDERR).say HighLine.color(msg, HighLine::YELLOW) end end # vim: ft=ruby sts=2 sw=2 ts=8