Module: Kubeclient::ClientMixin

Included in:
Client
Defined in:
lib/kubeclient/common.rb

Overview

Common methods

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Instance Attribute Details

#api_endpointObject (readonly)

Returns the value of attribute api_endpoint.



6
7
8
# File 'lib/kubeclient/common.rb', line 6

def api_endpoint
  @api_endpoint
end

#auth_optionsObject (readonly)

Returns the value of attribute auth_options.



8
9
10
# File 'lib/kubeclient/common.rb', line 8

def auth_options
  @auth_options
end

#headersObject (readonly)

Returns the value of attribute headers.



9
10
11
# File 'lib/kubeclient/common.rb', line 9

def headers
  @headers
end

#ssl_optionsObject (readonly)

Returns the value of attribute ssl_options.



7
8
9
# File 'lib/kubeclient/common.rb', line 7

def ssl_options
  @ssl_options
end

Class Method Details

.define_entity_methods(entity_types) ⇒ Object



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
# File 'lib/kubeclient/common.rb', line 76

def self.define_entity_methods(entity_types)
  entity_types.each do |klass, entity_type|
    entity_name = entity_type.underscore
    entity_name_plural = pluralize_entity(entity_name)

    # get all entities of a type e.g. get_nodes, get_pods, etc.
    define_method("get_#{entity_name_plural}") do |options = {}|
      get_entities(entity_type, klass, options)
    end

    # watch all entities of a type e.g. watch_nodes, watch_pods, etc.
    define_method("watch_#{entity_name_plural}") \
    do |options = {}|
      # This method used to take resource_version as a param, so
      # this conversion is to keep backwards compatibility
      options = { resource_version: options } unless options.is_a?(Hash)

      watch_entities(entity_type, options)
    end

    # get a single entity of a specific type by name
    define_method("get_#{entity_name}") do |name, namespace = nil|
      get_entity(entity_type, klass, name, namespace)
    end

    define_method("delete_#{entity_name}") do |name, namespace = nil|
      delete_entity(entity_type, name, namespace)
    end

    define_method("create_#{entity_name}") do |entity_config|
      create_entity(entity_type, entity_config, klass)
    end

    define_method("update_#{entity_name}") do |entity_config|
      update_entity(entity_type, entity_config)
    end
  end
end

.pluralize_entity(entity_name) ⇒ Object



115
116
117
118
# File 'lib/kubeclient/common.rb', line 115

def self.pluralize_entity(entity_name)
  return entity_name + 's' if entity_name.end_with? 'quota'
  entity_name.pluralize
end

Instance Method Details

#apiObject



306
307
308
309
310
311
# File 'lib/kubeclient/common.rb', line 306

def api
  response = handle_exception do
    create_rest_client.get(@headers)
  end
  JSON.parse(response)
end

#api_valid?Boolean

Returns:

  • (Boolean)


301
302
303
304
# File 'lib/kubeclient/common.rb', line 301

def api_valid?
  result = api
  result.is_a?(Hash) && (result['versions'] || []).include?(@api_version)
end

#build_namespace_prefix(namespace) ⇒ Object



70
71
72
# File 'lib/kubeclient/common.rb', line 70

def build_namespace_prefix(namespace)
  namespace.to_s.empty? ? '' : "namespaces/#{namespace}/"
end

#create_entity(entity_type, entity_config, klass) ⇒ Object



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
# File 'lib/kubeclient/common.rb', line 209

def create_entity(entity_type, entity_config, klass)
  # Duplicate the entity_config to a hash so that when we assign
  # kind and apiVersion, this does not mutate original entity_config obj.
  hash = entity_config.to_hash

  ns_prefix = build_namespace_prefix(hash[:metadata][:namespace])

  # TODO: temporary solution to add "kind" and apiVersion to request
  # until this issue is solved
  # https://github.com/GoogleCloudPlatform/kubernetes/issues/6439
  # TODO: #2 solution for
  # https://github.com/kubernetes/kubernetes/issues/8115
  if entity_type.eql? 'Endpoint'
    hash[:kind] = resource_name(entity_type).capitalize
  else
    hash[:kind] = entity_type
  end
  hash[:apiVersion] = @api_version
  response = handle_exception do
    rest_client[ns_prefix + resource_name(entity_type)]
    .post(hash.to_json, @headers)
  end
  result = JSON.parse(response)
  new_entity(result, klass)
end

#create_rest_client(path = nil) ⇒ Object



120
121
122
123
124
125
126
127
128
129
130
131
132
# File 'lib/kubeclient/common.rb', line 120

