Class: Docker::Utils

Inherits:
Object
  • Object
show all
Defined in:
lib/docker_rack/docker_utils.rb

Class Method Summary collapse

Class Method Details

.containers_by_name(name) ⇒ Object



150
151
152
153
154
155
# File 'lib/docker_rack/docker_utils.rb', line 150

def self.containers_by_name(name)
  containers = `docker ps -a`
  ps = []
  containers.each_line { |line| if line.include?(name) then ps << line.strip.partition(' ').first end }
  ps
end

.create_docker_command(info) ⇒ Object



10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
# File 'lib/docker_rack/docker_utils.rb', line 10

def self.create_docker_command(info)
  docker_cmd = ['docker']
  docker_cmd.push info['action'] || 'run -d'
  docker_cmd.push "--name=\"#{info['name']}\""
  docker_cmd.push "--add-host=\"dockerhost:#{dockerhost}\"" unless info.key? 'net'
  docker_cmd.push "--hostname=\"#{info['hostname']}\"" if info.key? 'hostname'
  docker_cmd.push info['environment'].map { |k, v| "-e #{k.to_s}=\"#{v}\"" } if info.key? 'environment'
  docker_cmd.push info['ports'].map { |port| "-p #{mirror_if_single(port)}" } if info.key? 'ports'
  docker_cmd.push info['expose'].map { |port| "--expose=#{port}" } if info.key? 'expose'
  docker_cmd.push info['links'].map { |link| "--link #{link}" } if info.key? 'links'
  docker_cmd.push info['volumes_from'].map { |volume| "--volumes-from \"#{volume}\"" } if info.key? 'volumes_from'
  docker_cmd.push info['volumes'].map { |volume| "-v #{quote_parts(volume)}" } if info.key? 'volumes'
  docker_cmd.push "--net=\"#{info['net']}\"" if info.key? 'net'
  docker_cmd.push '--privileged' if info['privileged'] == true
  docker_cmd.push "--log-driver=\"#{info['log-driver']}\"" if info.key? 'log-driver'
  docker_cmd.push info['log-opt'].map { |k, v| "--log-opt #{k.to_s}=\"#{v}\"" } if info.key? 'log-opt'
  docker_cmd.push info['image']
  docker_cmd.push info['command'] if info.key? 'command'
  return docker_cmd.join(' ')
end

.dockerhostObject



4
5
6
7
8
# File 'lib/docker_rack/docker_utils.rb', line 4

def self.dockerhost
  @dockerhost = ENV['DOCKER_HOST']
  return nil if @dockerhost.nil?
  @dockerhost[/tcp:\/\/([^:]+)/,1]
end

.get_image_id(name) ⇒ Object



157
158
159
160
161
162
# File 'lib/docker_rack/docker_utils.rb', line 157

def self.get_image_id(name)
  images = `docker images`
  img = []
  images.each_line { |line| if line.include?(name) then img << line.strip.partition(' ').first end }
  img.first
end

.is_http_present?(url) ⇒ Boolean

Returns:

  • (Boolean)


115
116
117
118
119
120
121
122
123
124
125
126
# File 'lib/docker_rack/docker_utils.rb', line 115

def self.is_http_present?(url)
  begin
    uri = URI(url)
    request = Net::HTTP::Get.new(uri.request_uri)
    response = Net::HTTP.start(uri.host, uri.port, :read_timeout => 500) {|http| http.request(request)}

    return response.code == '200'
  rescue Errno::ECONNREFUSED, Errno::EHOSTUNREACH
    # ignored

  end
  return false
end

.is_port_open?(ip, port) ⇒ Boolean

Returns:

  • (Boolean)


128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
# File 'lib/docker_rack/docker_utils.rb', line 128

def self.is_port_open?(ip, port)
  begin
    Timeout::timeout(1) do
      begin
        s = TCPSocket.new(ip, port)
        s.close
        return true
      rescue Errno::ECONNREFUSED, Errno::EHOSTUNREACH
        return false
      end
    end
  rescue Timeout::Error
    # ignored

  end

  return false
end

.mirror_if_single(text) ⇒ Object



35
36
37
38
# File 'lib/docker_rack/docker_utils.rb', line 35

def self.mirror_if_single(text)
  parts = text.to_s.split(':')
  parts.count == 1 ? "#{text}:#{text}" : text
end

.present?(name) ⇒ Boolean

Returns:

  • (Boolean)


146
147
148
# File 'lib/docker_rack/docker_utils.rb', line 146

def self.present?(name)
  ! containers_by_name(name).empty?
end

.put_char(str) ⇒ Object



110
111
112
113
# File 'lib/docker_rack/docker_utils.rb', line 110

def self.put_char(str)
  print str
  $stdout.flush
end

.quote_parts(text) ⇒ Object



31
32
33
# File 'lib/docker_rack/docker_utils.rb', line 31

def self.quote_parts(text)
  text.split(':').map { |s| "\"#{s}\""}.join(':')
end

.start_container(info) ⇒ Object



72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
# File 'lib/docker_rack/docker_utils.rb', line 72

def self.start_container(info)
  command = create_docker_command(info)
  puts command if LOG_LEVEL == 'DEBUG'
  if present?(info['name'])
    puts 'Detected as running. Skipping ....' # if LOG_LEVEL == 'DEBUG'

  else
    `#{command}`
  end
  Array(info['checks']).each do |check|
    try = (check['retry'] || 3).to_i
    interval = (check['interval'] || 2).to_i
    while true
      sleep interval
      put_char '.' if LOG_LEVEL != 'DEBUG'
      case check['type']
        when 'port'
          puts "Checking port #{check['ip']}:#{check['port']} availability." if LOG_LEVEL == 'DEBUG'
          result = is_port_open?(check['ip'], check['port'])
          puts "Result: #{result}" if LOG_LEVEL == 'DEBUG'
          break if result
        when 'rest'
          puts "Checking HTTP response #{check['uri']}." if LOG_LEVEL == 'DEBUG'
          result = is_http_present?(check['uri'])
          puts "Result: #{result}" if LOG_LEVEL == 'DEBUG'
          break if result
        when 'script'
          `#{check['script']}`
          break if $?.to_i == 0
        else
          puts 'Unrecognizable check type. Skipping ...'
      end
      try -= 1
      abort '  Health check failed all retries' if try == 0
    end
    puts
  end
end

.stop_container(container_template) ⇒ Object



40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
# File 'lib/docker_rack/docker_utils.rb', line 40

def self.stop_container(container_template)

  container_template.each do |template_id, _|
    name = template_id
    # containers = `docker ps`

    ps = containers_by_name(name)
    ps.each do |line|
      if line != ''
        cmd = "docker inspect -f {{.State.Running}} #{line}"
        puts cmd if LOG_LEVEL == 'DEBUG'
        is_running = `#{cmd}`.strip
        if is_running == 'true'
          cmd = "docker kill #{line}"
          puts cmd if LOG_LEVEL == 'DEBUG'
          `#{cmd}`
        else
          puts 'Container not running. Nothing to kill. Skipping...'
        end
      end
    end

    ps = containers_by_name(name)
    ps.each do |line|
      if line != ''
        cmd = "docker rm #{line}"
        puts cmd if LOG_LEVEL == 'DEBUG'
        `#{cmd}`
      end
    end
  end
end