Class: Vagrant::Action::Builtin::BoxAdd

Inherits:
Object
  • Object
show all
Defined in:
lib/vagrant/action/builtin/box_add.rb

Overview

This middleware will download a remote box and add it to the given box collection.

Constant Summary collapse

METADATA_SIZE_LIMIT =

This is the size in bytes that if a file exceeds, is considered to NOT be metadata.

20971520
RESUME_DELAY =

This is the amount of time to "resume" downloads if a partial box file already exists.

24 * 60 * 60

Instance Method Summary collapse

Constructor Details

#initialize(app, env) ⇒ BoxAdd

Returns a new instance of BoxAdd.



29
30
31
32
33
# File 'lib/vagrant/action/builtin/box_add.rb', line 29

def initialize(app, env)
  @app    = app
  @logger = Log4r::Logger.new("vagrant::action::builtin::box_add")
  @parser = URI::RFC2396_Parser.new
end

Instance Method Details

#add_direct(urls, env) ⇒ Object

Adds a box file directly (no metadata component, versioning, etc.)

Parameters:

  • urls (Array<String>)
  • env (Hash)


171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
# File 'lib/vagrant/action/builtin/box_add.rb', line 171

def add_direct(urls, env)
  env[:ui].output(I18n.t("vagrant.box_adding_direct"))

  name = env[:box_name]
  if !name || name == ""
    raise Errors::BoxAddNameRequired
  end

  if env[:box_version]
    raise Errors::BoxAddDirectVersion
  end

  provider = env[:box_provider]
  provider = Array(provider) if provider

  box_add(
    urls,
    name,
    "0",
    provider,
    nil,
    env,
    checksum: env[:box_checksum],
    checksum_type: env[:box_checksum_type],
    architecture: env[:architecture]
  )
end

#add_from_metadata(url, env, expanded) ⇒ Object

Adds a box given that the URL is a metadata document.

Parameters:

  • url (String | Array<String>)

    The URL of the metadata for the box to add. If this is an array, then it must be a two-element array where the first element is the original URL and the second element is an authenticated URL.

  • env (Hash)
  • expanded (Bool)

    True if the metadata URL was expanded with a Atlas server URL.



208
209
210
211
212
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
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
# File 'lib/vagrant/action/builtin/box_add.rb', line 208

def (url, env, expanded)
  original_url = env[:box_url]
  architecture = env[:box_architecture]
  display_architecture = architecture == :auto ?
                           Util::Platform.architecture : architecture
  provider = env[:box_provider]
  provider = Array(provider) if provider
  version = env[:box_version]

  authenticated_url = url
  if url.is_a?(Array)
    # We have both a normal URL and "authenticated" URL. Split
    # them up.
    authenticated_url = url[1]
    url               = url[0]
  end

  display_original_url = Util::CredentialScrubber.scrub(Array(original_url).first)
  display_url = Util::CredentialScrubber.scrub(url)

  env[:ui].output(I18n.t(
    "vagrant.box_loading_metadata",
    name: display_original_url))
  if original_url != url
    env[:ui].detail(I18n.t(
      "vagrant.box_expanding_url", url: display_url))
  end

   = nil
  begin
     = download(
      authenticated_url, env, json: true, ui: false)
    return if @download_interrupted

    File.open() do |f|
       = BoxMetadata.new(f, url: authenticated_url)
    end
  rescue Errors::DownloaderError => e
    raise if !expanded
    raise Errors::BoxAddShortNotFound,
      error: e.extra_data[:message],
      name: display_original_url,
      url: display_url
  ensure
    .delete if  && .file?
  end

  if env[:box_name] && .name != env[:box_name]
    raise Errors::BoxAddNameMismatch,
      actual_name: .name,
      requested_name: env[:box_name]
  end

    = .version(
    version || ">= 0",
    provider: provider,
    architecture: architecture,
  )
  if !
    if provider && !.version(">= 0", provider: provider, architecture: architecture)
      raise Errors::BoxAddNoMatchingProvider,
        name: .name,
        requested: [provider,
          display_architecture ? "(#{display_architecture})" : nil
        ].compact.join(" "),
        url: display_url
    else
      raise Errors::BoxAddNoMatchingVersion,
        constraints: version || ">= 0",
        name: .name,
        url: display_url,
        versions: .versions.join(", ")
    end
  end

   = nil
  if provider
    # If a provider was specified, make sure we get that specific
    # version.
    provider.each do |p|
       = .provider(p, architecture)
      break if 
    end
  elsif .providers(architecture).length == 1
    # If we have only one provider in the metadata, just use that
    # provider.
     = .provider(
      .providers.first, architecture)
  else
    providers = .providers(architecture).sort

    choice = 0
    options = providers.map do |p|
      choice += 1
      "#{choice}) #{p}"
    end.join("\n")

    # We have more than one provider, ask the user what they want
    choice = env[:ui].ask(I18n.t(
      "vagrant.box_add_choose_provider",
      options: options) + " ", prefix: false)
    choice = choice.to_i if choice
    while !choice || choice <= 0 || choice > providers.length
      choice = env[:ui].ask(I18n.t(
        "vagrant.box_add_choose_provider_again") + " ",
        prefix: false)
      choice = choice.to_i if choice
    end

     = .provider(
      providers[choice-1], architecture)
  end

  provider_url = .url
  if provider_url != authenticated_url
    # Authenticate the provider URL since we're using auth
    hook_env    = env[:hook].call(:authenticate_box_url, box_urls: [provider_url])
    authed_urls = hook_env[:box_urls]
    if !authed_urls || authed_urls.length != 1
      raise "Bad box authentication hook, did not generate proper results."
    end
    provider_url = authed_urls[0]
  end

  # The architecture name used when adding the box should be
  # the value extracted from the metadata provider
  arch_name = .architecture

  # In the special case where the architecture name is "unknown" and
  # it is listed as the default architecture, unset the architecture
  # name so it is installed without architecture information
  if arch_name == "unknown" && .default_architecture
    arch_name = nil
  end

  box_add(
    [[provider_url, .url]],
    .name,
    .version,
    .name,
    url,
    env,
    checksum: .checksum,
    checksum_type: .checksum_type,
    architecture: arch_name,
  )