def create_rest_client(path = nil)
  path ||= @api_endpoint.path
  options = {
    ssl_ca_file: @ssl_options[:ca_file],
    ssl_cert_store: @ssl_options[:cert_store],
    verify_ssl: @ssl_options[:verify_ssl],
    ssl_client_cert: @ssl_options[:client_cert],
    ssl_client_key: @ssl_options[:client_key],
    user: @auth_options[:username],
    password: @auth_options[:password]
  }
  RestClient::Resource.new(@api_endpoint.merge(path).to_s, options)
end

#delete_entity(entity_type, name, namespace = nil) ⇒ Object



201
202
203
204
205
206
207
# File 'lib/kubeclient/common.rb', line 201

def delete_entity(entity_type, name, namespace = nil)
  ns_prefix = build_namespace_prefix(namespace)
  handle_exception do
    rest_client[ns_prefix + resource_name(entity_type) + "/#{name}"]
      .delete(@headers)
  end
end

#get_entities(entity_type, klass, options = {}) ⇒ Object

Accepts the following string options:

:namespace - the namespace of the entity.
:label_selector - a selector to restrict the list of returned objects by their labels.
:field_selector - a selector to restrict the list of returned objects by their fields.


165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
# File 'lib/kubeclient/common.rb', line 165

def get_entities(entity_type, klass, options = {})
  params = {}
  [:label_selector, :field_selector].each do |p|
    params[p.to_s.camelize(:lower)] = options[p] if options[p]
  end

  ns_prefix = build_namespace_prefix(options[:namespace])
  response = handle_exception do
    rest_client[ns_prefix + resource_name(entity_type)]
    .get({ 'params' => params }.merge(@headers))
  end

  result = JSON.parse(response)

  resource_version = result.fetch('resourceVersion', nil)
  if resource_version.nil?
    resource_version =
        result.fetch('metadata', {}).fetch('resourceVersion', nil)
  end

  # result['items'] might be nil due to https://github.com/kubernetes/kubernetes/issues/13096
  collection = result['items'].to_a.map { |item| new_entity(item, klass) }

  Kubeclient::Common::EntityList.new(entity_type, resource_version, collection)
end

#get_entity(entity_type, klass, name, namespace = nil) ⇒ Object



191
192
193
194
195
196
197
198
199
# File 'lib/kubeclient/common.rb', line 191

def get_entity(entity_type, klass, name, namespace = nil)
  ns_prefix = build_namespace_prefix(namespace)
  response = handle_exception do
    rest_client[ns_prefix + resource_name(entity_type) + "/#{name}"]
    .get(@headers)
  end
  result = JSON.parse(response)
  new_entity(result, klass)
end

#get_pod_log(pod_name, namespace, container: nil, previous: false) ⇒ Object



259
260
261
262
263
264
265
266
267
268
269
# File 'lib/kubeclient/common.rb', line 259

def get_pod_log(pod_name, namespace, container: nil, previous: false)
  params = {}
  params[:previous] = true if previous
  params[:container] = container if container

  ns = build_namespace_prefix(namespace)
  handle_exception do
    rest_client[ns + "pods/#{pod_name}/log"]
      .get({ 'params' => params }.merge(@headers))
  end
end

#handle_exceptionObject



50
51
52
53
54
55
56
57
58
59
60
# File 'lib/kubeclient/common.rb', line 50

def handle_exception
  yield
rescue RestClient::Exception => e
  begin
    json_error_msg = JSON.parse(e.response || '') || {}
  rescue JSON::ParserError
    json_error_msg = {}
  end
  err_message = json_error_msg['message'] || e.message
  raise KubeException.new(e.http_code, err_message, e.response)
end

#handle_uri(uri, path) ⇒ Object



62
63
64
65
66
67
68
# File 'lib/kubeclient/common.rb', line 62

def handle_uri(uri, path)
  fail ArgumentError, 'Missing uri' if uri.nil?
  @api_endpoint = (uri.is_a? URI) ? uri : URI.parse(uri)
  @api_endpoint.path = path if @api_endpoint.path.empty?
  @api_endpoint.path = @api_endpoint.path.chop \
                     if @api_endpoint.path.end_with? '/'
end

#initialize_client(uri, path, version = nil, ssl_options: { client_cert: nil, client_key: nil, ca_file: nil, cert_store: nil, verify_ssl: OpenSSL::SSL::VERIFY_PEER }, auth_options: { username: nil, password: nil, bearer_token: nil, bearer_token_file: nil }, socket_options: { socket_class: nil, ssl_socket_class: nil }) ⇒ Object



11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
# File 'lib/kubeclient/common.rb', line 11

