Class: VagrantCloud::Client

Inherits:
Object
  • Object
show all
Includes:
Logger
Defined in:
lib/vagrant_cloud/client.rb

Constant Summary collapse

API_V1_PATH =

Path to the v1 API

"/api/v1".freeze
API_V2_PATH =

Path to the v2 API

"/api/v2".freeze
API_DEFAULT_URL =

Default host URL

"https://vagrantcloud.com".freeze
IDEMPOTENT_METHODS =

Valid methods that can be retried

[:get, :head].freeze
IDEMPOTENT_RETRIES =

Number or allowed retries

3
IDEMPOTENT_RETRY_INTERVAL =

Number of seconds to wait between retries

2
QUERY_PARAMS_METHODS =

Methods which require query parameters

[:get, :head, :delete].freeze
DEFAULT_INSTRUMENTOR =

Default instrumentor

Instrumentor::Collection.new

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Methods included from Logger

default, included, #logger

Constructor Details

#initialize(access_token: nil, url_base: nil, retry_count: nil, retry_interval: nil, instrumentor: nil) ⇒ Client

Create a new Client instance



45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
# File 'lib/vagrant_cloud/client.rb', line 45

def initialize(access_token: nil, url_base: nil, retry_count: nil, retry_interval: nil, instrumentor: nil)
  url_base = API_DEFAULT_URL if url_base.nil?
  remote_url = URI.parse(url_base)
  @url_base = "#{remote_url.scheme}://#{remote_url.host}"
  @path_base = remote_url.path
  if @path_base.empty? || @path_base == API_V1_PATH || @path_base == API_V2_PATH
    @path_base = nil
  end
  @auth = Auth.new(access_token: access_token)
  @retry_count = retry_count.nil? ? IDEMPOTENT_RETRIES : retry_count.to_i
  @retry_interval = retry_interval.nil? ? IDEMPOTENT_RETRY_INTERVAL : retry_interval.to_i
  @instrumentor = instrumentor.nil? ? Instrumentor::Collection.new : instrumentor
  headers = {}.tap do |h|
    h["Accept"] = "application/json"
    h["Content-Type"] = "application/json"
  end
  @connection_lock = Mutex.new
  @connection = Excon.new(url_base,
    headers: headers,
    instrumentor: @instrumentor
  )
end

Instance Attribute Details

#instrumentorInstrumentor::Collection (readonly)



35
36
37
# File 'lib/vagrant_cloud/client.rb', line 35

def instrumentor
  @instrumentor
end

#path_baseString (readonly)



27
28
29
# File 'lib/vagrant_cloud/client.rb', line 27

def path_base
  @path_base
end

#retry_countInteger (readonly)



31
32
33
# File 'lib/vagrant_cloud/client.rb', line 31

def retry_count
  @retry_count
end

#retry_intervalInteger (readonly)



33
34
35
# File 'lib/vagrant_cloud/client.rb', line 33

def retry_interval
  @retry_interval
end

#url_baseString (readonly)



29
30
31
# File 'lib/vagrant_cloud/client.rb', line 29

def url_base
  @url_base
end

Class Method Details

.instrumentorInstrumentor::Collection



22
23
24
# File 'lib/vagrant_cloud/client.rb', line 22

def self.instrumentor
  DEFAULT_INSTRUMENTOR
end

Instance Method Details

#access_tokenString



69
70
71
# File 'lib/vagrant_cloud/client.rb', line 69

def access_token
  @auth.token
end

#authentication_request_2fa_code(username:, password:, delivery_method:) ⇒ Hash

Request a 2FA code is sent



247
248
249
250
251
252
253
254
255
256
257
258
259
# File 'lib/vagrant_cloud/client.rb', line 247

def authentication_request_2fa_code(username:, password:, delivery_method:)
  params = {
    two_factor: {
      delivery_method: delivery_method
    },
    user: {
      login: username,
      password: password
    }
  }

  request(method: :post, path: "two-factor/request-code", params: params, api_version: 1)
end

#authentication_token_create(username:, password:, description: Data::Nil, code: Data::Nil) ⇒ Hash

Create a new access token



217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
# File 'lib/vagrant_cloud/client.rb', line 217

