Class: Contur::Controller

Inherits:
Object
  • Object
show all
Defined in:
lib/contur/controller.rb

Overview

Contur::Controller

Class Method Summary collapse

Class Method Details

.buildObject



50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
# File 'lib/contur/controller.rb', line 50

def self.build
  template = load_docker_template(
    'base-docker-container',
    php_memory_limit: '128M'
  )

  docker_context = generate_docker_archive(template)

  Docker::Image.build_from_tar(docker_context, t: Contur::IMAGE_NAME) do |r|
    r.each_line do |log|
      if (message = JSON.parse(log)) && message.key?('stream')
        yield message['stream'] if block_given?
      end
    end
  end
end

.compress_archive(tar) ⇒ Object



221
222
223
224
225
226
227
228
229
230
231
# File 'lib/contur/controller.rb', line 221

def self.compress_archive(tar)
  tar.seek(0)
  gz = StringIO.new(String.new, 'r+b').set_encoding(Encoding::BINARY)
  gz_writer = Zlib::GzipWriter.new(gz)
  gz_writer.write(tar.read)
  tar.close
  gz_writer.finish
  gz.rewind

  gz
end

.config(path_to_config = nil) ⇒ Object

rubocop:disable Metrics/AbcSize, Metrics/CyclomaticComplexity



18
19
20
21
22
23
24
25
26
27
28
29
30
31
# File 'lib/contur/controller.rb', line 18

def self.config(path_to_config = nil)
  # rubocop:disable Style/ClassVars
  @@config ||= nil

  unless @@config
    @@config = if path_to_config.nil?
                 config_file_name = Dir['.contur.y*ml'].first
                 Contur::Config.new(File.join(Dir.pwd, config_file_name))
               else
                 Contur::Config.new(path_to_config)
               end
  end
  @@config
end

.container?Boolean

Returns:

  • (Boolean)


37
38
39
40
41
42
43
# File 'lib/contur/controller.rb', line 37

def self.container?
  Docker::Container.all(
    'filters' => { 'ancestor' => [Contur::IMAGE_NAME] }.to_json, 'all' => true
  ).first
rescue
  nil
end

.container_idObject



156
157
158
159
# File 'lib/contur/controller.rb', line 156

def self.container_id
  return nil unless c = container?
  c.id[0, 10]
end

.container_logsObject



161
162
163
164
# File 'lib/contur/controller.rb', line 161

def self.container_logs
  return nil unless c = container?
  c.logs(stdout: true)
end

.default_yamlObject



189
190
191
# File 'lib/contur/controller.rb', line 189

def self.default_yaml
  Contur::DEFAULT_YAML.to_yaml
end

.delete_containerObject



147
148
149
150
151
152
153
154
# File 'lib/contur/controller.rb', line 147

def self.delete_container
  if c = container?
    c.delete(force: true)
    true
  else
    false
  end
end

.delete_imageObject



166
167
168
169
170
# File 'lib/contur/controller.rb', line 166

def self.delete_image
  return nil unless image_exist?
  image = Docker::Image.get Contur::IMAGE_NAME
  image.remove(force: true)
end

.delete_mysql_containersObject



176
177
178
179
180
181
182
183
# File 'lib/contur/controller.rb', line 176

def self.delete_mysql_containers
  if mysql_containers.empty?
    false
  else
    mysql_containers.each { |c| c.delete(force: true) }
    true
  end
end

.generate_docker_archive(dockerfile_content) ⇒ Object



211
212
213
214
215
216
217
218
219
# File 'lib/contur/controller.rb', line 211

def self.generate_docker_archive(dockerfile_content)
  tar = StringIO.new

  Gem::Package::TarWriter.new(tar) do |writer|
    writer.add_file('Dockerfile', 0o644) { |f| f.write(dockerfile_content) }
  end

  compress_archive(tar)
end

.image_exist?Boolean

Returns:

  • (Boolean)


33
34
35
# File 'lib/contur/controller.rb', line 33

def self.image_exist?
  Docker::Image.exist? Contur::IMAGE_NAME
end

.load_docker_template(template_name, opts = {}) ⇒ Object



195
196
197
198
199
200
201
202
# File 'lib/contur/controller.rb', line 195

