Class: Construi::Container

Inherits:
Object
  • Object
show all
Defined in:
lib/construi/container.rb

Defined Under Namespace

Classes: Error

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(container) ⇒ Container

Returns a new instance of Container.



8
9
10
# File 'lib/construi/container.rb', line 8

def initialize(container)
  @container = container
end

Class Method Details

.create(image, cmd, options = {}) ⇒ Object



48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
# File 'lib/construi/container.rb', line 48

def self.create(image, cmd, options = {})
  env = options[:env] || []
  privileged = options[:privileged] || false

  host_config = {
    'Binds' => ["#{Dir.pwd}:/var/workspace"],
    'Privileged' => privileged
  }

  wrap Docker::Container.create(
    'Cmd' => cmd.split,
    'Image' => image.id,
    'Env' => env,
    'Tty' => false,
    'WorkingDir' => '/var/workspace',
    'HostConfig' => host_config)
end

.run(image, cmd, options = {}) ⇒ Object



77
78
79
# File 'lib/construi/container.rb', line 77

def self.run(image, cmd, options = {})
  use image, cmd, options, &:run
end

.use(image, cmd, options = {}) ⇒ Object



70
71
72
73
74
75
# File 'lib/construi/container.rb', line 70

def self.use(image, cmd, options = {})
  container = create image, cmd, options
  yield container
ensure
  container.delete unless container.nil?
end

.wrap(container) ⇒ Object



66
67
68
# File 'lib/construi/container.rb', line 66

def self.wrap(container)
  new container
end

Instance Method Details

#==(other) ⇒ Object



44
45
46
# File 'lib/construi/container.rb', line 44

def ==(other)
  other.is_a? Container and id == other.id
end

#attach_stdoutObject



20
21
22
23
24
25
26
# File 'lib/construi/container.rb', line 20

def attach_stdout
  @container.attach(:stream => true, :logs => true) { |s, c| puts c; $stdout.flush }
  true
rescue Docker::Error::TimeoutError
  puts 'Failed to attach to stdout'.yellow
  false
end

#commitObject



28
29
30
# File 'lib/construi/container.rb', line 28

def commit
  Image.wrap(@container.commit)
end

#deleteObject



16
17
18
# File 'lib/construi/container.rb', line 16

def delete
  @container.delete force: true, v: true
end

#idObject



12
13
14
# File 'lib/construi/container.rb', line 12

def id
  @container.id
end

#runObject

Raises:



32
33
34
35
36
37
38
39
40
41
42
# File 'lib/construi/container.rb', line 32

def run
  @container.start
  attached = attach_stdout
  status_code = @container.wait['StatusCode']

  puts @container.logs(:stdout => true) unless attached

  raise Error, "Cmd returned status code: #{status_code}" unless status_code == 0

  commit
end