Class: Chef::ApiClientV1

Inherits:
Object
  • Object
show all
Includes:
Mixin::ApiVersionRequestHandling, Mixin::FromFile, Mixin::ParamsValidate
Defined in:
lib/chef/api_client_v1.rb

Constant Summary collapse

SUPPORTED_API_VERSIONS =
[0, 1].freeze

Instance Attribute Summary

Attributes included from Mixin::FromFile

#source_file

Class Method Summary collapse

Instance Method Summary collapse

Methods included from Mixin::ApiVersionRequestHandling

#reregister_only_v0_supported_error_msg, #server_client_api_version_intersection

Methods included from Mixin::ParamsValidate

#lazy, #set_or_return, #validate

Methods included from Mixin::FromFile

#class_from_file, #from_file

Constructor Details

#initializeApiClientV1

Create a new Chef::ApiClientV1 object.



50
51
52
53
54
55
56
57
# File 'lib/chef/api_client_v1.rb', line 50

def initialize
  @name = ""
  @public_key = nil
  @private_key = nil
  @admin = false
  @validator = false
  @create_key = nil
end

Class Method Details

.from_hash(o) ⇒ Object



175
176
177
178
179
180
181
182
183
184
# File 'lib/chef/api_client_v1.rb', line 175

def self.from_hash(o)
  client = Chef::ApiClientV1.new
  client.name(o["name"] || o["clientname"])
  client.admin(o["admin"])
  client.validator(o["validator"])
  client.private_key(o["private_key"]) if o.key?("private_key")
  client.public_key(o["public_key"]) if o.key?("public_key")
  client.create_key(o["create_key"]) if o.key?("create_key")
  client
end

.from_json(j) ⇒ Object



186
187
188
# File 'lib/chef/api_client_v1.rb', line 186

def self.from_json(j)
  Chef::ApiClientV1.from_hash(Chef::JSONCompat.from_json(j))
end

.http_apiObject



71
72
73
# File 'lib/chef/api_client_v1.rb', line 71

def self.http_api
  Chef::ServerAPI.new(Chef::Config[:chef_server_url], { api_version: "1", inflate_json_class: false })
end

.list(inflate = false) ⇒ Object



195
196
197
198
199
200
201
202
203
204
205
206
# File 'lib/chef/api_client_v1.rb', line 195

def self.list(inflate = false)
  if inflate
    response = {}
    Chef::Search::Query.new.search(:client) do |n|
      n = from_hash(n) if n.instance_of?(Hash)
      response[n.name] = n
    end
    response
  else
    http_api.get("clients")
  end
end

.load(name) ⇒ Object

Load a client by name via the API

Parameters:

  • name (String)

    the client name



210
211
212
213
# File 'lib/chef/api_client_v1.rb', line 210

def self.load(name)
  response = http_api.get("clients/#{name}")
  Chef::ApiClientV1.from_hash(response)
end

.reregister(name) ⇒ Object



190
191
192
193
# File 'lib/chef/api_client_v1.rb', line 190

def self.reregister(name)
  api_client = Chef::ApiClientV1.load(name)
  api_client.reregister
end

Instance Method Details

#admin(arg = nil) ⇒ True/False

Gets or sets whether this client is an admin.

Parameters:

  • arg (Optional True/False) (defaults to: nil)

    Should be true or false - default is false.

Returns:

  • (True/False)

    The current value



91
92
93
94
95
96
97
# File 'lib/chef/api_client_v1.rb', line 91

def admin(arg = nil)
  set_or_return(
    :admin,
    arg,
    kind_of: [ TrueClass, FalseClass ]
  )
end

#chef_rest_v0Object



59
60
61
# File 'lib/chef/api_client_v1.rb', line 59

def chef_rest_v0
  @chef_rest_v0 ||= Chef::ServerAPI.new(Chef::Config[:chef_server_url], { api_version: "0", inflate_json_class: false })
end

#chef_rest_v1Object



63
64
65
# File 'lib/chef/api_client_v1.rb', line 63

def chef_rest_v1
  @chef_rest_v1 ||= Chef::ServerAPI.new(Chef::Config[:chef_server_url], { api_version: "1", inflate_json_class: false })