def self.load_docker_template(template_name, opts = {})
  opts = Contur::DEFAULT_OPTS.merge(opts)

  context = BindableHash.new opts
  ::ERB.new(
    File.read("#{Contur::TEMPLATE_DIR}/#{template_name}.erb")
  ).result(context.get_binding)
end

.load_init_scriptObject



204
205
206
207
208
209
# File 'lib/contur/controller.rb', line 204

def self.load_init_script
  context = BindableHash.new(before_script: config.init_script)
  ::ERB.new(
    File.read("#{Contur::TEMPLATE_DIR}/init.sh.erb")
  ).result(context.get_binding)
end

.mysql_containersObject



172
173
174
# File 'lib/contur/controller.rb', line 172

def self.mysql_containers
  Docker::Container.all.select { |c| c.info['Image'].start_with?('mysql') }
end

.promoteObject



45
46
47
48
# File 'lib/contur/controller.rb', line 45

def self.promote
  puts '!!! WIP !!!'
  puts "FQDN: #{Contur::Utils.fqdn}"
end

.run(config_path: nil, webroot: nil, initscripts: nil) {|"MySQL container: #{mysql_container.id[0, 10]}"| ... } ⇒ Object

rubocop:disable Metrics/PerceivedComplexity, Lint/UnusedMethodArgument, Metrics/MethodLength

Yields:

  • ("MySQL container: #{mysql_container.id[0, 10]}")


68
69
70
71
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
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
# File 'lib/contur/controller.rb', line 68

def self.run(config_path: nil, webroot: nil, initscripts: nil)
  unless image_exist?
    yield "Image doesn't exist" if block_given?
    return false
  end

  bind_volumes = []

  if !webroot.nil? && Dir.exist?(File.expand_path(webroot))
    bind_volumes << "#{webroot}:/www"
  end
  if !initscripts.nil? && Dir.exist?(File.expand_path(initscripts))
    bind_volumes << "#{initscripts}:/initscripts"
  end

  if c = container?
    yield 'Removing existing contur container...' if block_given?
    c.remove(force: true)
  end

  mysql_container_version = "mysql:#{config.use['mysql']}"
  unless Docker::Image.exist? mysql_container_version
    yield "Downloading #{mysql_container_version}..." if block_given?
    Docker::Image.create('fromImage' => mysql_container_version)
  end

  mysql_container_name = mysql_container_version.tr(':.', '_')

  stop_mysql_containers(except: mysql_container_version)
  begin
    mysql_container = Docker::Container.get(mysql_container_name)
  rescue Docker::Error::NotFoundError
    yield 'Creating MySQL container...' if block_given?
    mysql_container = Docker::Container.create(
      'name' => mysql_container_name,
      'Image' => mysql_container_version,
      'Env' => ['MYSQL_ROOT_PASSWORD=admin']
    )
  ensure
    mysql_container_info = Docker::Container.get(mysql_container.id).info
    unless mysql_container_info['State']['Running']
      yield 'Starting MySQL container...' if block_given?
      mysql_container.start!
      sleep 10
    end
  end
  mysql_container_info = Docker::Container.get(mysql_container.id).info
  unless mysql_container_info['State']['Running']
    yield "Couldn't start MySQL container" if block_given?
    return false
  end
  yield "MySQL container: #{mysql_container.id[0, 10]}" if block_given?

  yield 'Creating Contur container...' if block_given?
  container = Docker::Container.create(
    'name' => Contur::Utils.generate_conatiner_name,
    'Image' => Contur::IMAGE_NAME,
    'Cmd' => ['/init.sh'],
    'Volumes' => {
      "#{Dir.pwd}/webroot" => {},
      "#{Dir.pwd}/initscripts" => {}
    },
    'ExposedPorts' => {
      '80/tcp' => {}
    },
    'HostConfig' => {
      'Links' => ["#{mysql_container_name}:mysql"],
      'PortBindings' => {
        '80/tcp' => [{ 'HostPort' => '8088' }]
      },
      'Binds' => bind_volumes
    }
  )

  container.store_file('/init.sh', content: load_init_script, permissions: 0o777)

  container.start!
end

.stop_mysql_containers(except: "\n") ⇒ Object



185
186
187
# File 'lib/contur/controller.rb', line 185

def self.stop_mysql_containers(except: "\n")
  mysql_containers.select { |c| !c.info['Image'].end_with?(except) }.each(&:stop)
end