def initialize_client(
  uri,
  path,
  version = nil,
  ssl_options: {
    client_cert: nil,
    client_key: nil,
    ca_file: nil,
    cert_store: nil,
    verify_ssl: OpenSSL::SSL::VERIFY_PEER
  },
  auth_options: {
    username: nil,
    password: nil,
    bearer_token: nil,
    bearer_token_file: nil
  },
  socket_options: {
    socket_class: nil,
    ssl_socket_class: nil
  }
)
  validate_auth_options(auth_options)
  handle_uri(uri, path)

  @api_version = version
  @headers = {}
  @ssl_options = ssl_options
  @auth_options = auth_options
  @socket_options = socket_options

  if auth_options[:bearer_token]
    bearer_token(@auth_options[:bearer_token])
  elsif auth_options[:bearer_token_file]
    validate_bearer_token_file
    bearer_token(File.read(@auth_options[:bearer_token_file]))
  end
end

#new_entity(hash, klass) ⇒ Object



244
245
246
# File 'lib/kubeclient/common.rb', line 244

def new_entity(hash, klass)
  klass.new(hash)
end

#proxy_url(kind, name, port, namespace = '') ⇒ Object



286
287
288
289
290
291
292
293
294
295
# File 'lib/kubeclient/common.rb', line 286

def proxy_url(kind, name, port, namespace = '')
  entity_name_plural = ClientMixin.pluralize_entity(kind.to_s)
  ns_prefix = build_namespace_prefix(namespace)
  # TODO: Change this once services supports the new scheme
  if entity_name_plural == 'pods'
    rest_client["#{ns_prefix}#{entity_name_plural}/#{name}:#{port}/proxy"].url
  else
    rest_client["proxy/#{ns_prefix}#{entity_name_plural}/#{name}:#{port}"].url
  end
end

#resource_name(entity_type) ⇒ Object



297
298
299
# File 'lib/kubeclient/common.rb', line 297

def resource_name(entity_type)
  ClientMixin.pluralize_entity entity_type.downcase
end

#rest_clientObject



134
135
136
137
138
# File 'lib/kubeclient/common.rb', line 134

def rest_client
  @rest_client ||= begin
    create_rest_client("#{@api_endpoint.path}/#{@api_version}")
  end
end

#retrieve_all_entities(entity_types) ⇒ Object



248
249
250
251
252
253
254
255
256
257
# File 'lib/kubeclient/common.rb', line 248

def retrieve_all_entities(entity_types)
  entity_types.each_with_object({}) do |(_, entity_type), result_hash|
    # method call for get each entities
    # build hash of entity name to array of the entities
    entity_name = ClientMixin.pluralize_entity entity_type.underscore
    method_name = "get_#{entity_name}"
    key_name = entity_type.underscore
    result_hash[key_name] = send(method_name)
  end
end

#update_entity(entity_type, entity_config) ⇒ Object



235
236
237
238
239
240
241
242
# File 'lib/kubeclient/common.rb', line 235

def update_entity(entity_type, entity_config)
  name      = entity_config[:metadata][:name]
  ns_prefix = build_namespace_prefix(entity_config[:metadata][:namespace])
  handle_exception do
    rest_client[ns_prefix + resource_name(entity_type) + "/#{name}"]
      .put(entity_config.to_h.to_json, @headers)
  end
end

#watch_entities(entity_type, options = {}) ⇒ Object

Accepts the following string options:

:namespace - the namespace of the entity.
:name - the name of the entity to watch.
:label_selector - a selector to restrict the list of returned objects by their labels.
:field_selector - a selector to restrict the list of returned objects by their fields.
:resource_version - shows changes that occur after that particular version of a resource.


146
147
148
149
150
151
152
153
154
155
156
157
158
159
# File 'lib/kubeclient/common.rb', line 146

def watch_entities(entity_type, options = {})
  ns = build_namespace_prefix(options[:namespace])

  path = "watch/#{ns}#{resource_name(entity_type.to_s)}"
  path += "/#{options[:name]}" if options[:name]
  uri = @api_endpoint.merge("#{@api_endpoint.path}/#{@api_version}/#{path}")

  params = options.slice(:label_selector, :field_selector, :resource_version)
  if params.any?
    uri.query = URI.encode_www_form(params.map { |k, v| [k.to_s.camelize(:lower), v] })
  end

  Kubeclient::Common::WatchStream.new(uri, http_options(uri))
end

#watch_pod_log(pod_name, namespace, container: nil) ⇒ Object



271
272
273
274
275
276
277
278
279
280
281
282
283
284
# File 'lib/kubeclient/common.rb', line 271

def watch_pod_log(pod_name, namespace, container: nil)
  # Adding the "follow=true" query param tells the Kubernetes API to keep
  # the connection open and stream updates to the log.
  params = { follow: true }
  params[:container] = container if container

  ns = build_namespace_prefix(namespace)

  uri = @api_endpoint.dup
  uri.path += "/#{@api_version}/#{ns}pods/#{pod_name}/log"
  uri.query = URI.encode_www_form(params)

  Kubeclient::Common::WatchStream.new(uri, http_options(uri), format: :text)
end