Class: VagrantDockerNetworksManager::ActionDestroy

Inherits:
Object
  • Object
show all
Defined in:
lib/vagrant-docker-networks-manager/action.rb

Instance Method Summary collapse

Constructor Details

#initialize(app, _env) ⇒ ActionDestroy

Returns a new instance of ActionDestroy.



113
# File 'lib/vagrant-docker-networks-manager/action.rb', line 113

def initialize(app, _env); @app = app; end

Instance Method Details

#call(env) ⇒ Object



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
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
# File 'lib/vagrant-docker-networks-manager/action.rb', line 115

def call(env)
  UiHelpers.setup_i18n!
  cfg  = env[:machine].config.docker_network
  set_locale!(cfg)

  unless Util.docker_available?
    env[:ui].error("#{UiHelpers.e(:error)} #{I18n.t('errors.docker_unavailable')}")
    return @app.call(env)
  end

  name = cfg.network_name
  mid  = env[:machine].id

  unless cfg.cleanup_on_destroy
    @app.call(env)
    return
  end

  if created_by_this_machine?(env, name) || owned_by_this_machine?(name, mid)
    env[:ui].info("#{UiHelpers.e(:broom)} #{I18n.t('messages.remove_network', name: name)}")

    if Util.docker_network_exists?(name)
      out, _e, st = Open3.capture3("docker", "network", "inspect", name)
      if st.success?
        begin
          info = JSON.parse(out).first
          (info["Containers"] || {}).values.each do |c|
            cn = c["Name"]
            env[:ui].info("#{UiHelpers.e(:ongoing)} #{I18n.t('log.disconnect_container', name: cn)}")
            Util.sh!("network", "disconnect", "--force", name, cn)
            if ENV["VDNM_DESTROY_WITH_CONTAINERS"] == "1"
              env[:ui].info("#{UiHelpers.e(:ongoing)} #{I18n.t('log.remove_container', name: cn)}")
              Util.sh!("rm", "-f", cn)
            end
          end
        rescue => e
          env[:ui].warn("failed to parse containers for '#{name}': #{e.message}")
        end
      end

      if Util.sh!("network", "rm", name)
        delete_marker(env, name)
        env[:ui].info("#{UiHelpers.e(:success)} #{I18n.t('log.ok')}")
      else
        env[:ui].warn("#{UiHelpers.e(:warning)} #{I18n.t('errors.remove_failed')}")
      end
    else
      delete_marker(env, name)
      env[:ui].info("#{UiHelpers.e(:info)} #{I18n.t('messages.nothing_to_do')}")
    end
  else
    env[:ui].info("#{UiHelpers.e(:broom)} #{I18n.t('messages.nothing_to_do')}")
  end

  @app.call(env)
end