def authentication_token_create(username:, password:, description: Data::Nil, code: Data::Nil)
  params = {
    user: {
      login: username,
      password: password
    },
    token: {
      description: description
    },
    two_factor: {
      code: code
    }
  }
  request(method: :post, path: "authenticate", params: params, api_version: 1)
end

#authentication_token_deleteHash

Delete the token currently in use



236
237
238
# File 'lib/vagrant_cloud/client.rb', line 236

def authentication_token_delete
  request(method: :delete, path: "authenticate", api_version: 1)
end

#authentication_token_validateHash

Validate the current token



264
265
266
# File 'lib/vagrant_cloud/client.rb', line 264

def authentication_token_validate
  request(method: :get, path: "authenticate")
end

#box_create(username:, name:, short_description: Data::Nil, description: Data::Nil, is_private: Data::Nil) ⇒ Hash

Create a new box



293
294
295
296
297
298
299
300
301
302
303
# File 'lib/vagrant_cloud/client.rb', line 293

def box_create(username:, name:, short_description: Data::Nil, description: Data::Nil, is_private: Data::Nil)
  request(method: :post, path: '/boxes', params: {
    box: {
      username: username,
      name: name,
      short_description: short_description,
      description: description,
      is_private: is_private
    }
  })
end

#box_delete(username:, name:) ⇒ Hash

Delete an existing box



329
330
331
# File 'lib/vagrant_cloud/client.rb', line 329

def box_delete(username:, name:)
  request(method: :delete, path: "/box/#{username}/#{name}")
end

#box_get(username:, name:) ⇒ Hash

Get an existing box



281
282
283
# File 'lib/vagrant_cloud/client.rb', line 281

def box_get(username:, name:)
  request(method: :get, path: "/box/#{username}/#{name}")
end

#box_update(username:, name:, short_description: Data::Nil, description: Data::Nil, is_private: Data::Nil) ⇒ Hash

Update an existing box



313
314
315
316
317
318
319
320
321
322
# File 'lib/vagrant_cloud/client.rb', line 313

def box_update(username:, name:, short_description: Data::Nil, description: Data::Nil, is_private: Data::Nil)
  params = {
    box: {
      short_description: short_description,
      description: description,
      is_private: is_private
    }
  }
  request(method: :put, path: "/box/#{username}/#{name}", params: params)
end

#box_version_create(username:, name:, version:, description: Data::Nil) ⇒ Hash

Create a new box version



350
351
352
353
354
355
356
357
# File 'lib/vagrant_cloud/client.rb', line 350

def box_version_create(username:, name:, version:, description: Data::Nil)
  request(method: :post, path: "/box/#{username}/#{name}/versions", params: {
    version: {
      version: version,
      description: description
    }
  })
end

#box_version_delete(username:, name:, version:) ⇒ Hash

Delete an existing box version



382
383
384
# File 'lib/vagrant_cloud/client.rb', line 382

def box_version_delete(username:, name:, version:)
  request(method: :delete, path: "/box/#{username}/#{name}/version/#{version}")
end

#box_version_get(username:, name:, version:) ⇒ Hash

Get an existing box version



339
340
341
# File 'lib/vagrant_cloud/client.rb', line 339

def box_version_get(username:, name:, version:)
  request(method: :get, path: "/box/#{username}/#{name}/version/#{version}")
end

#box_version_provider_create(username:, name:, version:, provider:, architecture: nil, default_architecture: Data::Nil, url: Data::Nil, checksum: Data::Nil, checksum_type: Data::Nil) ⇒ Hash

Create a new box version provider



432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
# File 'lib/vagrant_cloud/client.rb', line 432

def box_version_provider_create(username:, name:, version:, provider:, architecture: nil, default_architecture: Data::Nil, url: Data::Nil, checksum: Data::Nil, checksum_type: Data::Nil)
  provider_params = {
    name: provider,
    url: url,
    checksum: checksum,
    checksum_type: checksum_type
  }
  if architecture.nil?
    api_version = 1
  else
    api_version = 2
    provider_params.merge!(
      architecture: architecture,
      default_architecture: default_architecture
    )
  end

  request(
    method: :post,
    path: "/box/#{username}/#{name}/version/#{version}/providers",
    params: {
      provider: provider_params
    },
    api_version: api_version
  )
end

#box_version_provider_delete(username:, name:, version:, provider:, architecture: nil) ⇒ Hash

