Class: Dapp::Kube::Kubernetes::Client

Inherits:
Object
  • Object
show all
Extended by:
Helper::YAML
Includes:
Helper::YAML
Defined in:
lib/dapp/kube/kubernetes/client.rb

Defined Under Namespace

Modules: Error, Resource

Class Method Summary collapse

Instance Method Summary collapse

Methods included from Helper::YAML

yaml_load, yaml_load_file

Constructor Details

#initialize(namespace: nil) ⇒ Client

Returns a new instance of Client.



57
58
59
60
61
# File 'lib/dapp/kube/kubernetes/client.rb', line 57

def initialize(namespace: nil)
  @namespace = namespace
  @query_parameters = {}
  @cluster_version
end

Class Method Details

.kube_cluster_config(kube_config, cluster_name) ⇒ Object



354
355
356
# File 'lib/dapp/kube/kubernetes/client.rb', line 354

def kube_cluster_config(kube_config, cluster_name)
  kube_config.fetch('clusters', []).find {|cluster| cluster['name'] == cluster_name}
end

.kube_config(kube_config_path) ⇒ Object



333
334
335
# File 'lib/dapp/kube/kubernetes/client.rb', line 333

def kube_config(kube_config_path)
  yaml_load_file(kube_config_path) if File.exist?(kube_config_path)
end

.kube_config_pathObject



327
328
329
330
331
# File 'lib/dapp/kube/kubernetes/client.rb', line 327

def kube_config_path
  kube_config_path = ENV['KUBECONFIG']
  kube_config_path = File.join(ENV['HOME'], '.kube/config') unless kube_config_path
  kube_config_path
end

.kube_context_config(kube_config, kube_context_name) ⇒ Object



346
347
348
# File 'lib/dapp/kube/kubernetes/client.rb', line 346

def kube_context_config(kube_config, kube_context_name)
  kube_config.fetch('contexts', []).find {|context| context['name'] == kube_context_name}
end

.kube_context_name(kube_config) ⇒ Object



337
338
339
340
341
342
343
344
# File 'lib/dapp/kube/kubernetes/client.rb', line 337

def kube_context_name(kube_config)
  kube_config['current-context'] || begin
    if (context = kube_config.fetch('contexts', []).first)
      warn "[WARN] .kube/config current-context is not set, using context '#{context['name']}'"
      context['name']
    end
  end
end

.kube_context_namespace(kube_context_config) ⇒ Object



358
359
360
# File 'lib/dapp/kube/kubernetes/client.rb', line 358

def kube_context_namespace(kube_context_config)
  kube_context_config['context']['namespace']
end

.kube_user_config(kube_config, user_name) ⇒ Object



350
351
352
# File 'lib/dapp/kube/kubernetes/client.rb', line 350

def kube_user_config(kube_config, user_name)
  kube_config.fetch('users', []).find {|user| user['name'] == user_name}
end

Instance Method Details

#cluster_version(**query_parameters) ⇒ Object

minikube returns empty major and minor. Fallback to stable only apis for minikube setup



165
166
167
168
169
170
171
172
173
174
175
176
177
# File 'lib/dapp/kube/kubernetes/client.rb', line 165

def cluster_version(**query_parameters)
  version_obj = request!(:get, "/version", **query_parameters)
  @cluster_version ||= begin
    major = version_obj['major']
    minor = version_obj['minor']
    k8s_version = "#{version_obj['major']}.#{version_obj['minor']}"
    if K8S_API_ENDPOINTS.has_key?(k8s_version)
      k8s_version
    else
      "stable"
    end
  end
end

#create_namespace!(name, **query_parameters) ⇒ Object



156
157
158
# File 'lib/dapp/kube/kubernetes/client.rb', line 156

def create_namespace!(name, **query_parameters)
  request!(:post, '/api/v1/namespaces', body: { metadata: { name: name } }, **query_parameters)
end