end

#chef_rest_v1_with_validatorObject



67
68
69
# File 'lib/chef/api_client_v1.rb', line 67

def chef_rest_v1_with_validator
  @chef_rest_v1_with_validator ||= Chef::ServerAPI.new(Chef::Config[:chef_server_url], { client_name: Chef::Config[:validation_client_name], signing_key_filename: Chef::Config[:validation_key], api_version: "1", inflate_json_class: false })
end

#createObject

Create the client via the REST API



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
# File 'lib/chef/api_client_v1.rb', line 285

def create
  payload = {
    name: name,
    validator: validator,
    # this field is ignored in API V1, but left for backwards-compat,
    # can remove after OSC 11 support is finished?
    admin: admin,
  }
  begin
    # try API V1
    raise Chef::Exceptions::InvalidClientAttribute, "You cannot set both public_key and create_key for create." if !create_key.nil? && !public_key.nil?

    payload[:public_key] = public_key unless public_key.nil?
    payload[:create_key] = create_key unless create_key.nil?

    new_client = if Chef::Config[:migrate_key_to_keystore] == true
                   chef_rest_v1_with_validator.post("clients", payload)
                 else
                   chef_rest_v1.post("clients", payload)
                 end

    # get the private_key out of the chef_key hash if it exists
    if new_client["chef_key"]
      if new_client["chef_key"]["private_key"]
        new_client["private_key"] = new_client["chef_key"]["private_key"]
      end
      new_client["public_key"] = new_client["chef_key"]["public_key"]
      new_client.delete("chef_key")
    end

  rescue Net::HTTPClientException => e
    # rescue API V0 if 406 and the server supports V0
    supported_versions = server_client_api_version_intersection(e, SUPPORTED_API_VERSIONS)
    raise e unless supported_versions && supported_versions.include?(0)

    # under API V0, a key pair will always be created unless public_key is
    # passed on initial POST
    payload[:public_key] = public_key unless public_key.nil?

    new_client = chef_rest_v0.post("clients", payload)
  end
  Chef::ApiClientV1.from_hash(to_h.merge(new_client))
end

#create_key(arg = nil) ⇒ True/False

Used to ask server to generate key pair under api V1

Parameters:

  • arg (Optional True/False) (defaults to: nil)

    Should be true or false - default is false.

Returns:

  • (True/False)

    The current value



141
142
143
144
145
146
147
# File 'lib/chef/api_client_v1.rb', line 141

def create_key(arg = nil)
  set_or_return(
    :create_key,
    arg,
    kind_of: [ TrueClass, FalseClass ]
  )
end

#destroyObject

Remove this client via the REST API



216
217
218
# File 'lib/chef/api_client_v1.rb', line 216

def destroy
  chef_rest_v1.delete("clients/#{@name}")
end

#name(arg = nil) ⇒ String

Gets or sets the client name.

Parameters:

  • arg (Optional String) (defaults to: nil)

    The name must be alpha-numeric plus - and _.

Returns:

  • (String)

    The current value of the name.



79
80
81
82
83
84
85
# File 'lib/chef/api_client_v1.rb', line 79

def name(arg = nil)
  set_or_return(
    :name,
    arg,
    regex: /^[\-[:alnum:]_\.]+$/
  )
end

#private_key(arg = nil) ⇒ String

Private key. The server will return it as a string. Set to true under API V0 to have the server regenerate the default key.

Parameters:

  • arg (Optional String) (defaults to: nil)

    The string representation of the private key.

Returns:

  • (String)

    The current value.



129
130
131
132
133
134
135
# File 'lib/chef/api_client_v1.rb', line 129

def private_key(arg = nil)
  set_or_return(
    :private_key,
    arg,
    kind_of: [String, TrueClass, FalseClass]
  )
end

#public_key(arg = nil) ⇒ String

Gets or sets the public key.

Parameters:

  • arg (Optional String) (defaults to: nil)

    The string representation of the public key.

Returns:

  • (String)

    The current value.



103
104
105
106
107
108
109
# File 'lib/chef/api_client_v1.rb', line 103

def public_key(arg = nil)
  set_or_return(
    :public_key,
    arg,
    kind_of: String
  )