Delete an existing box version provider



500
501
502
503
504
505
506
# File 'lib/vagrant_cloud/client.rb', line 500

def box_version_provider_delete(username:, name:, version:, provider:, architecture: nil)
  req_path = ["/box", username, name, "version", version,
    "provider", provider, architecture].compact.join("/")
  api_version = architecture.nil? ? 1 : 2

  request(method: :delete, path: req_path, api_version: api_version)
end

#box_version_provider_get(username:, name:, version:, provider:, architecture: nil) ⇒ Hash

Get an existing box version provider



414
415
416
417
418
419
420
# File 'lib/vagrant_cloud/client.rb', line 414

def box_version_provider_get(username:, name:, version:, provider:, architecture: nil)
  req_path = ["/box", username, name, "version", version,
    "provider", provider, architecture].compact.join("/")
  api_version = architecture.nil? ? 1 : 2

  request(method: :get, path: req_path, api_version: api_version)
end

#box_version_provider_update(username:, name:, version:, provider:, architecture: nil, new_architecture: Data::Nil, default_architecture: Data::Nil, url: Data::Nil, checksum: Data::Nil, checksum_type: Data::Nil) ⇒ Hash

Update an existing box version provider



469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
# File 'lib/vagrant_cloud/client.rb', line 469

def box_version_provider_update(username:, name:, version:, provider:, architecture: nil, new_architecture: Data::Nil, default_architecture: Data::Nil, url: Data::Nil, checksum: Data::Nil, checksum_type: Data::Nil)
  provider_params = {
    name: provider,
    url: url,
    checksum: checksum,
    checksum_type: checksum_type
  }
  if architecture.nil?
    api_version = 1
  else
    api_version = 2
    provider_params.merge!(
      architecture: new_architecture,
      default_architecture: default_architecture
    )
  end

  req_path = ["/box", username, name, "version", version,
    "provider", provider, architecture].compact.join("/")

  request(method: :put, path: req_path, params: {provider: provider_params}, api_version: api_version)
end

#box_version_provider_upload(username:, name:, version:, provider:, architecture: nil) ⇒ Hash

Upload a box asset for an existing box version provider



516
517
518
519
520
521
522
# File 'lib/vagrant_cloud/client.rb', line 516

def box_version_provider_upload(username:, name:, version:, provider:, architecture: nil)
  req_path = ["/box", username, name, "version", version,
    "provider", provider, architecture, "upload"].compact.join("/")
  api_version = architecture.nil? ? 1 : 2

  request(method: :get, path: req_path, api_version: api_version)
end

#box_version_provider_upload_direct(username:, name:, version:, provider:, architecture: nil) ⇒ Hash

Upload a box asset directly to the backend storage for an existing box version provider



532
533
534
535
536
537
538
# File 'lib/vagrant_cloud/client.rb', line 532

def box_version_provider_upload_direct(username:, name:, version:, provider:, architecture: nil)
  req_path = ["/box", username, name, "version", version,
    "provider", provider, architecture, "upload/direct"].compact.join("/")
  api_version = architecture.nil? ? 1 : 2

  request(method: :get, path: req_path, api_version: api_version)
end

#box_version_release(username:, name:, version:) ⇒ Hash

Release an existing box version



392
393
394
# File 'lib/vagrant_cloud/client.rb', line 392

def box_version_release(username:, name:, version:)
  request(method: :put, path: "/box/#{username}/#{name}/version/#{version}/release")
end

#box_version_revoke(username:, name:, version:) ⇒ Hash

Revoke an existing box version



402
403
404
# File 'lib/vagrant_cloud/client.rb', line 402

def box_version_revoke(username:, name:, version:)
  request(method: :put, path: "/box/#{username}/#{name}/version/#{version}/revoke")
end

#box_version_update(username:, name:, version:, description: Data::Nil) ⇒ Hash

Update an existing box version



366
367
368
369
370
371
372
373
374
# File 'lib/vagrant_cloud/client.rb', line 366

def box_version_update(username:, name:, version:, description: Data::Nil)
  params = {
    version: {
      version: version,
      description: description
    }
  }
  request(method: :put, path: "/box/#{username}/#{name}/version/#{version}", params: params)
end

#clone(access_token: nil) ⇒ Client