end

#call(env) ⇒ Object



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
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
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
# File 'lib/vagrant/action/builtin/box_add.rb', line 35

def call(env)
  @download_interrupted = false

  unless env[:box_name].nil?
    begin
      if URI.parse(env[:box_name]).kind_of?(URI::HTTP)
        env[:ui].warn(I18n.t("vagrant.box_add_url_warn"))
      end
    rescue URI::InvalidURIError
      # do nothing
    end
  end

  url = Array(env[:box_url]).map do |u|
    u = u.gsub("\\", "/")
    if Util::Platform.windows? && u =~ /^[a-z]:/i
      # On Windows, we need to be careful about drive letters
      u = "file:///#{@parser.escape(u)}"
    end

    if u =~ /^[a-z0-9]+:.*$/i && !u.start_with?("file://")
      # This is not a file URL... carry on
      next u
    end

    # Expand the path and try to use that, if possible
    p = File.expand_path(@parser.unescape(u.gsub(/^file:\/\//, "")))
    p = Util::Platform.cygwin_windows_path(p)
    next "file://#{@parser.escape(p.gsub("\\", "/"))}" if File.file?(p)

    u
  end

  # If we received a shorthand URL ("mitchellh/precise64"),
  # then expand it properly.
  expanded = false
  # Mark if only a single url entry was provided
  single_entry = url.size == 1

  url = url.map do |url_entry|
    if url_entry =~ /^[^\/]+\/[^\/]+$/ && !File.file?(url_entry)
      server = Vagrant.server_url env[:box_server_url]
      raise Errors::BoxServerNotSet if !server

      expanded = true
      # If only a single entry, expand to both the API endpoint and
      # the direct shorthand endpoint.
      if single_entry
        url_entry = [
          "#{server}/api/v2/vagrant/#{url_entry}",
          "#{server}/#{url_entry}"
        ]
      else
        url_entry = "#{server}/#{url_entry}"
      end
    end

    url_entry
  end.flatten

  # Call the hook to transform URLs into authenticated URLs.
  # In the case we don't have a plugin that does this, then it
  # will just return the same URLs.
  hook_env    = env[:hook].call(
    :authenticate_box_url, box_urls: url.dup)
  authed_urls = hook_env[:box_urls]
  if !authed_urls || authed_urls.length != url.length
    raise "Bad box authentication hook, did not generate proper results."
  end

  # Test if any of our URLs point to metadata
   = authed_urls.map do |u|
    begin
      (u, env)
    rescue Errors::DownloaderError => e
      e
    end
  end

  # If only a single entry was provided, and it was expanded,
  # inspect the metadata check results and extract the one that
  # was successful, with preference to the API endpoint
  if single_entry && expanded
    idx = .index { |v| v === true }
    # If none of the urls were successful, set the index
    # as the last entry
    idx = .size - 1 if idx.nil?

    # Now reset collections with single value
     = [[idx]]
    authed_urls = [authed_urls[idx]]
    url = [url[idx]]
  end

  if expanded && url.length == 1
    is_error = .find do |b|
      b.is_a?(Errors::DownloaderError)
    end

    if is_error
      raise Errors::BoxAddShortNotFound,
        error: is_error.extra_data[:message],
        name: env[:box_url],
        url: url
    end
  end

  is_error = .find do |b|
    b.is_a?(Errors::DownloaderError)
  end
  if is_error
    raise Errors::BoxMetadataDownloadError,  
      message: is_error.extra_data[:message]
  end

   = .any? { |b| b === true }
  if  && url.length > 1
    raise Errors::BoxAddMetadataMultiURL,
      urls: url.join(", ")
  end

  if 
    url = [url.first, authed_urls.first]
    (url, env, expanded)
  else
    add_direct(authed_urls, env)
  end

  @app.call(env)
end