end

#reregisterObject



232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
# File 'lib/chef/api_client_v1.rb', line 232

def reregister
  # Try API V0 and if it fails due to V0 not being supported, raise the proper error message.
  # reregister only supported in API V0 or lesser.
  reregistered_self = chef_rest_v0.put("clients/#{name}", { name: name, admin: admin, validator: validator, private_key: true })
  if reregistered_self.respond_to?(:[])
    private_key(reregistered_self["private_key"])
  else
    private_key(reregistered_self.private_key)
  end
  self
rescue Net::HTTPClientException => e
  # if there was a 406 related to versioning, give error explaining that
  # only API version 0 is supported for reregister command
  if e.response.code == "406" && e.response["x-ops-server-api-version"]
    version_header = Chef::JSONCompat.from_json(e.response["x-ops-server-api-version"])
    min_version = version_header["min_version"]
    max_version = version_header["max_version"]
    error_msg = reregister_only_v0_supported_error_msg(max_version, min_version)
    raise Chef::Exceptions::OnlyApiVersion0SupportedForAction.new(error_msg)
  else
    raise e
  end
end

#saveObject

Save this client via the REST API, returns a hash including the private key



221
222
223
224
225
226
227
228
229
230
# File 'lib/chef/api_client_v1.rb', line 221

def save
  update
rescue Net::HTTPClientException => e
  # If that fails, go ahead and try and update it
  if e.response.code == "404"
    create
  else
    raise e
  end
end

#to_hHash Also known as: to_hash

The hash representation of the object. Includes the name and public_key. Private key is included if available.

Returns:

  • (Hash)


153
154
155
156
157
158
159
160
161
162
163
164
# File 'lib/chef/api_client_v1.rb', line 153

def to_h
  result = {
    "name" => @name,
    "validator" => @validator,
    "admin" => @admin,
    "chef_type" => "client",
  }
  result["private_key"] = @private_key unless @private_key.nil?
  result["public_key"] = @public_key unless @public_key.nil?
  result["create_key"] = @create_key unless @create_key.nil?
  result
end

#to_json(*a) ⇒ String

The JSON representation of the object.

Returns:

  • (String)

    the JSON string.



171
172
173
# File 'lib/chef/api_client_v1.rb', line 171

def to_json(*a)
  Chef::JSONCompat.to_json(to_h, *a)
end

#to_sObject

As a string



330
331
332
# File 'lib/chef/api_client_v1.rb', line 330

def to_s
  "client[#{@name}]"
end

#updateObject

Updates the client via the REST API



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
# File 'lib/chef/api_client_v1.rb', line 257

def update
  # NOTE: API V1 dropped support for updating client keys via update (aka PUT),
  # but this code never supported key updating in the first place. Since
  # it was never implemented, we will simply ignore that functionality
  # as it is being deprecated.
  # Delete this comment after V0 support is dropped.
  payload = { name: name }
  payload[:validator] = validator unless validator.nil?

  # DEPRECATION
  # This field is ignored in API V1, but left for backwards-compat,
  # can remove after API V0 is no longer supported.
  payload[:admin] = admin unless admin.nil?

  begin
    new_client = chef_rest_v1.put("clients/#{name}", payload)
  rescue Net::HTTPClientException => e
    # rescue API V0 if 406 and the server supports V0
    supported_versions = server_client_api_version_intersection(e, SUPPORTED_API_VERSIONS)
    raise e unless supported_versions && supported_versions.include?(0)

    new_client = chef_rest_v0.put("clients/#{name}", payload)
  end

  Chef::ApiClientV1.from_hash(new_client)
end

#validator(arg = nil) ⇒ Boolean

Gets or sets whether this client is a validator.

Parameters:

  • arg (Boolean) (defaults to: nil)

    whether or not the client is a validator. If ‘nil`, retrieves the already-set value.

Returns:

  • (Boolean)

    The current value



116
117
118
119
120
121
122
# File 'lib/chef/api_client_v1.rb', line 116

def validator(arg = nil)
  set_or_return(
    :validator,
    arg,
    kind_of: [TrueClass, FalseClass]
  )
end