Clone this client to create a new instance



181
182
183
184
185
# File 'lib/vagrant_cloud/client.rb', line 181

def clone(access_token: nil)
  self.class.new(access_token: access_token, url_base: url_base,
    retry_count: retry_count, retry_interval: retry_interval
  )
end

#organization_get(name:) ⇒ Hash

Get an organization



272
273
274
# File 'lib/vagrant_cloud/client.rb', line 272

def organization_get(name:)
  request(method: :get, path: "user/#{name}")
end

#request(path:, method: :get, params: {}, api_version: 2) ⇒ Hash

Send a request



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
165
166
167
168
169
170
171
172
173
174
175
# File 'lib/vagrant_cloud/client.rb', line 111

def request(path:, method: :get, params: {}, api_version: 2)
  # Apply any path modifications that are required
  catch(:done) do
    # If a base path is defined, and the provided path
    # is already properly prefixed with it, do nothing.
    throw :done if !path_base.nil? && path.start_with?(path_base)

    # If the path does not include an API version
    # prefix, add it now.
    if !path.start_with?(API_V1_PATH) && !path.start_with?(API_V2_PATH)
      case api_version
      when 1
        start_path = API_V1_PATH
      when 2
        start_path = API_V2_PATH
      else
        raise ArgumentError, "Unsupported API version provided"
      end
    end

    path = [path_base, start_path, path].compact.join("/").gsub(/\/{2,}/, "/")
  end

  method = method.to_s.downcase.to_sym

  # Build base request parameters
  request_params = {
    method: method,
    path: path,
    expects: [200, 201, 204]
  }

  # If this is an idempotent request allow it to retry on failure
  if IDEMPOTENT_METHODS.include?(method)
    request_params[:idempotent] = true
    request_params[:retry_limit] = retry_count
    request_params[:retry_interval] = retry_interval
  end

  # If parameters are provided, set them in the expected location
  if !params.empty?
    # Copy the parameters so we can freely modify them
    params = clean_parameters(params)

    if QUERY_PARAMS_METHODS.include?(method)
      request_params[:query] = params
    else
      request_params[:body] = JSON.dump(params)
    end
  end

  # Set a request ID so we can track request/responses
  request_params[:headers] = {"X-Request-Id" => SecureRandom.uuid}

  begin
    result = with_connection { |c| c.request(request_params) }
  rescue Excon::Error::HTTPStatus => err
    raise Error::ClientError::RequestError.new(
          "Vagrant Cloud request failed", err.response.body, err.response.status)
  rescue Excon::Error => err
    raise Error::ClientError, err.message
  end

  parse_json(result.body)
end

#search(query: Data::Nil, architecture: Data::Nil, provider: Data::Nil, sort: Data::Nil, order: Data::Nil, limit: Data::Nil, page: Data::Nil) ⇒ Hash

Submit a search on Vagrant Cloud



197
198
199
200
201
202
203
204
205
206
207
208
# File 'lib/vagrant_cloud/client.rb', line 197

def search(query: Data::Nil, architecture: Data::Nil, provider: Data::Nil, sort: Data::Nil, order: Data::Nil, limit: Data::Nil, page: Data::Nil)
  params = {
    q: query,
    architecture: architecture,
    provider: provider,
    sort: sort,
    order: order,
    limit: limit,
    page: page
  }
  request(method: :get, path: "search", params: params)
end

#with_connection(wait: true) {|| ... } ⇒ Object

Use the remote connection

Yield Parameters:

  • (Excon::Connection)

Raises:

  • (ArgumentError)


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
# File 'lib/vagrant_cloud/client.rb', line 78

def with_connection(wait: true)
  raise ArgumentError,
    "Block expected but no block given" if !block_given?

  # Adds authentication header to connection if available
  set_authentication = ->(conn) {
    if @auth.available?
      conn.connection[:headers]["Authorization"] = "Bearer #{@auth.token}"
    end
  }

  if !wait
    raise Error::ClientError::ConnectionLockedError,
      "Connection is currently locked" if !@connection_lock.try_lock
    set_authentication.call(@connection)
    begin
      yield @connection
    ensure
      @connection_lock.unlock
    end
  else
    @connection_lock.synchronize do
      set_authentication.call(@connection)
      yield @connection
    end
  end
end