Sha256: 0fe7bd81572a330881aa037a4a0878ee9d748e4691197edead6075e4d832d8c2

Contents?: true

Size: 1.77 KB

Versions: 7

Compression:

Stored size: 1.77 KB

Contents

# frozen_string_literal: true
module KubernetesDeploy
  class SyncMediator
    def initialize(namespace:, context:, logger:)
      @namespace = namespace
      @context = context
      @logger = logger
      clear_cache
    end

    def get_instance(kind, resource_name)
      if @cache.key?(kind)
        @cache.dig(kind, resource_name) || {}
      else
        request_instance(kind, resource_name)
      end
    end

    def get_all(kind, selector = nil)
      fetch_by_kind(kind) unless @cache.key?(kind)
      instances = @cache.fetch(kind, {}).values
      return instances unless selector

      instances.select do |r|
        labels = r.dig("metadata", "labels") || {}
        labels >= selector
      end
    end

    def sync(resources)
      clear_cache
      dependencies = resources.map(&:class).uniq.flat_map do |c|
        c::SYNC_DEPENDENCIES if c.const_defined?('SYNC_DEPENDENCIES')
      end
      kinds = (resources.map(&:type) + dependencies).compact.uniq
      kinds.each { |kind| fetch_by_kind(kind) }

      KubernetesDeploy::Concurrency.split_across_threads(resources) do |r|
        r.sync(dup)
      end
    end

    def kubectl
      @kubectl ||= Kubectl.new(namespace: @namespace, context: @context, logger: @logger, log_failure_by_default: false)
    end

    private

    def clear_cache
      @cache = {}
    end

    def request_instance(kind, iname)
      raw_json, _, st = kubectl.run("get", kind, iname, "-a", "--output=json")
      st.success? ? JSON.parse(raw_json) : {}
    end

    def fetch_by_kind(kind)
      raw_json, _, st = kubectl.run("get", kind, "-a", "--output=json")
      return unless st.success?
      @cache[kind] = JSON.parse(raw_json)["items"].each_with_object({}) do |r, instances|
        instances[r.dig("metadata", "name")] = r
      end
    end
  end
end

Version data entries

7 entries across 7 versions & 1 rubygems

Version Path
kubernetes-deploy-0.20.4 lib/kubernetes-deploy/sync_mediator.rb
kubernetes-deploy-0.20.3 lib/kubernetes-deploy/sync_mediator.rb
kubernetes-deploy-0.20.2 lib/kubernetes-deploy/sync_mediator.rb
kubernetes-deploy-0.20.1 lib/kubernetes-deploy/sync_mediator.rb
kubernetes-deploy-0.20.0 lib/kubernetes-deploy/sync_mediator.rb
kubernetes-deploy-0.19.0 lib/kubernetes-deploy/sync_mediator.rb
kubernetes-deploy-0.18.1 lib/kubernetes-deploy/sync_mediator.rb