Class: Controlplane

Inherits:
Object
  • Object
show all
Defined in:
lib/core/controlplane.rb

Overview

rubocop:disable Metrics/ClassLength

Constant Summary collapse

NO_IMAGE_AVAILABLE =
"NO_IMAGE_AVAILABLE"

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(config) ⇒ Controlplane

Returns a new instance of Controlplane.



10
11
12
13
14
15
16
17
# File 'lib/core/controlplane.rb', line 10

def initialize(config)
  @config = config
  @api = ControlplaneApi.new
  @gvc = config.app
  @org = config.org

  ensure_org_exists! if org
end

Instance Attribute Details

#apiObject (readonly)

Returns the value of attribute api.



6
7
8
# File 'lib/core/controlplane.rb', line 6

def api
  @api
end

#configObject (readonly)

Returns the value of attribute config.



6
7
8
# File 'lib/core/controlplane.rb', line 6

def config
  @config
end

#gvcObject (readonly)

Returns the value of attribute gvc.



6
7
8
# File 'lib/core/controlplane.rb', line 6

def gvc
  @gvc
end

#orgObject (readonly)

Returns the value of attribute org.



6
7
8
# File 'lib/core/controlplane.rb', line 6

def org
  @org
end

Instance Method Details

#apply_hash(data, wait: false) ⇒ Object



435
436
437
# File 'lib/core/controlplane.rb', line 435

def apply_hash(data, wait: false)
  apply_template(data.to_yaml, wait: wait)
end

#apply_template(data, wait: false) ⇒ Object

apply



409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
# File 'lib/core/controlplane.rb', line 409

def apply_template(data, wait: false) # rubocop:disable Metrics/MethodLength, Metrics/PerceivedComplexity
  Tempfile.create do |f|
    f.write(data)
    f.rewind
    cmd = "cpln apply #{gvc_org} --file #{f.path}"
    cmd += " --ready" if wait && ENV.fetch("DISABLE_APPLY_READY", nil).nil?
    if Shell.tmp_stderr
      cmd += " 2> #{Shell.tmp_stderr.path}" if Shell.should_hide_output?

      Shell.debug("CMD", cmd)

      result = Shell.cmd(cmd)
      parse_apply_result(result[:output]) if result[:success]
    else
      Shell.debug("CMD", cmd)

      result = Shell.cmd(cmd)
      if result[:success]
        parse_apply_result(result[:output])
      else
        Shell.abort("Command exited with non-zero status.")
      end
    end
  end
end

#bind_identity_to_policy(identity_link, policy) ⇒ Object



398
399
400
401
# File 'lib/core/controlplane.rb', line 398

def bind_identity_to_policy(identity_link, policy)
  cmd = "cpln policy add-binding #{policy} --org #{org} --identity #{identity_link} --permission reveal"
  perform!(cmd)
end

#cron_workload_deployed_version(workload) ⇒ Object



303
304
305
306
307
308
309
310
311
# File 'lib/core/controlplane.rb', line 303

def cron_workload_deployed_version(workload)
  current_deployment = fetch_workload_deployments(workload)&.dig("items")&.first
  return nil unless current_deployment

  ready = current_deployment.dig("status", "ready")
  last_processed_version = current_deployment.dig("status", "lastProcessedVersion")

  ready ? last_processed_version : nil
end

#delete_volumeset(volumeset, a_gvc = gvc) ⇒ Object



319
320
321
# File 'lib/core/controlplane.rb', line 319

def delete_volumeset(volumeset, a_gvc = gvc)
  api.delete_volumeset(org: org, gvc: a_gvc, volumeset: volumeset)
end

#delete_workload(workload, a_gvc = gvc) ⇒ Object



270
271
272
# File 'lib/core/controlplane.rb', line 270

def delete_workload(workload, a_gvc = gvc)
  api.delete_workload(org: org, gvc: a_gvc, workload: workload)
end

#domain_workload_matches?(data, workload) ⇒ Boolean

Returns:

  • (Boolean)


353
354
355
356
# File 'lib/core/controlplane.rb', line 353

