diff --git a/Gemfile.lock b/Gemfile.lock index c9dff76..b60718d 100644 --- a/Gemfile.lock +++ b/Gemfile.lock @@ -5,7 +5,7 @@ PATH docker-api (~> 2.1) dotenv (~> 2.7) excon (~> 0.47) - kubeclient (~> 4.9) + kubeclient (~> 4.10) newrelic_rpm (~> 7.1) prometheus-client (~> 2.1) @@ -42,8 +42,8 @@ GEM json (2.6.3) jsonpath (1.1.0) multi_json - kubeclient (4.9.3) - http (>= 3.0, < 5.0) + kubeclient (4.13.0) + http (>= 3.0, < 6.0) jsonpath (~> 1.0) recursive-open-struct (~> 1.1, >= 1.1.1) rest-client (~> 2.0) diff --git a/exe/scaltainer b/exe/scaltainer index 5e28dcd..d45e955 100755 --- a/exe/scaltainer +++ b/exe/scaltainer @@ -5,6 +5,14 @@ require 'scaltainer' begin configfile, statefile, logger, wait, orchestrator, pushgateway, enable_newrelic_reporting = Scaltainer::Command.parse ARGV Scaltainer::Runner.new configfile, statefile, logger, wait, orchestrator, pushgateway, enable_newrelic_reporting +rescue Scaltainer::AuthenticationError => e + # Credentials were rejected by the orchestrator. There is nothing this + # process can do about it while it is running, so exit non-zero and let the + # orchestrator restart us; on restart the credential is read from disk again. + # A dedicated exit code keeps this distinguishable from ordinary failures in + # `kubectl describe pod` (State -> Terminated -> Exit Code). + $stderr.puts "FATAL: #{e.message}" + exit 77 rescue => e $stderr.puts e.message $stderr.puts e.backtrace diff --git a/lib/scaltainer/exceptions.rb b/lib/scaltainer/exceptions.rb index 3dd4078..c57edc2 100644 --- a/lib/scaltainer/exceptions.rb +++ b/lib/scaltainer/exceptions.rb @@ -3,4 +3,14 @@ class ApplicationError < RuntimeError; end class ConfigurationError < ApplicationError; end class NetworkError < ApplicationError; end class Warning < ApplicationError; end + + # Raised when the orchestrator rejects our credentials (HTTP 401). + # + # Deliberately NOT a descendant of ApplicationError (and therefore not of + # RuntimeError), so that it is *not* caught by the `rescue RuntimeError` + # handlers in Runner#iterate_services that exist to skip one bad service and + # keep looping. An expired credential is not recoverable by continuing the + # loop: the process has to exit so the orchestrator restarts it and the + # credential is read from disk again. + class AuthenticationError < StandardError; end end \ No newline at end of file diff --git a/lib/scaltainer/orchestrators/kubernetes.rb b/lib/scaltainer/orchestrators/kubernetes.rb index cb6e7f5..676edc9 100644 --- a/lib/scaltainer/orchestrators/kubernetes.rb +++ b/lib/scaltainer/orchestrators/kubernetes.rb @@ -8,7 +8,9 @@ def initialize(name, namespace) # if namespace not specified, use the one found in configuration namespace ||= @@namespace || 'default' super(name, type, namespace) - @resource = @@client.send("get_#{@type}", normalize_name(@name), @namespace) + @resource = self.class.raising_authentication_errors do + @@client.send("get_#{@type}", normalize_name(@name), @namespace) + end @id = @resource.metadata.uid end @@ -17,7 +19,38 @@ def get_replicas end def set_replicas(replicas) - @@client.send("patch_#{@type}", normalize_name(@name), {spec: {replicas: replicas}}, @namespace) + self.class.raising_authentication_errors do + @@client.send("patch_#{@type}", normalize_name(@name), {spec: {replicas: replicas}}, @namespace) + end + end + + # Translate an HTTP 401 from the Kubernetes API into Scaltainer::AuthenticationError. + # + # 401 (as opposed to 403) means the API server could not authenticate us at + # all, before RBAC was even consulted. For a pod authenticating with a + # projected service account token that almost always means the bearer token + # this process read at startup has expired: kubelet rotates the file on disk + # (at 80% of the token TTL, or every 24h, whichever comes first) but the + # token is passed to Kubeclient as a string, so a long-running process keeps + # presenting the copy it read when it booted. + # + # Retrying cannot fix that, and neither can skipping the service, so we let + # the error escape all the way out of the run loop and terminate the + # process. Kubernetes then restarts the container, which re-reads the token. + # + # 403 and every other status are left alone: those are genuine + # authorization/config problems where crash-looping would only hide the + # cause and stop the remaining services from being scaled. + def self.raising_authentication_errors + yield + rescue Kubeclient::HttpError => e + raise unless e.error_code == 401 + raise Scaltainer::AuthenticationError.new( + "Kubernetes API returned 401 Unauthorized: #{e.message}. " \ + "The credential this process is using is no longer accepted " \ + "(most likely an expired service account token that was read once at " \ + "startup). Exiting so the container is restarted with a fresh token." + ) end private @@ -52,7 +85,15 @@ def self.get_client_from_serviceaccount(serviceaccount) client_cert: OpenSSL::X509::Certificate.new(read_secret(serviceaccount, 'ca.crt')), verify_ssl: ssl_verify } - auth_options = {bearer_token: read_secret(serviceaccount, 'token')} + # Pass the *path*, not the contents. Kubeclient >= 4.10 re-reads this file + # on every request, so a long-lived client keeps working when kubelet + # rotates the projected service account token underneath us. + # + # Reading the token once here (`bearer_token: read_secret(...)`) froze it + # at boot: since Kubernetes 1.21 in-cluster tokens are short-lived and + # rotated in place, so every request started failing with 401 once the + # boot-time copy expired, and only a restart cleared it. + auth_options = {bearer_token_file: token_path(serviceaccount)} @@namespace = read_secret(serviceaccount, 'namespace') url = get_api_url('https://kubernetes.default:443') version = get_api_version('v1') @@ -74,7 +115,15 @@ def self.get_api_version(default_version) end def self.read_secret(serviceaccount, secret) - File.read("#{serviceaccount}/#{secret}") + File.read(secret_path(serviceaccount, secret)) + end + + def self.secret_path(serviceaccount, secret) + "#{serviceaccount}/#{secret}" + end + + def self.token_path(serviceaccount) + secret_path(serviceaccount, 'token') end def normalize_name(name) diff --git a/lib/scaltainer/runner.rb b/lib/scaltainer/runner.rb index 531433e..d36052f 100644 --- a/lib/scaltainer/runner.rb +++ b/lib/scaltainer/runner.rb @@ -26,13 +26,20 @@ def initialize(configfile, statefile, logger, wait, orchestrator, pushgateway, e register_pushgateway(pushgateway) if pushgateway register_newrelic if enable_newrelic_reporting namespace = config["namespace"] || config["stack_name"] - loop do - run config, state, service_type_web, service_type_worker, namespace - save_state statefile, state - sync_pushgateway(namespace, state) if pushgateway - sync_newrelic(state) if enable_newrelic_reporting - sleep wait - break if wait == 0 + begin + loop do + run config, state, service_type_web, service_type_worker, namespace + save_state statefile, state + sync_pushgateway(namespace, state) if pushgateway + sync_newrelic(state) if enable_newrelic_reporting + sleep wait + break if wait == 0 + end + rescue Scaltainer::AuthenticationError => e + # Log through the normal logger so the reason shows up in `kubectl logs` + # in the same format as everything else, then let it terminate the run. + @logger.fatal e.message + raise end end @@ -107,6 +114,10 @@ def get_service(service_name, namespace) elsif @orchestrator == :kubernetes KubeResource.new service_name, namespace end + rescue Scaltainer::AuthenticationError + # Not a "resource not found" problem: our credentials were rejected. + # Let it through untouched so it terminates the process. + raise rescue => e raise NetworkError.new "Could not find resource with name #{service_name} in namespace #{namespace}: #{e.message}" end @@ -120,6 +131,8 @@ def scale_out(service, current_replicas, desired_replicas) @logger.info "Scaling #{service.type} #{service.name} from #{current_replicas} to #{desired_replicas}" begin service.set_replicas desired_replicas + rescue Scaltainer::AuthenticationError + raise rescue => e raise NetworkError.new "Could not scale #{service.type} #{service.name} due to error: #{e.message}" end diff --git a/scaltainer.gemspec b/scaltainer.gemspec index 2527405..18ece45 100644 --- a/scaltainer.gemspec +++ b/scaltainer.gemspec @@ -31,7 +31,9 @@ Gem::Specification.new do |spec| spec.add_runtime_dependency "excon", "~> 0.47" spec.add_runtime_dependency "docker-api", "~> 2.1" - spec.add_runtime_dependency "kubeclient", "~> 4.9" + # >= 4.10 re-reads :bearer_token_file on every request, which is what keeps a + # long-running process working across service account token rotation. + spec.add_runtime_dependency "kubeclient", "~> 4.10" spec.add_runtime_dependency "dotenv", "~> 2.7" spec.add_runtime_dependency "prometheus-client", "~> 2.1" spec.add_runtime_dependency "newrelic_rpm", "~> 7.1" diff --git a/spec/scaltainer/orchestrators/kubernetes_spec.rb b/spec/scaltainer/orchestrators/kubernetes_spec.rb new file mode 100644 index 0000000..5934b9d --- /dev/null +++ b/spec/scaltainer/orchestrators/kubernetes_spec.rb @@ -0,0 +1,81 @@ +require 'spec_helper' + +describe Scaltainer::AuthenticationError do + it 'is a StandardError' do + expect(described_class.new('x')).to be_a StandardError + end + + # This is the whole point of the class: Runner#iterate_services rescues + # RuntimeError in order to skip a single misbehaving service and keep the + # loop alive. An expired credential must NOT be skipped that way, so the + # class must sit outside the RuntimeError branch of the hierarchy. + it 'is not a RuntimeError, so the Runner loop handlers cannot swallow it' do + expect(described_class.ancestors).not_to include(RuntimeError) + expect(described_class.ancestors).not_to include(Scaltainer::ApplicationError) + end +end + +describe Scaltainer::KubeResource do + describe '.get_client_from_serviceaccount' do + let(:dir) { '/var/run/secrets/kubernetes.io/serviceaccount' } + let(:captured) { {} } + + before do + allow(described_class).to receive(:read_secret).with(dir, 'ca.crt').and_return('CA') + allow(described_class).to receive(:read_secret).with(dir, 'namespace').and_return('rayyan-staging') + allow(OpenSSL::X509::Certificate).to receive(:new).with('CA').and_return(:cert) + allow(Kubeclient::Client).to receive(:new) { |*_a, **kw| captured.merge!(kw); :client } + end + + # The whole point of the kubeclient >= 4.10 bump: handing over the path lets + # kubeclient re-read the file per request, so a rotated token is picked up. + # Handing over the contents freezes the token at process start. + it 'passes the token file path, not the token contents' do + described_class.get_client_from_serviceaccount(dir) + + expect(captured[:auth_options]).to eq(bearer_token_file: "#{dir}/token") + end + + it 'never reads the token file itself' do + described_class.get_client_from_serviceaccount(dir) + + expect(described_class).not_to have_received(:read_secret).with(dir, 'token') + end + end + + describe '.raising_authentication_errors' do + it 'returns the block value when nothing is raised' do + expect(described_class.raising_authentication_errors { :ok }).to eq :ok + end + + it 'translates HTTP 401 into Scaltainer::AuthenticationError' do + expect { + described_class.raising_authentication_errors do + raise Kubeclient::HttpError.new(401, 'Unauthorized', nil) + end + }.to raise_error(Scaltainer::AuthenticationError, /401 Unauthorized/) + end + + it 'leaves HTTP 403 alone so RBAC problems do not crash-loop the pod' do + expect { + described_class.raising_authentication_errors do + raise Kubeclient::HttpError.new(403, 'Forbidden', nil) + end + }.to raise_error(Kubeclient::HttpError) + end + + it 'leaves HTTP 404 alone so a genuinely missing resource is still skipped' do + expect { + described_class.raising_authentication_errors do + raise Kubeclient::ResourceNotFoundError.new(404, 'Not Found', nil) + end + }.to raise_error(Kubeclient::ResourceNotFoundError) + end + + it 'leaves non-kubeclient errors alone' do + expect { + described_class.raising_authentication_errors { raise IOError, 'socket went away' } + }.to raise_error(IOError) + end + end +end diff --git a/spec/scaltainer/runner_spec.rb b/spec/scaltainer/runner_spec.rb new file mode 100644 index 0000000..8265dc7 --- /dev/null +++ b/spec/scaltainer/runner_spec.rb @@ -0,0 +1,71 @@ +require 'spec_helper' + +describe Scaltainer::Runner do + # Runner#initialize does a lot of I/O, and everything under test here is + # private behaviour reachable without it, so allocate a bare instance and set + # only the ivars the methods actually touch. + let(:runner) { described_class.allocate } + let(:logger) { Logger.new(File::NULL) } + + before do + runner.instance_variable_set(:@logger, logger) + runner.instance_variable_set(:@orchestrator, :kubernetes) + runner.instance_variable_set(:@default_service_config, {}) + end + + describe '#get_service' do + it 'lets AuthenticationError through instead of relabelling it as NetworkError' do + allow(Scaltainer::KubeResource).to receive(:new) + .and_raise(Scaltainer::AuthenticationError.new('token expired')) + + expect { runner.send(:get_service, 'customizer_by_filter', 'rayyan-staging') } + .to raise_error(Scaltainer::AuthenticationError, /token expired/) + end + + it 'still wraps every other failure as NetworkError' do + allow(Scaltainer::KubeResource).to receive(:new).and_raise(IOError.new('boom')) + + expect { runner.send(:get_service, 'customizer_by_filter', 'rayyan-staging') } + .to raise_error(Scaltainer::NetworkError, /Could not find resource with name/) + end + end + + describe '#scale_out' do + let(:service) { double('service', type: 'deployment', name: 'customizer-by-filter') } + + it 'lets AuthenticationError through' do + allow(service).to receive(:set_replicas) + .and_raise(Scaltainer::AuthenticationError.new('token expired')) + + expect { runner.send(:scale_out, service, 1, 2) } + .to raise_error(Scaltainer::AuthenticationError) + end + + it 'still wraps every other failure as NetworkError' do + allow(service).to receive(:set_replicas).and_raise(IOError.new('boom')) + + expect { runner.send(:scale_out, service, 1, 2) } + .to raise_error(Scaltainer::NetworkError, /Could not scale/) + end + end + + describe '#iterate_services' do + let(:type) { double('service_type', get_metrics: {}, to_s: 'web') } + let(:services) { {'customizer_by_filter' => {}} } + + it 'propagates AuthenticationError out of the per-service loop' do + allow(Scaltainer::KubeResource).to receive(:new) + .and_raise(Scaltainer::AuthenticationError.new('token expired')) + + expect { runner.send(:iterate_services, services, 'rayyan-staging', type, {}) } + .to raise_error(Scaltainer::AuthenticationError) + end + + it 'keeps swallowing ordinary errors so one bad service does not stop the rest' do + allow(Scaltainer::KubeResource).to receive(:new).and_raise(IOError.new('boom')) + + expect { runner.send(:iterate_services, services, 'rayyan-staging', type, {}) } + .not_to raise_error + end + end +end