Method: TestLab::Container::IO#sc_download

Defined in:
lib/testlab/container/io.rb

#sc_download(local_file, url, count) ⇒ Boolean

Downloads a given shipping container image

Returns:

  • (Boolean)

    True if successful.



213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
# File 'lib/testlab/container/io.rb', line 213

def sc_download(local_file, url, count)
  (count <= 0) and raise ContainerError, "Too many redirects, aborting!"

  uri        = URI(url)
  http       = Net::HTTP.new(uri.host, uri.port)

  if (uri.scheme.downcase == 'https')
    http.use_ssl = true
    http.verify_mode = OpenSSL::SSL::VERIFY_NONE  # lets be really permissive for now
  end

  http.request_get(uri.path) do |response|
    case response
    when Net::HTTPNotFound then
      raise ContainerError, "The supplied sc_url for this container was 404 Not Found!"

    when Net::HTTPClientError then
      raise ContainerError, "Client Error: #{response.inspect}"

    when Net::HTTPRedirection then
      location = response['location']
      @ui.stdout.puts(format_message("REDIRECT: #{url} --> #{location}".white))
      return sc_download(local_file, location, (count - 1))

    when Net::HTTPOK then
      tempfile = Tempfile.new(%(download-#{self.id}))
      tempfile.binmode

      current_size = 0
      total_size   = response['content-length'].to_i
      start_time   = Time.now

      response.read_body do |chunk|
        tempfile << chunk

        elapsed  = (Time.now - start_time)
        current_size += chunk.size

        transfer_message(%(downloading locally:), local_file, current_size, total_size, elapsed)
      end
      @ui.stdout.puts

      tempfile.close

      FileUtils.mkdir_p(File.dirname(local_file))
      File.exists?(local_file) and File.unlink(local_file)
      FileUtils.mv(tempfile.path, local_file, :force => true)

      true
    else
      raise ContainerError, "Unknown HTTP response when attempt to download your shipping container!"
    end
  end

end