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



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

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 |resource_version = nil|
      watch_entities(entity_type, resource_version)
    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



105
106
107
108
# File 'lib/kubeclient/common.rb', line 105

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

Instance Method Details

#apiObject



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

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

#api_valid?Boolean

Returns:

  • (Boolean)


247
248
249
250
# File 'lib/kubeclient/common.rb', line 247

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

#build_namespace_prefix(namespace) ⇒ Object



64
65
66
# File 'lib/kubeclient/common.rb', line 64

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

#create_entity(entity_type, entity_config, klass) ⇒ Object



185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
# File 'lib/kubeclient/common.rb', line 185

def create_entity(entity_type, entity_config, klass)
  # to_hash should be called because of issue #9 in recursive open
  # struct
  hash = entity_config.to_hash

  ns_prefix = build_namespace_prefix(entity_config.['table'][:namespace])

  # TODO: temporary solution to add "kind" and apiVersion to request
  # until this issue is solved
  # https://github.com/GoogleCloudPlatform/kubernetes/issues/6439
  hash['kind'] = entity_type
  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



110
111
112
113
114
115
116
117
118
119
120
121
# File 'lib/kubeclient/common.rb', line 110

def create_rest_client(path = nil)
  path ||= @api_endpoint.path
  options = {
    ssl_ca_file: @ssl_options[:ca_file],
    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



177
178
179
180
181
182
183
# File 'lib/kubeclient/common.rb', line 177

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



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

def get_entities(entity_type, klass, options = {})
  params = {}
  if options[:label_selector]
    params['params'] = { labelSelector: options[:label_selector] }
  end

  ns_prefix = build_namespace_prefix(options[:namespace])
  response = handle_exception do
    rest_client[ns_prefix + resource_name(entity_type)]
    .get(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



167
168
169
170
171
172
173
174
175
# File 'lib/kubeclient/common.rb', line 167

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

#handle_exceptionObject



44
45
46
47
48
49
50
51
52
53
54
# File 'lib/kubeclient/common.rb', line 44

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



56
57
58
59
60
61
62
# File 'lib/kubeclient/common.rb', line 56

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, verify_ssl: OpenSSL::SSL::VERIFY_PEER }, auth_options: { username: nil, password: nil, bearer_token: nil, bearer_token_file: 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
# 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,
    verify_ssl: OpenSSL::SSL::VERIFY_PEER
  },
  auth_options: {
    username: nil,
    password: nil,
    bearer_token: nil,
    bearer_token_file: nil
  }
)
  validate_auth_options(auth_options)
  handle_uri(uri, path)

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

  if auth_options[:bearer_token]
    @headers[:Authorization] = "Bearer #{@auth_options[:bearer_token]}"
  elsif auth_options[:bearer_token_file]
    validate_bearer_token_file
    @headers[:Authorization] = "Bearer #{File.read(@auth_options[:bearer_token_file])}"
  end
end

#new_entity(hash, klass) ⇒ Object



217
218
219
# File 'lib/kubeclient/common.rb', line 217

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

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



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

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



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

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

#rest_clientObject



123
124
125
126
127
# File 'lib/kubeclient/common.rb', line 123

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

#retrieve_all_entities(entity_types) ⇒ Object



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

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



205
206
207
208
209
210
211
212
213
214
215
# File 'lib/kubeclient/common.rb', line 205

def update_entity(entity_type, entity_config)
  name = entity_config..name
  # to_hash should be called because of issue #9 in recursive open
  # struct
  hash = entity_config.to_hash
  ns_prefix = build_namespace_prefix(entity_config.['table'][:namespace])
  handle_exception do
    rest_client[ns_prefix + resource_name(entity_type) + "/#{name}"]
      .put(hash.to_json, @headers)
  end
end

#watch_entities(entity_type, resource_version = nil) ⇒ Object



129
130
131
132
133
134
135
136
137
138
139
# File 'lib/kubeclient/common.rb', line 129

def watch_entities(entity_type, resource_version = nil)
  resource = resource_name(entity_type.to_s)
  uri = @api_endpoint
        .merge("#{@api_endpoint.path}/#{@api_version}/watch/#{resource}")

  unless resource_version.nil?
    uri.query = URI.encode_www_form('resourceVersion' => resource_version)
  end

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