#delete_namespace!(name, **query_parameters) ⇒ Object



160
161
162
# File 'lib/dapp/kube/kubernetes/client.rb', line 160

def delete_namespace!(name, **query_parameters)
  request!(:delete, "/api/v1/namespaces/#{name}", **query_parameters)
end

#event_list(**query_parameters) ⇒ Object



201
202
203
# File 'lib/dapp/kube/kubernetes/client.rb', line 201

def event_list(**query_parameters)
  request!(:get, "/api/v1/namespaces/#{namespace}/events", **query_parameters)
end

#namespaceObject



63
64
65
# File 'lib/dapp/kube/kubernetes/client.rb', line 63

def namespace
  @namespace || self.class.kube_context_namespace(kube_context_config) || "default"
end

#namespace?(name, **query_parameters) ⇒ Boolean

Returns:

  • (Boolean)


152
153
154
# File 'lib/dapp/kube/kubernetes/client.rb', line 152

def namespace?(name, **query_parameters)
  namespace_list(**query_parameters)['items'].map { |item| item['metadata']['name'] }.include?(name)
end

#namespace_list(**query_parameters) ⇒ Object



148
149
150
# File 'lib/dapp/kube/kubernetes/client.rb', line 148

def namespace_list(**query_parameters)
  request!(:get, '/api/v1/namespaces', **query_parameters)
end

#pod_log(name, follow: false, **query_parameters, &blk) ⇒ Object



179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
# File 'lib/dapp/kube/kubernetes/client.rb', line 179

def pod_log(name, follow: false, **query_parameters, &blk)
  excon_parameters = follow ? { response_block: blk } : {}
  request!(:get,
           "/api/v1/namespaces/#{namespace}/pods/#{name}/log",
           excon_parameters: excon_parameters,
           response_body_parameters: {json: false},
           **{ follow: follow }.merge(query_parameters))
rescue Excon::Error::Timeout
  raise Error::Timeout
rescue Error::Base => err
  if err.net_status[:code] == :bad_request and err.net_status[:data][:response_body]
    msg = err.net_status[:data][:response_body]['message']
    if msg.end_with? 'ContainerCreating'
      raise Error::Pod::ContainerCreating, data: err.net_status[:data]
    elsif msg.end_with? 'PodInitializing'
      raise Error::Pod::PodInitializing, data: err.net_status[:data]
    end
  end

  raise
end

#resource_endpoint_path(resource) ⇒ Object

NOTICE: Название метода аналогично kind’у выдаваемого результата. NOTICE: В данном случае в результате kind=DeploymentList. NOTICE: Методы создания/обновления/удаления сущностей kubernetes заканчиваются на ‘!’. Например, create_deployment!. В каждом методе происходит выбор api на основе версии кластера



95
96
97
98
99
# File 'lib/dapp/kube/kubernetes/client.rb', line 95

def resource_endpoint_path(resource)
  K8S_API_ENDPOINTS[cluster_version()].map do |path, resources|
    resources.include?(resource) ? path : nil
  end.compact.first
end

#with_namespace(namespace, &blk) ⇒ Object

Чтобы не перегружать методы явной передачей namespace. Данный метод может пригодиться только в ситуации, когда надо указать другой namespace, в большинстве случаев используется namespace из конструктора.



70
71
72
73
74
75
76
77
78
# File 'lib/dapp/kube/kubernetes/client.rb', line 70

def with_namespace(namespace, &blk)
  old_namespace = @namespace
  begin
    @namespace = namespace
    return yield
  ensure
    @namespace = old_namespace
  end
end

#with_query(query, &blk) ⇒ Object



80
81
82
83
84
85
86
87
88
# File 'lib/dapp/kube/kubernetes/client.rb', line 80

def with_query(query, &blk)
  old_query = @query_parameters
  begin
    @query_parameters = query
    return yield
  ensure
    @query_parameters = old_query
  end
end