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.select do |rc| rc.metadata.name.match(/^#{@image.name}/) && \ rc.metadata.namespace == @image.composer.namespace 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.image_name_tag, 'ports' => @image.ports_rc } # append environment variables if in place if @image.class.instance_methods.include? :environment env = @image.environment(@kubernetes) c['env'] = env unless env.nil? end # append liveness probe if required liveness_probe = @image.liveness_probe c['livenessProbe'] = liveness_probe unless liveness_probe.nil? [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) pods = client.get_pods( namespace: @rc.metadata.namespace, label_selector: selector ).select do |pod| pod.metadata.namespace == @rc.metadata.namespace end pods.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