Class: CHBuild::Controller

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

Overview

CHBuild::Controller

Class Method Summary collapse

Class Method Details

.buildObject



47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
# File 'lib/chbuild/controller.rb', line 47

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: CHBuild::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



217
218
219
220
221
222
223
224
225
226
227
228
# File 'lib/chbuild/controller.rb', line 217

def self.compress_archive(tar)
  tar.seek(0)
  # rubocop:disable Style/EmptyLiteral
  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



16
17
18
19
20
21
22
23
24
25
26
27
28
# File 'lib/chbuild/controller.rb', line 16

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

  unless @@config
    @@config = if path_to_config.nil?
                 CHBuild::Config.new(File.join(Dir.pwd, '.chbuild.yml'))
               else
                 CHBuild::Config.new(path_to_config)
               end
  end
  @@config
end

.container?Boolean

Returns:

  • (Boolean)


34
35
36
37
38
39
40
# File 'lib/chbuild/controller.rb', line 34

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

.container_idObject



153
154
155
156
157
# File 'lib/chbuild/controller.rb', line 153

def self.container_id
  if c = container?
    c.id[0, 10]
  end
end

.container_logsObject



159
160
161
162
163
# File 'lib/chbuild/controller.rb', line 159

def self.container_logs
  if c = container?
    c.logs(stdout: true)
  end
end

.delete_containerObject



144
145
146
147
148
149
150
151
# File 'lib/chbuild/controller.rb', line 144

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

.delete_imageObject



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

def self.delete_image
  if image_exist?
    image = Docker::Image.get CHBuild::IMAGE_NAME
    image.remove(force: true)
  end
end

.delete_mysql_containersObject



176
177
178
179
180
181
182
183
# File 'lib/chbuild/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



207
208
209
210
211
212
213
214
215
# File 'lib/chbuild/controller.rb', line 207

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

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

  compress_archive(tar)
end

.image_exist?Boolean

Returns:

  • (Boolean)


30
31
32
# File 'lib/chbuild/controller.rb', line 30

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

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



191
192
193
194
195
196
197
198
# File 'lib/chbuild/controller.rb', line 191

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

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

.load_init_scriptObject



200
201
202
203
204
205
# File 'lib/chbuild/controller.rb', line 200

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

.mysql_containersObject



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

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

.promoteObject



42
43
44
45
# File 'lib/chbuild/controller.rb', line 42

def self.promote
  puts '!!! WIP !!!'
  puts "FQDN: #{CHBuild::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]}")


65
66
67
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
# File 'lib/chbuild/controller.rb', line 65

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 chbuild 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 CHBuild container...' if block_given?
  container = Docker::Container.create(
    'name' => CHBuild::Utils.generate_conatiner_name,
    'Image' => CHBuild::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: 0777)

  container.start!
end

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



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

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