def domain_workload_matches?(data, workload)
  route = find_domain_route(data)
  route["workloadLink"].match?(%r{/org/#{org}/gvc/#{gvc}/workload/#{workload}})
end

#extract_image_commit(image_name) ⇒ Object



84
85
86
# File 'lib/core/controlplane.rb', line 84

def extract_image_commit(image_name)
  image_name.match(/_(\h+)$/)&.captures&.first
end

#extract_image_number(image_name) ⇒ Object



78
79
80
81
82
# File 'lib/core/controlplane.rb', line 78

def extract_image_number(image_name)
  return 0 if image_name.end_with?(NO_IMAGE_AVAILABLE)

  image_name.match(/:(\d+)/)&.captures&.first.to_i
end

#fetch_cron_workload(workload, location:) ⇒ Object



298
299
300
301
# File 'lib/core/controlplane.rb', line 298

def fetch_cron_workload(workload, location:)
  cmd = "cpln workload cron get #{workload} #{gvc_org} --location #{location} -o yaml"
  perform_yaml(cmd)
end

#fetch_domain(domain) ⇒ Object



345
346
347
348
349
350
351
# File 'lib/core/controlplane.rb', line 345

def fetch_domain(domain)
  domain_data = api.fetch_domain(org: org, domain: domain)
  route = find_domain_route(domain_data)
  return nil if route.nil?

  domain_data
end

#fetch_gvc(a_gvc = gvc, a_org = org) ⇒ Object



151
152
153
# File 'lib/core/controlplane.rb', line 151

def fetch_gvc(a_gvc = gvc, a_org = org)
  api.gvc_get(gvc: a_gvc, org: a_org)
end

#fetch_gvc!(a_gvc = gvc) ⇒ Object



155
156
157
158
159
160
# File 'lib/core/controlplane.rb', line 155

def fetch_gvc!(a_gvc = gvc)
  gvc_data = fetch_gvc(a_gvc)
  return gvc_data if gvc_data

  raise "Can't find app '#{gvc}', please create it with 'cpflow setup-app -a #{config.app}'."
end

#fetch_gvcsObject

gvc



138
139
140
# File 'lib/core/controlplane.rb', line 138

def fetch_gvcs
  api.gvc_list(org: org)
end

#fetch_identity(identity, a_gvc = gvc) ⇒ Object

identities



388
389
390
# File 'lib/core/controlplane.rb', line 388

def fetch_identity(identity, a_gvc = gvc)
  api.fetch_identity(org: org, gvc: a_gvc, identity: identity)
end

#fetch_image_details(image) ⇒ Object



108
109
110
# File 'lib/core/controlplane.rb', line 108

def fetch_image_details(image)
  api.fetch_image_details(org: org, image: image)
end

#fetch_policy(policy) ⇒ Object

policies



394
395
396
# File 'lib/core/controlplane.rb', line 394

def fetch_policy(policy)
  api.fetch_policy(org: org, policy: policy)
end

#fetch_secret(secret) ⇒ Object

secrets



382
383
384
# File 'lib/core/controlplane.rb', line 382

def fetch_secret(secret)
  api.fetch_secret(org: org, secret: secret)
end

#fetch_volumesets(a_gvc = gvc) ⇒ Object

volumeset



315
316
317
# File 'lib/core/controlplane.rb', line 315

def fetch_volumesets(a_gvc = gvc)
  api.list_volumesets(org: org, gvc: a_gvc)
end

#fetch_workload(workload) ⇒ Object



176
177
178
# File 'lib/core/controlplane.rb', line 176

def fetch_workload(workload)
  api.workload_get(workload: workload, gvc: gvc, org: org)
end

#fetch_workload!(workload) ⇒ Object



180
181
182
183
184
185
186
# File 'lib/core/controlplane.rb', line 180

def fetch_workload!(workload)
  workload_data = fetch_workload(workload)
  return workload_data if workload_data

  raise "Can't find workload '#{workload}', " \
        "please create it with 'cpflow apply-template #{workload} -a #{config.app}'."
end

#fetch_workload_deployments(workload) ⇒ Object



206
207
208
# File 'lib/core/controlplane.rb', line 206

def fetch_workload_deployments(workload)
  api.workload_deployments(workload: workload, gvc: gvc, org: org)
end

#fetch_workload_replicas(workload, location:) ⇒ Object



196
197
198
199
# File 'lib/core/controlplane.rb', line 196

def fetch_workload_replicas(workload, location:)
  cmd = "cpln workload replica get #{workload} #{gvc_org} --location #{location} -o yaml 2> /dev/null"
  perform_yaml(cmd)
end

#fetch_workloads(a_gvc = gvc) ⇒ Object

workload



168
169
170
# File 'lib/core/controlplane.rb', line 168

def fetch_workloads(a_gvc = gvc)
  api.workload_list(gvc: a_gvc, org: org)
end

#fetch_workloads_by_org(a_org = org) ⇒ Object



172
173
174
# File 'lib/core/controlplane.rb', line 172

def fetch_workloads_by_org(a_org = org)
  api.workload_list_by_org(org: a_org)
end

#find_domain_for(workloads) ⇒ Object



335
336
337
338
339
340
341
342
343
# File 'lib/core/controlplane.rb', line 335

def find_domain_for(workloads)
  domains = api.list_domains(org: org)["items"]
  domains.find do |domain_data|
    route = find_domain_route(domain_data)
    next false if route.nil?

    workloads.any? { |workload| route["workloadLink"].match?(%r{/org/#{org}/gvc/#{gvc}/workload/#{workload}}) }
  end
end

#find_domain_route(data) ⇒ Object

domain



325
326
327
328
329
330
331
332
333
# File 'lib/core/controlplane.rb', line 325

def find_domain_route(data)
  port = data["spec"]["ports"].find { |current_port| [80, 443].include?(current_port["number"]) }
  return nil if port.nil? || port["routes"].nil?

  route = port["routes"].find { |current_route| current_route["prefix"] == "/" }
  return nil if route.nil?

  route
end

#gvc_delete(a_gvc = gvc) ⇒ Object



162
163
164
# File 'lib/core/controlplane.rb', line 162

def gvc_delete(a_gvc = gvc)
  api.gvc_delete(gvc: a_gvc, org: org)
end

#gvc_query(app_name = config.app) ⇒ Object



142
143
144
145
146
147
148
149
# File 'lib/core/controlplane.rb', line 142

def gvc_query(app_name = config.app)
  # When `match_if_app_name_starts_with` is `true`, we query for any gvc containing the name,
  # otherwise we query for a gvc with the exact name.
  op = config.should_app_start_with?(app_name) ? "~" : "="

  cmd = "cpln gvc query --org #{org} -o yaml --prop name#{op}#{app_name}"
  perform_yaml!(cmd)
end

#image_build(image, dockerfile:, docker_context:, docker_args: [], build_args: []) ⇒ Object



95
96
97
98
99
100
101
102
103
104
105
106
# File 'lib/core/controlplane.rb', line 95

def image_build(image, dockerfile:, docker_context:, docker_args: [], build_args: [])
  # https://docs.controlplane.com/guides/push-image#step-2
  # Might need to use `docker buildx build` if compatiblitity issues arise
  cmd = ["docker", "build", "--platform=linux/amd64", "-t", image, "-f", dockerfile]
  cmd << "--progress=plain" if ControlplaneApiDirect.trace

  cmd.concat(docker_args)
  build_args.each { |build_arg| cmd.concat(["--build-arg", build_arg]) }
  cmd << docker_context

  perform!(Shellwords.join(cmd))
end

#image_delete(image) ⇒ Object



112
113
114
# File 'lib/core/controlplane.rb', line 112

def image_delete(image)
  api.image_delete(org: org, image: image)
end

#image_login(org_name = config.org) ⇒ Object



116
117
118
119
# File 'lib/core/controlplane.rb', line 116

def (org_name = config.org)
  cmd = "cpln image docker-login --org #{org_name}"
  perform!(cmd, output_mode: :none)
end

#image_pull(image) ⇒ Object



121
122
123
124
# File 'lib/core/controlplane.rb', line 121

def image_pull(image)
  cmd = "docker pull #{image}"
  perform!(cmd, output_mode: :none)
end

#image_push(image) ⇒ Object



131
132
133
134
# File 'lib/core/controlplane.rb', line 131

def image_push(image)
  cmd = "docker push #{image}"
  perform!(cmd)
end

#image_tag(old_tag, new_tag) ⇒ Object



126
127
128
129
# File 'lib/core/controlplane.rb', line 126

def image_tag(old_tag, new_tag)
  cmd = "docker tag #{old_tag} #{new_tag}"
  perform!(cmd)
end

#latest_image(a_gvc = gvc, a_org = org) ⇒ Object

image



44
45
46
47
48
49
50
51
# File 'lib/core/controlplane.rb', line 44

def latest_image(a_gvc = gvc, a_org = org)
  @latest_image ||= {}
  @latest_image[a_gvc] ||=
    begin
      items = query_images(a_gvc, a_org)["items"]
      latest_image_from(items, app_name: a_gvc)
    end
end

#latest_image_from(items, app_name: gvc, name_only: true) ⇒ Object



66
67
68
69
70
71
72
73
74
75
76
# File 'lib/core/controlplane.rb', line 66

def latest_image_from(items, app_name: gvc, name_only: true)
  matching_items = items.select { |item| item["name"].start_with?("#{app_name}:") }

  # Or special string to indicate no image available
  if matching_items.empty?
    name_only ? "#{app_name}:#{NO_IMAGE_AVAILABLE}" : nil
  else
    latest_item = matching_items.max_by { |item| DateTime.parse(item["created"]) }
    name_only ? latest_item["name"] : latest_item
  end
end

#latest_image_next(a_gvc = gvc, a_org = org, commit: nil) ⇒ Object



53
54
55
56
57
58
59
60
61
62
63
64
# File 'lib/core/controlplane.rb', line 53

def latest_image_next(a_gvc = gvc, a_org = org, commit: nil)
  commit ||= config.options[:commit]

  @latest_image_next ||= {}
  @latest_image_next[a_gvc] ||= begin
    latest_image_name = latest_image(a_gvc, a_org)
    image = latest_image_name.split(":").first
    image += ":#{extract_image_number(latest_image_name) + 1}"
    image += "_#{commit}" if commit
    image
  end
end

#log_get(workload:, from:, to:, replica: nil) ⇒ Object



376
377
378
# File 'lib/core/controlplane.rb', line 376

def log_get(workload:, from:, to:, replica: nil)
  api.log_get(org: org, gvc: gvc, workload: workload, replica: replica, from: from, to: to)
end

#logs(workload:, limit:, since:, replica: nil) ⇒ Object

logs



367
368
369
370
371
372
373
374
# File 'lib/core/controlplane.rb', line 367

def logs(workload:, limit:, since:, replica: nil)
  query_parts = ["gvc=\"#{gvc}\"", "workload=\"#{workload}\""]
  query_parts.push("replica=\"#{replica}\"") if replica
  query = "{#{query_parts.join(',')}}"

  cmd = "cpln logs '#{query}' --org #{org} -t -o raw --limit #{limit} --since #{since}"
  perform!(cmd, output_mode: :all)
end

#parse_apply_result(result) ⇒ Object

rubocop:disable Metrics/CyclomaticComplexity, Metrics/MethodLength, Metrics/PerceivedComplexity



439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
# File 'lib/core/controlplane.rb', line 439

def parse_apply_result(result) # rubocop:disable Metrics/CyclomaticComplexity, Metrics/MethodLength, Metrics/PerceivedComplexity
  items = []

  lines = result.split("\n")
  lines.each do |line|
    # The line can be in one of these formats:
    # - "Created /org/shakacode-open-source-examples/gvc/my-app-staging"
    # - "Created /org/shakacode-open-source-examples/gvc/my-app-staging/workload/redis"
    # - "Updated gvc 'tutorial-app-test-1'"
    # - "Updated workload 'redis'"
    if line.start_with?("Created")
      matches = line.match(%r{Created\s/org/[^/]+/gvc/([^/]+)($|(/([^/]+)/([^/]+)$))})&.captures
      next unless matches

      app, _, __, kind, name = matches
      if kind
        items.push({ kind: kind, name: name })
      else
        items.push({ kind: "app", name: app })
      end
    else
      matches = line.match(/Updated\s([^\s]+)\s'([^\s]+)'$/)&.captures
      next unless matches

      kind, name = matches
      kind = "app" if kind == "gvc"
      items.push({ kind: kind, name: name })
    end
  end

  items
end

#profile_create(profile, token) ⇒ Object



31
32
33
34
35
# File 'lib/core/controlplane.rb', line 31

def profile_create(profile, token)
  sensitive_data_pattern = /(?<=--token )(\S+)/
  cmd = "cpln profile create #{profile} --token #{token}"
  perform!(cmd, sensitive_data_pattern: sensitive_data_pattern)
end

#profile_delete(profile) ⇒ Object



37
38
39
40
# File 'lib/core/controlplane.rb', line 37

def profile_delete(profile)
  cmd = "cpln profile delete #{profile}"
  perform!(cmd)
end

#profile_exists?(profile) ⇒ Boolean

Returns:

  • (Boolean)


26
27
28
29
# File 'lib/core/controlplane.rb', line 26

def profile_exists?(profile)
  cmd = "cpln profile get #{profile} -o yaml"
  perform_yaml!(cmd).length.positive?
end

#profile_switch(profile) ⇒ Object

profile



21
22
23
24
# File 'lib/core/controlplane.rb', line 21

def profile_switch(profile)
  ENV["CPLN_PROFILE"] = profile
  ControlplaneApiDirect.reset_api_token
end

#query_images(a_gvc = gvc, a_org = org, partial_gvc_match: nil) ⇒ Object



88
89
90
91
92
93
# File 'lib/core/controlplane.rb', line 88

def query_images(a_gvc = gvc, a_org = org, partial_gvc_match: nil)
  partial_gvc_match = config.should_app_start_with?(a_gvc) if partial_gvc_match.nil?
  gvc_op = partial_gvc_match ? "~" : "="

  api.query_images(org: a_org, gvc: a_gvc, gvc_op_type: gvc_op)
end

#query_workloads(workload, a_gvc = gvc, a_org = org, partial_workload_match: false, partial_gvc_match: nil) ⇒ Object



188
189
190
191
192
193
194
# File 'lib/core/controlplane.rb', line 188

def query_workloads(workload, a_gvc = gvc, a_org = org, partial_workload_match: false, partial_gvc_match: nil)
  partial_gvc_match = config.should_app_start_with?(a_gvc) if partial_gvc_match.nil?
  gvc_op = partial_gvc_match ? "~" : "="
  workload_op = partial_workload_match ? "~" : "="

  api.query_workloads(org: a_org, gvc: a_gvc, workload: workload, gvc_op_type: gvc_op, workload_op_type: workload_op)
end

#set_domain_workload(data, workload) ⇒ Object



358
359
360
361
362
363
# File 'lib/core/controlplane.rb', line 358

def set_domain_workload(data, workload)
  route = find_domain_route(data)
  route["workloadLink"] = "/org/#{org}/gvc/#{gvc}/workload/#{workload}"

  api.update_domain(org: org, domain: data["name"], data: data)
end

#set_workload_env_var(workload, container:, name:, value:) ⇒ Object



238
239
240
241
242
243
244
245
246
247
248
249
250
251
# File 'lib/core/controlplane.rb', line 238

def set_workload_env_var(workload, container:, name:, value:)
  data = fetch_workload!(workload)
  data["spec"]["containers"].each do |container_data|
    next unless container_data["name"] == container

    container_data["env"].each do |env_data|
      next unless env_data["name"] == name

      env_data["value"] = value
    end
  end

  api.update_workload(org: org, gvc: gvc, workload: workload, data: data)
end

#set_workload_suspend(workload, value) ⇒ Object



253
254
255
256
257
258
# File 'lib/core/controlplane.rb', line 253

def set_workload_suspend(workload, value)
  data = fetch_workload!(workload)
  data["spec"]["defaultOptions"]["suspend"] = value

  api.update_workload(org: org, gvc: gvc, workload: workload, data: data)
end

#start_cron_workload(workload, job_start_yaml, location:) ⇒ Object



288
289
290
291
292
293
294
295
296
# File 'lib/core/controlplane.rb', line 288

def start_cron_workload(workload, job_start_yaml, location:)
  Tempfile.create do |f|
    f.write(job_start_yaml)
    f.rewind

    cmd = "cpln workload cron start #{workload} #{gvc_org} --file #{f.path} --location #{location} -o yaml"
    perform_yaml(cmd)
  end
end

#stop_workload_replica(workload, replica, location:) ⇒ Object



201
202
203
204
# File 'lib/core/controlplane.rb', line 201

def stop_workload_replica(workload, replica, location:)
  cmd = "cpln workload replica stop #{workload} #{gvc_org} --replica-name #{replica} --location #{location}"
  perform(cmd, output_mode: :none)
end

#unbind_identity_from_policy(identity_link, policy) ⇒ Object



403
404
405
406
# File 'lib/core/controlplane.rb', line 403

def unbind_identity_from_policy(identity_link, policy)
  cmd = "cpln policy remove-binding #{policy} --org #{org} --identity #{identity_link} --permission reveal"
  perform!(cmd)
end

#workload_connect(workload, location:, container: nil, shell: nil) ⇒ Object



274
275
276
277
278
279
# File 'lib/core/controlplane.rb', line 274

def workload_connect(workload, location:, container: nil, shell: nil)
  cmd = "cpln workload connect #{workload} #{gvc_org} --location #{location}"
  cmd += " --container #{container}" if container
  cmd += " --shell #{shell}" if shell
  perform!(cmd, output_mode: :all)
end

#workload_deployment_version_ready?(version, next_version) ⇒ Boolean

Returns:

  • (Boolean)


210
211
212
213
214
215
216
# File 'lib/core/controlplane.rb', line 210

def workload_deployment_version_ready?(version, next_version)
  return false unless version["workload"] == next_version

  version["containers"]&.all? do |_, container|
    container.dig("resources", "replicas") == container.dig("resources", "replicasReady")
  end
end

#workload_deployments_ready?(workload, location:, expected_status:) ⇒ Boolean

rubocop:disable Metrics/CyclomaticComplexity

Returns:

  • (Boolean)


218
219
220
221
222
223
224
225
226
227
228
229
230
# File 'lib/core/controlplane.rb', line 218

def workload_deployments_ready?(workload, location:, expected_status:) # rubocop:disable Metrics/CyclomaticComplexity
  deployed_replicas = fetch_workload_replicas(workload, location: location)&.dig("items")&.length || 0
  return deployed_replicas.zero? if expected_status == false

  deployments = fetch_workload_deployments(workload)["items"]
  deployments.all? do |deployment|
    next_version = deployment.dig("status", "expectedDeploymentVersion")

    deployment.dig("status", "versions")&.all? do |version|
      workload_deployment_version_ready?(version, next_version)
    end
  end
end

#workload_exec(workload, replica, location:, container: nil, command: nil) ⇒ Object



281
282
283
284
285
286
# File 'lib/core/controlplane.rb', line 281

def workload_exec(workload, replica, location:, container: nil, command: nil)
  cmd = "cpln workload exec #{workload} #{gvc_org} --replica #{replica} --location #{location} -it"
  cmd += " --container #{container}" if container
  cmd += " -- #{command}"
  perform!(cmd, output_mode: :all)
end

#workload_force_redeployment(workload) ⇒ Object



265
266
267
268
# File 'lib/core/controlplane.rb', line 265

def workload_force_redeployment(workload)
  cmd = "cpln workload force-redeployment #{workload} #{gvc_org}"
  perform!(cmd)
end

#workload_set_image_ref(workload, container:, image:) ⇒ Object



232
233
234
235
236
# File 'lib/core/controlplane.rb', line 232

def workload_set_image_ref(workload, container:, image:)
  cmd = "cpln workload update #{workload} #{gvc_org}"
  cmd += " --set spec.containers.#{container}.image=/org/#{config.org}/image/#{image}"
  perform!(cmd)
end

#workload_suspended?(workload) ⇒ Boolean

Returns:

  • (Boolean)


260
261
262
263
# File 'lib/core/controlplane.rb', line 260

def workload_suspended?(workload)
  details = fetch_workload!(workload)
  details["spec"]["defaultOptions"]["suspend"]
end