require 'picsolve_docker_builder/helpers/kubernetes/pod' require 'picsolve_docker_builder/helpers/kubernetes/resource' module PicsolveDockerBuilder module Helpers module Kubernetes # Ruby representation of a kuberentes replication cluster class Rc < Resource def initialize(image, kubernetes, rc = nil) super(image, kubernetes) @rc = rc end def existing_rcs rcs = client.get_replication_controllers( namespace: @image.composer.namespace ).select do |rc| rc.metadata.name.match(/^#{@image.name}/) end rcs.map do |rc| Rc.new(@image, @kubernetes, rc) end end def config_rc # configure the service @rc.metadata = {} unless @rc.metadata @rc.metadata.name = "#{@image.name}-#{@image.composer.hash}" @rc.metadata.namespace = @image.composer.namespace @rc.metadata.labels = template_labels @rc.spec = {} unless @rc.spec @rc.spec.replicas = 1 @rc.spec.selector = template_labels_pods @rc.spec.template = { 'metadata' => { 'labels' => template_labels_pods }, 'spec' => { 'containers' => containers } } end def containers c = { 'name' => @image.name, 'image' => @image.repo_tag_unique, 'ports' => @image.ports_rc } # append environment variables if in place if @image.class.instance_methods.include? :environment env = @image.environment c['env'] = env unless env.nil? end [c] end def deploy @old_rcs = existing_rcs @rc = Kubeclient::ReplicationController.new config_rc log.debug "create replication controller #{@rc.metadata.name}" client.create_replication_controller @rc end def wait ready? end def ready? pods.each do |pod| result = pod.ready? return false unless result end true end def pods_by_selector(selector) client.get_pods( namespace: @rc.metadata.namespace, label_selector: selector ).map do |pod| Pod.new(pod, @kubernetes) end end def pods pods_by_selector( "name=#{@rc.spec.selector.name}," \ "deployment=#{@rc.spec.selector.deployment}" ) end def pods_orphan pods_by_selector( "name=#{@rc.spec.selector.name}," \ "deployment!=#{@rc.spec.selector.deployment}" ) end def remove_pods_orphan pods_orphan.each(&:remove) end def remove_pods pods.each(&:remove) end def remove log.debug "remove replication controller #{@rc.metadata.name}" client.delete_replication_controller( @rc.metadata.name, @rc.metadata.namespace ) remove_pods end def remove_old_rcs @old_rcs.each(&:remove) end def template_labels_pods c = template_labels c['deployment'] = @image.composer.hash c end end end end end