Module: Dockerun::CommandHelper::DockerContainerHelper

Includes:
DockerCommandFactoryHelper
Included in:
Dockerun::Command::Run, Dockerun::Command::RunNewContainer, Dockerun::Command::RunNewImage
Defined in:
lib/dockerun/docker_container_helper.rb

Defined Under Namespace

Classes: DockerContainerBuildFailed, DockerContainerStartFailed

Instance Method Summary collapse

Methods included from DockerCommandFactoryHelper

#dcFact

Instance Method Details

#run_docker_container(image_name, container_name, &block) ⇒ Object



12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
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
71
72
73
74
75
76
77
78
79
80
81
82
# File 'lib/dockerun/docker_container_helper.rb', line 12

def run_docker_container(image_name, container_name, &block)
     
  raise DockerContainerBuildFailed, "block is required" if not block
  raise DockerContainerBuildFailed, "Image name is required" if is_empty?(image_name)

  reuse = nil

  if is_empty?(container_name)
    container_name = block.call(:new_container_name)
    loop do
      st, _ = is_container_exist?(container_name)
      if st
        reuse = block.call(:container_name_exist, container_name)
        break if reuse
        container_name = block.call(:new_container_name)
      else
        break
      end
    end

  else
    st, _ = is_container_exist?(container_name)
    if st
      reuse = true
    else
      # if not found shall drop into the next block's else clause 
    end
  end

  if reuse == true
   
    res = dcFact.find_running_container(container_name).run
    if not res.failed? and res.is_out_stream_empty?
      # not running
      ress = dcFact.start_container(container_name).run
      raise DockerContainerStartFailed, "Failed to start container '#{container_name}'. Error was : #{ress.err_stream}" if ress.failed?
    end

    ucmd = cli.ask("Command to be run inside the container. Empty to attach to existing session : ", value: "/bin/bash")
    if is_empty?(ucmd)
      dcFact.attach_container(container_name).run
    else
      dcFact.run_command_in_running_container(container_name, ucmd, tty: true, interactive: true).run
    end

  else

    reqVolMap = block.call(:volume_mapping_required?)
    mount = []
    if reqVolMap

      loop do

        src = block.call(:source_prompt)
        dest = block.call(:destination_prompt, src)
        mount << { src => dest }
        block.call(:add_mount_to_container, container_name, mount.last)
        repeat = block.call(:add_more_volume_mapping?)
        break if not repeat

      end

    end

    dcFact.create_container_from_image(image_name, interactive: true, tty: true, container_name: container_name, mount: mount).run

  end

  container_name

end