From 7213657d74a8db4eabe2e6502158843b0695ed60 Mon Sep 17 00:00:00 2001 From: Wei Quan Date: Fri, 23 Oct 2026 14:12:22 +0200 Subject: [PATCH 1/7] feat(observability): add structured logs and Prometheus metrics for blobstore and packer operations --- lib/cloud_controller/blobstore/base_client.rb | 67 +++- .../blobstore/client_provider.rb | 12 +- .../storage_cli/storage_cli_client.rb | 132 ++++++-- .../metrics/prometheus_updater.rb | 69 +++- .../packager/local_bits_packer.rb | 7 +- .../packager/shared_bits_packer.rb | 52 ++- lib/cloud_controller/user_audit_info.rb | 3 +- .../extensions/delayed_jobs_log_redaction.rb | 57 +++- lib/tasks/jobs.rake | 6 + .../blobstore/client_provider_spec.rb | 2 +- .../blobstore/error_handling_client_spec.rb | 2 +- .../blobstore/local/local_client_spec.rb | 41 +++ .../storage_cli/storage_cli_client_spec.rb | 315 +++++++++++++++++- .../metrics/prometheus_updater_spec.rb | 86 ++++- .../packager/local_bits_packer_spec.rb | 21 ++ .../cloud_controller/user_audit_info_spec.rb | 9 +- .../delayed_jobs_log_redaction_spec.rb | 73 ++++ 17 files changed, 883 insertions(+), 71 deletions(-) diff --git a/lib/cloud_controller/blobstore/base_client.rb b/lib/cloud_controller/blobstore/base_client.rb index 585d934f543..40ac0f24484 100644 --- a/lib/cloud_controller/blobstore/base_client.rb +++ b/lib/cloud_controller/blobstore/base_client.rb @@ -1,3 +1,4 @@ +require 'find' require 'cloud_controller/blobstore/blob' require 'cloud_controller/blobstore/blob_key_generator' @@ -5,15 +6,63 @@ module CloudController module Blobstore class BaseClient def cp_r_to_blobstore(source_dir) - Find.find(source_dir).each do |path| - next unless File.file?(path) - next unless within_limits?(File.size(path)) - next unless File.stat(path).mode.to_s(8)[3..5].to_i(8) >= 0o600 + digest_duration = 0 + exists_duration = 0 + upload_duration = 0 + digest_count = 0 + exists_count = 0 + upload_count = 0 + upload_attempts = 0 + traversal_completed = false - sha1 = Digester.new.digest_path(path) - next if exists?(sha1) + begin + unless File.directory?(source_dir) + logger.error('blobstore.cp_r.source_dir_missing', source_dir: source_dir) + raise Errno::ENOENT.new(source_dir) + end - cp_to_blobstore(path, sha1) + Find.find(source_dir).each do |path| + begin + stat = File.stat(path) + rescue SystemCallError + next + end + next unless stat.file? + next unless within_limits?(stat.size) + next unless stat.mode.to_s(8)[3..5].to_i(8) >= 0o600 + + t = Time.now.utc + begin + digest_count += 1 + sha1 = Digester.new.digest_path(path) + ensure + digest_duration += Time.now.utc - t + end + + t = Time.now.utc + begin + exists_count += 1 + exists = exists?(sha1) + ensure + exists_duration += Time.now.utc - t + end + + next if exists + + t = Time.now.utc + upload_attempts += 1 + begin + cp_to_blobstore(path, sha1) + upload_count += 1 + ensure + upload_duration += Time.now.utc - t + end + end + traversal_completed = true + ensure + logger.info('blobstore.cp_r.digest', duration_seconds: digest_duration, count: digest_count, completed: traversal_completed) + logger.info('blobstore.cp_r.exists', duration_seconds: exists_duration, count: exists_count, completed: traversal_completed) + logger.info('blobstore.cp_r.upload', duration_seconds: upload_duration, count: upload_count, attempted: upload_attempts, completed: traversal_completed) end end @@ -23,6 +72,10 @@ def cp_to_blobstore(_, _) private + def logger + @logger ||= Steno.logger('cc.blobstore') + end + def partitioned_key(key) key = key.to_s.downcase partitioned_key = BlobKeyGenerator.full_path_from_key(key) diff --git a/lib/cloud_controller/blobstore/client_provider.rb b/lib/cloud_controller/blobstore/client_provider.rb index 8e30fa1dbb7..ce858ff7701 100644 --- a/lib/cloud_controller/blobstore/client_provider.rb +++ b/lib/cloud_controller/blobstore/client_provider.rb @@ -4,6 +4,8 @@ require 'cloud_controller/blobstore/local/local_client' require 'cloud_controller/blobstore/safe_delete_client' require 'cloud_controller/blobstore/storage_cli/storage_cli_client' +require 'cloud_controller/execution_context' +require 'cloud_controller/metrics/prometheus_updater' module CloudController module Blobstore @@ -49,7 +51,8 @@ def provide_storage_cli(options, directory_key, root_dir, resource_type) resource_type: resource_type, root_dir: root_dir, min_size: options[:minimum_size], - max_size: options[:maximum_size] + max_size: options[:maximum_size], + metrics_updater: metrics_updater_if_registered ) logger = Steno.logger('cc.blobstore.storage_cli_client') @@ -58,6 +61,13 @@ def provide_storage_cli(options, directory_key, root_dir, resource_type) Client.new(SafeDeleteClient.new(retryable_client, root_dir)) end + + def metrics_updater_if_registered + ctx = VCAP::CloudController::ExecutionContext.from_process_type_env + return nil unless VCAP::CloudController::Metrics::PrometheusUpdater::STORAGE_CLI_METRICS_EXECUTION_CONTEXTS.include?(ctx) + + CloudController::DependencyLocator.instance.prometheus_updater + end end end end diff --git a/lib/cloud_controller/blobstore/storage_cli/storage_cli_client.rb b/lib/cloud_controller/blobstore/storage_cli/storage_cli_client.rb index ff05e1701c9..e3b89137ac5 100644 --- a/lib/cloud_controller/blobstore/storage_cli/storage_cli_client.rb +++ b/lib/cloud_controller/blobstore/storage_cli/storage_cli_client.rb @@ -20,7 +20,7 @@ class StorageCliClient < BaseClient # Native storage-cli type names supported by CC STORAGE_CLI_TYPES = %w[azurebs alioss s3 gcs dav].freeze - def initialize(directory_key:, resource_type:, root_dir:, min_size: nil, max_size: nil) + def initialize(directory_key:, resource_type:, root_dir:, min_size: nil, max_size: nil, metrics_updater: nil) raise 'Missing resource_type' if resource_type.nil? config_file_path = config_path_for(resource_type) @@ -40,6 +40,7 @@ def initialize(directory_key:, resource_type:, root_dir:, min_size: nil, max_siz @root_dir = root_dir @min_size = min_size || 0 @max_size = max_size + @metrics_updater = metrics_updater end def fetch_config(resource_type) @@ -102,23 +103,83 @@ def download_from_blobstore(source_key, destination_path, mode: nil) def cp_to_blobstore(source_path, destination_key) start = Time.now.utc log_entry = 'cp-skip' - size = -1 + size = nil logger.info('cp-start', destination_key: destination_key, source_path: source_path, bucket: @directory_key) - File.open(source_path) do |file| - size = file.size - next unless within_limits?(size) + state = { run_cli_called: false, run_cli_succeeded: false, skip_metric_emitted: false } + begin + File.open(source_path) do |file| + size = file.size + log_entry = cp_put_blob(source_path, destination_key, size, start, state) + end + rescue Interrupt, SignalException + log_entry = 'cp-error' + emit_signal_metric_if_needed(start, state) + raise + rescue StandardError + log_entry = 'cp-error' + safe_emit_metrics('put', -3, Time.now.utc - start, 'cp_to_blobstore') unless state[:run_cli_called] + raise + ensure + safe_log_finish(log_entry, destination_key, start, size) + end + end - run_cli('put', source_path, partitioned_key(destination_key)) - log_entry = 'cp-finish' + def cp_put_blob(source_path, destination_key, size, start, state) + if within_limits?(size) + state[:run_cli_called] = true + run_put_with_fatal_rescue(source_path, destination_key, size, start, state) + state[:run_cli_succeeded] = true + 'cp-finish' + else + safe_emit_metrics('put', -4, Time.now.utc - start, 'cp_to_blobstore skip') + state[:skip_metric_emitted] = true + 'cp-skip' end + end - duration = Time.now.utc - start + def run_put_with_fatal_rescue(source_path, destination_key, size, start, state) + run_cli('put', source_path, partitioned_key(destination_key), blob_size: size) + rescue StandardError + # run_cli already emitted a metric before re-raising; nothing to do here. + raise + rescue Exception => e # rubocop:disable Lint/RescueException + # Catches fatal exceptions (NoMemoryError etc.) and signals (Interrupt, SignalException) + # that StandardError does not cover. + # + # For signals: if Interrupt fired after run_cli returned, run_cli already emitted + # exit_code=0 — mark succeeded so the outer handler skips the -6 emit. + # For fatal exceptions: run_cli has not emitted, so emit -7 here. + if e.is_a?(Interrupt) || e.is_a?(SignalException) + state[:run_cli_succeeded] = true + else + safe_emit_metrics('put', -7, Time.now.utc - start, 'fatal exception in run_cli') + end + raise + end + + def emit_signal_metric_if_needed(start, state) + return if state[:run_cli_succeeded] || state[:skip_metric_emitted] + + # -5: signal before CLI was invoked; -6: signal mid-execution after CLI was invoked. + signal_exit_code = state[:run_cli_called] ? -6 : -5 + safe_emit_metrics('put', signal_exit_code, Time.now.utc - start, 'signal in cp_to_blobstore') + end + + def safe_emit_metrics(operation, exit_code, duration, context, blob_size: nil) + emit_storage_cli_metrics(operation, exit_code, duration, blob_size: blob_size) + rescue StandardError => e + logger.warn("emit_storage_cli_metrics failed in #{context}: #{e.inspect}") + end + + def safe_log_finish(log_entry, destination_key, start, size) logger.info(log_entry, destination_key: destination_key, - duration_seconds: duration, + duration_seconds: Time.now.utc - start, size: size) + rescue StandardError => e + logger.warn("cp_to_blobstore ensure log failed: #{e.inspect}") end def cp_file_between_keys(source_key, destination_key) @@ -170,25 +231,50 @@ def additional_flags flags_string.split end - def run_cli(command, *args, allow_exit_code_three: false) + def run_cli(command, *args, allow_exit_code_three: false, blob_size: nil) logger.debug("running storage-cli: #{@cli_path} -s #{@storage_type} -c #{@config_file} #{additional_flags.join(' ')} #{command} #{args.join(' ')}") - begin - stdout, stderr, status = Open3.capture3(@cli_path, '-s', @storage_type, '-c', @config_file, *additional_flags, command, *args) - stderr.split("\n").each do |line| - logger.info("[INFO] storage-cli: #{line}") - end - rescue StandardError => e - raise BlobstoreError.new(e.inspect) - end + t = Time.now.utc + stdout, stderr, status = capture_cli(command, args, t) + duration = Time.now.utc - t + + stderr.split("\n").each { |line| logger.info("[INFO] storage-cli: #{line}") } - unless status.success? || (allow_exit_code_three && status.exitstatus == 3) - raise "storage-cli #{command} failed with exit code #{status.exitstatus}, output: '#{stdout}', error: '#{stderr}'" + exit_code = resolve_exit_code(status) + success = status.success? || (allow_exit_code_three && status.exitstatus == 3) + + unless success + safe_emit_metrics(command, exit_code, duration, 'run_cli failure', blob_size: blob_size) + raise "storage-cli #{command} failed with exit code #{exit_code.inspect}, output: '#{stdout}', error: '#{stderr}'" end + # Remap allowed exit 3 (e.g. key-not-found on exists) to 0 so Prometheus only + # records non-zero exit_codes for genuine failures. + metric_exit_code = allow_exit_code_three && exit_code == 3 ? 0 : exit_code + safe_emit_metrics(command, metric_exit_code, duration, 'run_cli success', blob_size: blob_size) + [stdout, status] end + def capture_cli(command, args, start_time) + Open3.capture3(@cli_path, '-s', @storage_type, '-c', @config_file, *additional_flags, command, *args) + rescue StandardError => e + # exit_code=-1 is a sentinel for spawn failures (binary missing, permission denied). + safe_emit_metrics(command, -1, Time.now.utc - start_time, 'spawn error') + raise BlobstoreError.new(e.inspect) + end + + def resolve_exit_code(status) + if status.exitstatus + status.exitstatus + elsif status.termsig + 128 + status.termsig + else + # exit_code=-2: process exited with neither exitstatus nor termsig (platform anomaly). + -2 + end + end + def sign_url(key, verb:, expires_in_seconds:, use_internal_url: false) command = if @storage_type == 'dav' @@ -228,6 +314,12 @@ def tmpdir def logger @logger ||= Steno.logger('cc.blobstore.storage_cli_client') end + + def emit_storage_cli_metrics(operation, exit_code, duration_seconds, blob_size: nil) + return if @metrics_updater.nil? + + @metrics_updater.report_storage_cli_metrics(operation:, exit_code:, duration_seconds:, blob_size:) + end end end end diff --git a/lib/cloud_controller/metrics/prometheus_updater.rb b/lib/cloud_controller/metrics/prometheus_updater.rb index fc03f27e68a..88d4b24d401 100644 --- a/lib/cloud_controller/metrics/prometheus_updater.rb +++ b/lib/cloud_controller/metrics/prometheus_updater.rb @@ -63,6 +63,39 @@ def self.allow_pid_label { type: :histogram, name: :cc_job_duration_seconds, docstring: 'Job processing time (start to finish)', labels: %i[queue worker], buckets: DELAYED_JOB_METRIC_BUCKETS } ].freeze + STORAGE_CLI_DURATION_BUCKETS = [0.01, 0.05, 0.1, 0.5, 1, 5, 10, 30, 60].freeze + STORAGE_CLI_PUT_OPERATION = 'put'.freeze + STORAGE_CLI_SIZE_BUCKETS = [1_024, 10_240, 102_400, 1_048_576, 10_485_760, 104_857_600, 1_073_741_824].freeze + STORAGE_CLI_METRICS_EXECUTION_CONTEXTS = [ + VCAP::CloudController::ExecutionContext::CC_WORKER, + VCAP::CloudController::ExecutionContext::API_PUMA_MAIN, + VCAP::CloudController::ExecutionContext::API_PUMA_WORKER + ].freeze + + STORAGE_CLI_OPERATIONS_TOTAL_DOCSTRING = + 'Total storage-cli subprocess invocations by operation and exit_code. ' \ + 'exit_code=0: success; exit_code=3: not-found (expected for exists); ' \ + 'exit_code=-1: spawn failure (binary missing or permission denied); ' \ + 'exit_code=-2: process exited with neither exitstatus nor termsig (platform anomaly); ' \ + 'exit_code=-3: source file open/read failure before CLI invocation; ' \ + 'exit_code=-4: upload skipped locally because blob size is outside configured limits; ' \ + 'exit_code=-5: local non-StandardError before CLI invocation (for example Interrupt or SignalException); ' \ + 'exit_code=-6: signal received after CLI invocation began (Interrupt or SignalException mid-execution); ' \ + 'exit_code=-7: fatal non-signal exception escaping run_cli (e.g. NoMemoryError)'.freeze + STORAGE_CLI_METRICS = [ + { type: :counter, name: :cc_storage_cli_operations_total, + docstring: STORAGE_CLI_OPERATIONS_TOTAL_DOCSTRING, + labels: %i[operation exit_code] }, + { type: :histogram, name: :cc_storage_cli_duration_seconds, + docstring: 'Duration of individual storage-cli subprocess invocations. ' \ + 'Counts per-retry, not per logical operation.', + labels: %i[operation exit_code], buckets: STORAGE_CLI_DURATION_BUCKETS }, + { type: :histogram, name: :cc_storage_cli_blob_size_bytes, + docstring: 'Local source file size for storage-cli put operations ' \ + '(only emitted on success; reflects pre-upload size, not remote stored size)', + labels: %i[operation], buckets: STORAGE_CLI_SIZE_BUCKETS } + ].freeze + VITAL_METRICS = [ { type: :gauge, name: :cc_vitals_started_at, docstring: 'CloudController Vitals: started_at', aggregation: :most_recent }, { type: :gauge, name: :cc_vitals_mem_bytes, docstring: 'CloudController Vitals: mem_bytes', aggregation: :most_recent }, @@ -78,8 +111,8 @@ def initialize(registry: Prometheus::Client.registry) @registry = registry @execution_context = VCAP::CloudController::ExecutionContext.from_process_type_env - register_metrics_for_process - return if @execution_context.nil? # In unit tests, the execution context might not be set - thus skip initialization + register_metrics_for_process unless @execution_context.nil? + return if @execution_context.nil? initialize_cc_db_connection_pool_timeouts_total end @@ -92,6 +125,7 @@ def register_metrics_for_process when VCAP::CloudController::ExecutionContext::CC_WORKER DB_CONNECTION_POOL_METRICS.each { |metric| register(metric) } DELAYED_JOB_METRICS.each { |metric| register(metric) } + STORAGE_CLI_METRICS.each { |metric| register(metric) } VITAL_METRICS.each { |metric| register(metric) } when VCAP::CloudController::ExecutionContext::CLOCK, VCAP::CloudController::ExecutionContext::DEPLOYMENT_UPDATER DB_CONNECTION_POOL_METRICS.each { |metric| register(metric) } @@ -99,6 +133,7 @@ def register_metrics_for_process when VCAP::CloudController::ExecutionContext::API_PUMA_MAIN, VCAP::CloudController::ExecutionContext::API_PUMA_WORKER DB_CONNECTION_POOL_METRICS.each { |metric| register(metric) } DELAYED_JOB_METRICS.each { |metric| register(metric) } + STORAGE_CLI_METRICS.each { |metric| register(metric) } VITAL_METRICS.each { |metric| register(metric) } METRICS.each { |metric| register(metric) } PUMA_METRICS.each { |metric| register(metric) } @@ -210,6 +245,34 @@ def report_staging_failure_metrics(duration_ns) update_histogram_metric(:cc_staging_failed_duration_seconds, nanoseconds_to_seconds(duration_ns)) end + def report_storage_cli_metrics(operation:, exit_code:, duration_seconds:, blob_size: nil) + missing_metrics = [] + + if @registry.exist?(:cc_storage_cli_operations_total) + @registry.get(:cc_storage_cli_operations_total).increment(labels: { operation: operation, exit_code: exit_code.to_s }) + else + missing_metrics << :cc_storage_cli_operations_total + end + + if @registry.exist?(:cc_storage_cli_duration_seconds) + update_histogram_metric(:cc_storage_cli_duration_seconds, duration_seconds, labels: { operation: operation, exit_code: exit_code.to_s }) + else + missing_metrics << :cc_storage_cli_duration_seconds + end + + if !blob_size.nil? && exit_code == 0 && operation == STORAGE_CLI_PUT_OPERATION + if @registry.exist?(:cc_storage_cli_blob_size_bytes) + update_histogram_metric(:cc_storage_cli_blob_size_bytes, blob_size, labels: { operation: operation }) + else + missing_metrics << :cc_storage_cli_blob_size_bytes + end + end + + return if missing_metrics.empty? + + Steno.logger('cc.metrics').warn("report_storage_cli_metrics: missing storage_cli metrics #{missing_metrics.join(', ')}") + end + private def register(metric) @@ -230,7 +293,7 @@ def register_metric(type, name, message, labels:, buckets:, aggregation:) when :histogram @registry.histogram(name, docstring: message, labels: labels, buckets: buckets, store_settings: store_settings) else - throw ArgumentError("Metric type #{type} does not exist.") + raise ArgumentError.new("Metric type #{type} does not exist.") end end diff --git a/lib/cloud_controller/packager/local_bits_packer.rb b/lib/cloud_controller/packager/local_bits_packer.rb index 62688d2275b..eae9a2fdce2 100644 --- a/lib/cloud_controller/packager/local_bits_packer.rb +++ b/lib/cloud_controller/packager/local_bits_packer.rb @@ -23,7 +23,12 @@ def send_package_to_blobstore(blobstore_key, uploaded_package_zip, cached_files_ begin complete_package_path = match_resources_and_validate_package(local_bits_packer_path, uploaded_package_zip, cached_files_fingerprints) - package_blobstore.cp_to_blobstore(complete_package_path, blobstore_key) + t = Time.now.utc + begin + package_blobstore.cp_to_blobstore(complete_package_path, blobstore_key) + ensure + logger.info('packer.final-upload', duration_seconds: Time.now.utc - t, blobstore_key: blobstore_key) + end { sha1: Digester.new.digest_path(complete_package_path), diff --git a/lib/cloud_controller/packager/shared_bits_packer.rb b/lib/cloud_controller/packager/shared_bits_packer.rb index 8182a3c8c38..ede8a7febd9 100644 --- a/lib/cloud_controller/packager/shared_bits_packer.rb +++ b/lib/cloud_controller/packager/shared_bits_packer.rb @@ -1,3 +1,4 @@ +require 'find' require 'shellwords' module CloudController @@ -24,11 +25,22 @@ def copy_uploaded_package(uploaded_package_zip, app_packager) def populate_resource_cache(app_packager, app_contents_path) FileUtils.mkdir(app_contents_path) - app_packager.unzip(app_contents_path) + + t = Time.now.utc + begin + app_packager.unzip(app_contents_path) + ensure + logger.info('packer.unzip', duration_seconds: Time.now.utc - t) + end remove_symlinks(app_contents_path) - global_app_bits_cache.cp_r_to_blobstore(app_contents_path) + t = Time.now.utc + begin + global_app_bits_cache.cp_r_to_blobstore(app_contents_path) + ensure + logger.info('packer.resource-cache-upload', duration_seconds: Time.now.utc - t) + end end def remove_symlinks(app_contents_path) @@ -43,19 +55,35 @@ def append_matched_resources(app_packager, cached_files_fingerprints, root_path) FileUtils.mkdir(cached_resources_dir) checksum_mismatch = false - matched_resources.each do |local_destination, file_sha, mode| - file_path = File.join(cached_resources_dir, local_destination) - global_app_bits_cache.download_from_blobstore(file_sha, file_path, mode:) - - if Digester.new.digest_path(file_path) != file_sha - checksum_mismatch = true - global_app_bits_cache.delete(file_sha) + download_count = 0 + download_attempts = 0 + + t = Time.now.utc + begin + matched_resources.each do |local_destination, file_sha, mode| + file_path = File.join(cached_resources_dir, local_destination) + download_attempts += 1 + global_app_bits_cache.download_from_blobstore(file_sha, file_path, mode:) + + if Digester.new.digest_path(file_path) != file_sha + checksum_mismatch = true + global_app_bits_cache.delete(file_sha) + end + + download_count += 1 end + ensure + logger.info('packer.resource-cache-download', duration_seconds: Time.now.utc - t, count: download_count, attempted: download_attempts) end raise CloudController::Errors::ApiError.new_from_details('ResourceChecksumMismatch') if checksum_mismatch - app_packager.append_dir_contents(cached_resources_dir) + t = Time.now.utc + begin + app_packager.append_dir_contents(cached_resources_dir) + ensure + logger.info('packer.repackage', duration_seconds: Time.now.utc - t) + end end def match_resources_and_validate_package(root_path, uploaded_package_zip, cached_files_fingerprints) @@ -82,6 +110,10 @@ def max_package_size def global_app_bits_cache CloudController::DependencyLocator.instance.global_app_bits_cache end + + def logger + @logger ||= Steno.logger('cc.packer') + end end end end diff --git a/lib/cloud_controller/user_audit_info.rb b/lib/cloud_controller/user_audit_info.rb index d3909bf8539..47537479123 100644 --- a/lib/cloud_controller/user_audit_info.rb +++ b/lib/cloud_controller/user_audit_info.rb @@ -18,9 +18,8 @@ def self.from_context(context) ) end - # Non-sensitive identity fields for structured job logging. def hash_for_logs - { user_guid: user_guid, user_email: user_email, user_name: user_name }.compact + { user_guid: user_guid } end end end diff --git a/lib/sequel/extensions/delayed_jobs_log_redaction.rb b/lib/sequel/extensions/delayed_jobs_log_redaction.rb index 8fd87957616..137a8d28c34 100644 --- a/lib/sequel/extensions/delayed_jobs_log_redaction.rb +++ b/lib/sequel/extensions/delayed_jobs_log_redaction.rb @@ -4,38 +4,65 @@ module Sequel::DelayedJobsLogRedaction # Redact the serialized job payload (handler) from any logged SQL that writes the # delayed_jobs table. REDACTED = "'[REDACTED]'" - DELAYED_JOBS_TABLE = /(?:[`"]?\w+[`"]?\.)?[`"]?delayed_jobs[`"]?/i - HANDLER_COLUMN = /[`"]?handler[`"]?/i + DELAYED_JOBS_TABLE = /(?:[`"]?\w+[`"]?\.)?[`"]?delayed_jobs[`"]?(?=\W|$)/i + HANDLER_COLUMN = /\b[`"]?handler[`"]?/i def log_connection_yield(sql, conn, args=nil) - if @loggers.any? && sql.include?('delayed_jobs') + if @loggers.any? && delayed_jobs_write_sql?(sql) + # Compute redacted_indexes before mutating sql so the $N placeholders we scan for + # are from the original SQL, not the already-redacted literal form. + args = redact_args(sql, args) if args.is_a?(Array) sql = redact_delayed_jobs(sql) - # Sequel's base logger appends "; #{args.inspect}" to the logged line. If bound args - # carry the serialized handler, redact there too. - args = redact_args(args) if args.is_a?(Array) && args.any? { |a| sensitive_arg?(a) } end super end private - def redact_delayed_jobs(sql) - return sql unless /\b(?:INSERT INTO|UPDATE)\s+#{DELAYED_JOBS_TABLE}/io.match?(sql) + def delayed_jobs_write_sql?(sql) + /\b(?:INSERT INTO|UPDATE)\s+#{DELAYED_JOBS_TABLE}/io.match?(sql) + end + def redact_delayed_jobs(sql) sql = sql.gsub(/(#{HANDLER_COLUMN}\s*=\s*)'(?:[^']|'')*'/io, "\\1#{REDACTED}") - # INSERT: the handler is a Psych-serialized Ruby object graph, which always starts - # with the '--- !ruby' document marker regardless of the inner tag. - sql.gsub(/'--- !ruby(?:[^']|'')*'/i, REDACTED) + # INSERT only: the handler is a positional value with no column-name context. + # Scoped to INSERT to avoid redacting last_error/cf_api_error on UPDATE statements, + # which may contain '--- !ruby' if a job failed while processing YAML input. + sql = sql.gsub(/'\s*--- !ruby(?:[^']|'')*'/i, REDACTED) if /\bINSERT\b/i.match?(sql) + sql end - def redact_args(args) + def redact_args(sql, args) return args unless args.is_a?(Array) - args.map { |a| sensitive_arg?(a) ? '[REDACTED]' : a } + redacted_indexes = redacted_indexes(sql) + return args if redacted_indexes.empty? + + args.each_with_index.map { |a, index| redacted_indexes.include?(index) ? '[REDACTED]' : a } end - def sensitive_arg?(value) - value.is_a?(String) && value.include?('!ruby') + def redacted_indexes(sql) + indexes = [] + + if (columns = sql[/\bINSERT INTO\s+#{DELAYED_JOBS_TABLE}\s*\((.*?)\)\s*VALUES/i, 1]) && + (values = sql[/\bVALUES\s*\((.*?)\)/i, 1]) + handler_index = columns.split(',').map(&:strip).index { |column| HANDLER_COLUMN.match?(column) } + # Sequel emits all-$N placeholders for bound INSERTs, so VALUES(...) contains no literal commas. + # Scan $N tokens explicitly rather than splitting on commas so a future literal value with a comma + # cannot shift the index arithmetic. + value_placeholders = values.scan(/\$(\d+)/).map { |m| m[0].to_i } + if handler_index && (n = value_placeholders[handler_index]) + indexes << (n - 1) + end + end + + # For UPDATE: scan each "column = $N" assignment directly in the SQL rather than + # extracting the SET clause (a lazy match would stop early if a value contains WHERE). + sql.scan(/#{HANDLER_COLUMN}\s*=\s*\$(\d+)/i) do |match| + indexes << (match[0].to_i - 1) + end + + indexes.uniq end end diff --git a/lib/tasks/jobs.rake b/lib/tasks/jobs.rake index 671e4ec6b05..9c2aa46cf33 100644 --- a/lib/tasks/jobs.rake +++ b/lib/tasks/jobs.rake @@ -32,6 +32,12 @@ namespace :jobs do args.with_defaults(name: queue) RakeConfig.context = :api + VCAP::CloudController::ExecutionContext::API_PUMA_WORKER.set_process_type_env + + require 'prometheus/client/data_stores/direct_file_store' + prometheus_dir = File.join(RakeConfig.config.get(:directories, :tmpdir), 'prometheus') + FileUtils.mkdir_p(prometheus_dir) + Prometheus::Client.config.data_store = Prometheus::Client::DataStores::DirectFileStore.new(dir: prometheus_dir) CloudController::DelayedWorker.new(queues: [queue], name: args.name).start_working diff --git a/spec/unit/lib/cloud_controller/blobstore/client_provider_spec.rb b/spec/unit/lib/cloud_controller/blobstore/client_provider_spec.rb index 6c90ed9c668..50215ae5fc6 100644 --- a/spec/unit/lib/cloud_controller/blobstore/client_provider_spec.rb +++ b/spec/unit/lib/cloud_controller/blobstore/client_provider_spec.rb @@ -28,7 +28,7 @@ module Blobstore allow(StorageCliClient).to receive(:new).and_return(storage_cli_client_mock) ClientProvider.provide(options:, directory_key:, root_dir:, resource_type:) expect(StorageCliClient).to have_received(:new).with(directory_key: directory_key, resource_type: resource_type, root_dir: root_dir, - min_size: 100, max_size: 1000) + min_size: 100, max_size: 1000, metrics_updater: anything) end it 'raises an error if provider is not provided' do diff --git a/spec/unit/lib/cloud_controller/blobstore/error_handling_client_spec.rb b/spec/unit/lib/cloud_controller/blobstore/error_handling_client_spec.rb index d9f77c0c9b7..999b7e057bf 100644 --- a/spec/unit/lib/cloud_controller/blobstore/error_handling_client_spec.rb +++ b/spec/unit/lib/cloud_controller/blobstore/error_handling_client_spec.rb @@ -8,7 +8,7 @@ module Blobstore RSpec.describe ErrorHandlingClient do subject(:client) { ErrorHandlingClient.new(wrapped_client) } let(:wrapped_client) { Blobstore::NullClient.new } - let(:logger) { instance_double(Steno::Logger, error: nil) } + let(:logger) { instance_double(Steno::Logger, error: nil, info: nil) } before do allow(Steno).to receive(:logger).and_return(logger) diff --git a/spec/unit/lib/cloud_controller/blobstore/local/local_client_spec.rb b/spec/unit/lib/cloud_controller/blobstore/local/local_client_spec.rb index 6788bce225d..55715e3e645 100644 --- a/spec/unit/lib/cloud_controller/blobstore/local/local_client_spec.rb +++ b/spec/unit/lib/cloud_controller/blobstore/local/local_client_spec.rb @@ -104,6 +104,47 @@ module Blobstore end end + describe '#cp_r_to_blobstore' do + it 'logs completed: false when traversal is interrupted before any files are processed' do + allow(Find).to receive(:find).and_raise(Errno::EACCES) + + expect do + client.cp_r_to_blobstore(base_path) + end.to raise_error(Errno::EACCES) + + expect(logger).to have_received(:info).with('blobstore.cp_r.digest', hash_including(count: 0, completed: false)) + expect(logger).to have_received(:info).with('blobstore.cp_r.exists', hash_including(count: 0, completed: false)) + expect(logger).to have_received(:info).with('blobstore.cp_r.upload', hash_including(count: 0, attempted: 0, completed: false)) + end + + it 'skips broken symlinks without aborting traversal' do + source_dir = File.join(base_path, 'source') + FileUtils.mkdir_p(source_dir) + File.write(File.join(source_dir, 'file.txt'), 'contents') + File.symlink(File.join(source_dir, 'missing-target.txt'), File.join(source_dir, 'broken-link.txt')) + + expect do + client.cp_r_to_blobstore(source_dir) + end.not_to raise_error + end + + it 'counts a digest attempt even when digest_path raises' do + source_dir = File.join(base_path, 'source') + FileUtils.mkdir_p(source_dir) + File.write(File.join(source_dir, 'file.txt'), 'contents') + + digester = instance_double(Digester) + allow(digester).to receive(:digest_path).and_raise(StandardError.new('digest failed')) + allow(Digester).to receive(:new).and_return(digester) + + expect do + client.cp_r_to_blobstore(source_dir) + end.to raise_error(StandardError, 'digest failed') + + expect(logger).to have_received(:info).with('blobstore.cp_r.digest', hash_including(count: 1, completed: false)) + end + end + describe '#download_from_blobstore' do it 'downloads a file from the blobstore' do key = 'abcdef123456' diff --git a/spec/unit/lib/cloud_controller/blobstore/storage_cli/storage_cli_client_spec.rb b/spec/unit/lib/cloud_controller/blobstore/storage_cli/storage_cli_client_spec.rb index 41d7a7b5d6c..3cf0ed8a930 100644 --- a/spec/unit/lib/cloud_controller/blobstore/storage_cli/storage_cli_client_spec.rb +++ b/spec/unit/lib/cloud_controller/blobstore/storage_cli/storage_cli_client_spec.rb @@ -16,7 +16,7 @@ def stub_config_for_droplets(path) config_double = instance_double(VCAP::CloudController::Config) allow(VCAP::CloudController::Config).to receive(:config).and_return(config_double) allow(config_double).to receive(:get).with(:storage_cli_config_file_droplets).and_return(path) - allow(Steno).to receive(:logger).and_return(double(info: nil, error: nil, debug: nil)) + allow(Steno).to receive(:logger).and_return(double(info: nil, error: nil, debug: nil, warn: nil)) end describe 'client init' do @@ -160,7 +160,7 @@ def stub_config_for_droplets(path) end end - allow(Steno).to receive(:logger).and_return(double(info: nil, error: nil, debug: nil)) + allow(Steno).to receive(:logger).and_return(double(info: nil, error: nil, debug: nil, warn: nil)) end after do @@ -283,6 +283,9 @@ def build_client(resource_type) end it 'returns the default CLI path' do + allow(ENV).to receive(:[]).and_call_original + allow(ENV).to receive(:[]).with('STORAGE_CLI_PATH').and_return(nil) + expect(client.send(:cli_path)).to eq('/var/vcap/packages/storage-cli/bin/storage-cli') end @@ -318,7 +321,7 @@ def build_client(resource_type) tmp_cfg.path end end - allow(Steno).to receive(:logger).and_return(double(info: nil, error: nil, debug: nil)) + allow(Steno).to receive(:logger).and_return(double(info: nil, error: nil, debug: nil, warn: nil)) end after { tmp_cfg.close! } @@ -530,6 +533,312 @@ def build_client(resource_type) expect { client.send(:run_cli, 'list', 'arg1') }.to raise_error(BlobstoreError, /Open3 error/) end + + it 'reports 128+signal when the storage-cli process is terminated by a signal' do + metrics_updater = instance_double(VCAP::CloudController::Metrics::PrometheusUpdater) + allow(metrics_updater).to receive(:report_storage_cli_metrics) + signal_client = StorageCliClient.new( + directory_key: directory_key, + resource_type: resource_type, + root_dir: 'bommel', + metrics_updater: metrics_updater + ) + allow(signal_client).to receive(:additional_flags).and_return([]) + + status = instance_double(Process::Status, success?: false, exitstatus: nil, termsig: 9) + allow(Open3).to receive(:capture3).and_return(['', '', status]) + + expect { signal_client.send(:run_cli, 'get', 'some-key') }.to raise_error(RuntimeError, /exit code 137/) + expect(metrics_updater).to have_received(:report_storage_cli_metrics).with( + operation: 'get', exit_code: 137, duration_seconds: a_kind_of(Float), blob_size: nil + ) + end + + it 'reports exit_code=-1 when Open3 raises (spawn failure)' do + metrics_updater = instance_double(VCAP::CloudController::Metrics::PrometheusUpdater) + allow(metrics_updater).to receive(:report_storage_cli_metrics) + spawning_client = StorageCliClient.new( + directory_key: directory_key, + resource_type: resource_type, + root_dir: 'bommel', + metrics_updater: metrics_updater + ) + allow(spawning_client).to receive(:additional_flags).and_return([]) + allow(Open3).to receive(:capture3).and_raise(Errno::ENOENT.new('storage-cli binary not found')) + + expect { spawning_client.send(:run_cli, 'get', 'some-key') }.to raise_error(BlobstoreError) + expect(metrics_updater).to have_received(:report_storage_cli_metrics).with( + operation: 'get', exit_code: -1, duration_seconds: a_kind_of(Float), blob_size: nil + ) + end + + it 'lets Interrupt propagate from Open3.capture3' do + metrics_updater = instance_double(VCAP::CloudController::Metrics::PrometheusUpdater) + allow(metrics_updater).to receive(:report_storage_cli_metrics) + spawning_client = StorageCliClient.new( + directory_key: directory_key, + resource_type: resource_type, + root_dir: 'bommel', + metrics_updater: metrics_updater + ) + allow(spawning_client).to receive(:additional_flags).and_return([]) + allow(Open3).to receive(:capture3).and_raise(Interrupt) + + expect(metrics_updater).not_to receive(:report_storage_cli_metrics) + expect { spawning_client.send(:run_cli, 'get', 'some-key') }.to raise_error(Interrupt) + end + + context 'metrics' do + let(:metrics_updater) { instance_double(VCAP::CloudController::Metrics::PrometheusUpdater) } + let(:client_with_metrics) do + StorageCliClient.new( + directory_key: directory_key, + resource_type: resource_type, + root_dir: 'bommel', + metrics_updater: metrics_updater + ) + end + + before do + allow(client_with_metrics).to receive(:additional_flags).and_return([]) + allow(metrics_updater).to receive(:report_storage_cli_metrics) + end + + it 'reports metrics with operation and exit_code on success' do + status = instance_double(Process::Status, success?: true, exitstatus: 0) + allow(Open3).to receive(:capture3).and_return(['', '', status]) + + client_with_metrics.send(:run_cli, 'get', 'some-key', 'dest-path') + + expect(metrics_updater).to have_received(:report_storage_cli_metrics).with( + operation: 'get', exit_code: 0, duration_seconds: a_kind_of(Float), blob_size: nil + ) + end + + it 'passes blob_size for put operations' do + status = instance_double(Process::Status, success?: true, exitstatus: 0) + allow(Open3).to receive(:capture3).and_return(['', '', status]) + + client_with_metrics.send(:run_cli, 'put', 'src', 'dest', blob_size: 1024) + + expect(metrics_updater).to have_received(:report_storage_cli_metrics).with( + operation: 'put', exit_code: 0, duration_seconds: a_kind_of(Float), blob_size: 1024 + ) + end + + it 'still reports metrics when the command fails' do + status = instance_double(Process::Status, success?: false, exitstatus: 1) + allow(Open3).to receive(:capture3).and_return(['', 'err', status]) + + expect { client_with_metrics.send(:run_cli, 'put', 'src', 'dest') }.to raise_error(RuntimeError) + expect(metrics_updater).to have_received(:report_storage_cli_metrics).with( + operation: 'put', exit_code: 1, duration_seconds: a_kind_of(Float), blob_size: nil + ) + end + + it 'forwards blob_size to report_storage_cli_metrics even on failure (PrometheusUpdater suppresses the histogram observation)' do + status = instance_double(Process::Status, success?: false, exitstatus: 1) + allow(Open3).to receive(:capture3).and_return(['', 'err', status]) + + # run_cli forwards blob_size to report_storage_cli_metrics regardless of exit_code; + # PrometheusUpdater#report_storage_cli_metrics suppresses histogram observation on failure. + expect { client_with_metrics.send(:run_cli, 'put', 'src', 'dest', blob_size: 2048) }.to raise_error(RuntimeError) + expect(metrics_updater).to have_received(:report_storage_cli_metrics).with( + operation: 'put', exit_code: 1, duration_seconds: a_kind_of(Float), blob_size: 2048 + ) + end + + it 'does not call metrics_updater when nil' do + status = instance_double(Process::Status, success?: true, exitstatus: 0) + allow(Open3).to receive(:capture3).and_return(['', '', status]) + allow(client).to receive(:additional_flags).and_return([]) + + expect { client.send(:run_cli, 'get', 'some-key') }.not_to raise_error + end + end + end + + describe '#cp_to_blobstore' do + let(:logger_double) { double(info: nil, error: nil, debug: nil, warn: nil) } + + before do + allow(Steno).to receive(:logger).and_return(logger_double) + allow(client).to receive(:additional_flags).and_return([]) + end + + it 'logs cp-finish on success' do + source = Tempfile.new('src') + source.write('x' * 1025) + source.flush + + status = instance_double(Process::Status, success?: true, exitstatus: 0) + allow(Open3).to receive(:capture3).and_return(['', '', status]) + + client.cp_to_blobstore(source.path, 'some-key') + + expect(logger_double).to have_received(:info).with('cp-finish', a_hash_including(destination_key: 'some-key')) + ensure + source.close! + end + + it 'logs cp-error when run_cli raises' do + source = Tempfile.new('src') + source.write('x' * 1025) + source.flush + + allow(Open3).to receive(:capture3).and_raise(StandardError.new('blobstore unavailable')) + + expect { client.cp_to_blobstore(source.path, 'some-key') }.to raise_error(BlobstoreError) + expect(logger_double).to have_received(:info).with('cp-error', a_hash_including(destination_key: 'some-key')) + ensure + source.close! + end + + it 'logs cp-skip when file is outside size limits' do + source = Tempfile.new('src') + source.write('x') + source.flush + + small_client = StorageCliClient.new( + directory_key: directory_key, + resource_type: resource_type, + root_dir: 'bommel', + min_size: 1024 + ) + allow(small_client).to receive(:additional_flags).and_return([]) + + small_client.cp_to_blobstore(source.path, 'some-key') + + expect(logger_double).to have_received(:info).with('cp-skip', a_hash_including(destination_key: 'some-key')) + ensure + source.close! + end + + it 'emits exit_code=-4 metric when the file is skipped by size limits' do + source = Tempfile.new('src') + source.write('x') + source.flush + + start_time = Time.utc(2026, 10, 16, 12, 0, 0) + + metrics_updater = instance_double(VCAP::CloudController::Metrics::PrometheusUpdater) + allow(metrics_updater).to receive(:report_storage_cli_metrics) + allow(Time).to receive(:now).and_return(start_time, start_time + 0.125, start_time + 0.250) + + small_client = StorageCliClient.new( + directory_key: directory_key, + resource_type: resource_type, + root_dir: 'bommel', + min_size: 1024, + metrics_updater: metrics_updater + ) + allow(small_client).to receive(:additional_flags).and_return([]) + + small_client.cp_to_blobstore(source.path, 'some-key') + + expect(metrics_updater).to have_received(:report_storage_cli_metrics).with( + operation: 'put', exit_code: -4, duration_seconds: 0.125, blob_size: nil + ) + expect(logger_double).to have_received(:info).with('cp-skip', a_hash_including(destination_key: 'some-key', duration_seconds: 0.25)) + ensure + source.close! + end + + it 'emits exit_code=-3 metric and logs cp-error when File.open fails (missing source)' do + metrics_updater = instance_double(VCAP::CloudController::Metrics::PrometheusUpdater) + allow(metrics_updater).to receive(:report_storage_cli_metrics) + + client_with_metrics = StorageCliClient.new( + directory_key: directory_key, + resource_type: resource_type, + root_dir: 'bommel', + metrics_updater: metrics_updater + ) + allow(client_with_metrics).to receive(:additional_flags).and_return([]) + allow(File).to receive(:open).and_raise(Errno::ENOENT.new('no such file')) + + expect { client_with_metrics.cp_to_blobstore('/nonexistent/path', 'some-key') }.to raise_error(Errno::ENOENT) + expect(metrics_updater).to have_received(:report_storage_cli_metrics).with( + operation: 'put', exit_code: -3, duration_seconds: anything, blob_size: nil + ) + expect(logger_double).to have_received(:info).with('cp-error', a_hash_including(destination_key: 'some-key')) + end + + it 'lets Interrupt propagate when File.open is interrupted' do + source = Tempfile.new('src') + source.write('x' * 1025) + source.flush + + metrics_updater = instance_double(VCAP::CloudController::Metrics::PrometheusUpdater) + allow(metrics_updater).to receive(:report_storage_cli_metrics) + + client_with_metrics = StorageCliClient.new( + directory_key: directory_key, + resource_type: resource_type, + root_dir: 'bommel', + metrics_updater: metrics_updater + ) + allow(client_with_metrics).to receive(:additional_flags).and_return([]) + + allow(File).to receive(:open).and_raise(Interrupt) + + expect { client_with_metrics.cp_to_blobstore(source.path, 'some-key') }.to raise_error(Interrupt) + expect(metrics_updater).to have_received(:report_storage_cli_metrics).with( + operation: 'put', exit_code: -5, duration_seconds: anything, blob_size: nil + ) + ensure + source.close! + end + + it 'does not emit a duplicate signal metric when run_cli raises Interrupt' do + source = Tempfile.new('src') + source.write('x' * 1025) + source.flush + + metrics_updater = instance_double(VCAP::CloudController::Metrics::PrometheusUpdater) + allow(metrics_updater).to receive(:report_storage_cli_metrics) + + client_with_metrics = StorageCliClient.new( + directory_key: directory_key, + resource_type: resource_type, + root_dir: 'bommel', + metrics_updater: metrics_updater + ) + allow(client_with_metrics).to receive(:additional_flags).and_return([]) + allow(client_with_metrics).to receive(:run_cli).and_raise(Interrupt) + + expect { client_with_metrics.cp_to_blobstore(source.path, 'some-key') }.to raise_error(Interrupt) + expect(metrics_updater).not_to have_received(:report_storage_cli_metrics).with( + operation: 'put', exit_code: -6, duration_seconds: anything, blob_size: nil + ) + ensure + source.close! + end + + it 'emits exit_code=-7 when a fatal non-signal exception escapes run_cli' do + source = Tempfile.new('src') + source.write('x' * 1025) + source.flush + + metrics_updater = instance_double(VCAP::CloudController::Metrics::PrometheusUpdater) + allow(metrics_updater).to receive(:report_storage_cli_metrics) + + client_with_metrics = StorageCliClient.new( + directory_key: directory_key, + resource_type: resource_type, + root_dir: 'bommel', + metrics_updater: metrics_updater + ) + allow(client_with_metrics).to receive(:additional_flags).and_return([]) + allow(client_with_metrics).to receive(:run_cli).and_raise(NoMemoryError) + + expect { client_with_metrics.cp_to_blobstore(source.path, 'some-key') }.to raise_error(NoMemoryError) + expect(metrics_updater).to have_received(:report_storage_cli_metrics).with( + operation: 'put', exit_code: -7, duration_seconds: anything, blob_size: nil + ) + ensure + source.close! + end end end end diff --git a/spec/unit/lib/cloud_controller/metrics/prometheus_updater_spec.rb b/spec/unit/lib/cloud_controller/metrics/prometheus_updater_spec.rb index b69d38929ac..bb4260b9399 100644 --- a/spec/unit/lib/cloud_controller/metrics/prometheus_updater_spec.rb +++ b/spec/unit/lib/cloud_controller/metrics/prometheus_updater_spec.rb @@ -23,18 +23,31 @@ module VCAP::CloudController::Metrics end it_behaves_like 'metric registration based on execution context', VCAP::CloudController::ExecutionContext::API_PUMA_MAIN, - [PrometheusUpdater::METRICS, PrometheusUpdater::PUMA_METRICS, PrometheusUpdater::DB_CONNECTION_POOL_METRICS, PrometheusUpdater::DELAYED_JOB_METRICS, PrometheusUpdater::VITAL_METRICS] + [PrometheusUpdater::METRICS, PrometheusUpdater::PUMA_METRICS, PrometheusUpdater::DB_CONNECTION_POOL_METRICS, + PrometheusUpdater::DELAYED_JOB_METRICS, PrometheusUpdater::STORAGE_CLI_METRICS, PrometheusUpdater::VITAL_METRICS] it_behaves_like 'metric registration based on execution context', VCAP::CloudController::ExecutionContext::API_PUMA_WORKER, - [PrometheusUpdater::METRICS, PrometheusUpdater::PUMA_METRICS, PrometheusUpdater::DB_CONNECTION_POOL_METRICS, PrometheusUpdater::DELAYED_JOB_METRICS, PrometheusUpdater::VITAL_METRICS] + [PrometheusUpdater::METRICS, PrometheusUpdater::PUMA_METRICS, PrometheusUpdater::DB_CONNECTION_POOL_METRICS, + PrometheusUpdater::DELAYED_JOB_METRICS, PrometheusUpdater::STORAGE_CLI_METRICS, PrometheusUpdater::VITAL_METRICS] it_behaves_like 'metric registration based on execution context', VCAP::CloudController::ExecutionContext::CC_WORKER, - [PrometheusUpdater::DB_CONNECTION_POOL_METRICS, PrometheusUpdater::DELAYED_JOB_METRICS, PrometheusUpdater::VITAL_METRICS] + [PrometheusUpdater::DB_CONNECTION_POOL_METRICS, PrometheusUpdater::DELAYED_JOB_METRICS, PrometheusUpdater::STORAGE_CLI_METRICS, PrometheusUpdater::VITAL_METRICS] it_behaves_like 'metric registration based on execution context', VCAP::CloudController::ExecutionContext::CLOCK, [PrometheusUpdater::DB_CONNECTION_POOL_METRICS, PrometheusUpdater::VITAL_METRICS] it_behaves_like 'metric registration based on execution context', VCAP::CloudController::ExecutionContext::DEPLOYMENT_UPDATER, [PrometheusUpdater::DB_CONNECTION_POOL_METRICS, PrometheusUpdater::VITAL_METRICS] - it 'raises error when execution context is nil' do + it 'skips metric registration when execution context is nil and PROCESS_TYPE is unset' do allow(VCAP::CloudController::ExecutionContext).to receive(:from_process_type_env).and_return(nil) - expect { updater }.to raise_error('Could not register Prometheus metrics: Unexpected execution context: nil') + allow(ENV).to receive(:fetch).with('PROCESS_TYPE', nil).and_return(nil) + + expect { updater }.not_to raise_error + expect(prom_client.metrics).to be_empty + end + + it 'skips metric registration when execution context is nil even if PROCESS_TYPE is set' do + allow(VCAP::CloudController::ExecutionContext).to receive(:from_process_type_env).and_return(nil) + allow(ENV).to receive(:fetch).with('PROCESS_TYPE', nil).and_return('mystery') + + expect { updater }.not_to raise_error + expect(prom_client.metrics).to be_empty end context 'when execution context is set' do @@ -275,5 +288,68 @@ module VCAP::CloudController::Metrics expect(metric.get).to eq({ '5' => 0.0, '10' => 0.0, '30' => 0.0, '60' => 0.0, '300' => 0.0, '600' => 0.0, '890' => 0.0, 'sum' => 900.0, '+Inf' => 1.0 }) end end + + describe '#report_storage_cli_metrics' do + before do + allow(VCAP::CloudController::ExecutionContext).to receive(:from_process_type_env).and_return( + VCAP::CloudController::ExecutionContext::CC_WORKER + ) + end + + it 'increments the operations counter with operation and exit_code labels' do + updater.report_storage_cli_metrics(operation: 'get', exit_code: 0, duration_seconds: 0.1) + + metric = prom_client.get(:cc_storage_cli_operations_total) + expect(metric.get(labels: { operation: 'get', exit_code: '0' })).to eq(1.0) + end + + it 'observes duration with exit_code label' do + updater.report_storage_cli_metrics(operation: 'put', exit_code: 0, duration_seconds: 1.5) + + metric = prom_client.get(:cc_storage_cli_duration_seconds) + expect(metric.get(labels: { operation: 'put', exit_code: '0' })['sum']).to eq(1.5) + end + + it 'records blob_size when exit_code is 0' do + updater.report_storage_cli_metrics(operation: 'put', exit_code: 0, duration_seconds: 0.2, blob_size: 1_048_576) + + metric = prom_client.get(:cc_storage_cli_blob_size_bytes) + expect(metric.get(labels: { operation: 'put' })['sum']).to eq(1_048_576.0) + end + + it 'does not record blob_size when exit_code is non-zero' do + updater.report_storage_cli_metrics(operation: 'put', exit_code: 1, duration_seconds: 0.2, blob_size: 1_048_576) + + metric = prom_client.get(:cc_storage_cli_blob_size_bytes) + expect(metric.get(labels: { operation: 'put' })['sum']).to eq(0.0) + end + + it 'does not record blob_size when blob_size is nil' do + updater.report_storage_cli_metrics(operation: 'get', exit_code: 0, duration_seconds: 0.1, blob_size: nil) + + metric = prom_client.get(:cc_storage_cli_blob_size_bytes) + expect(metric.get(labels: { operation: 'get' })['sum']).to eq(0.0) + end + + it 'still updates registered storage-cli metrics when one metric is missing' do + allow(prom_client).to receive(:exist?).and_call_original + allow(prom_client).to receive(:exist?).with(:cc_storage_cli_blob_size_bytes).and_return(false) + + updater.report_storage_cli_metrics(operation: 'put', exit_code: 0, duration_seconds: 0.2, blob_size: 1_048_576) + + operations_metric = prom_client.get(:cc_storage_cli_operations_total) + duration_metric = prom_client.get(:cc_storage_cli_duration_seconds) + + expect(operations_metric.get(labels: { operation: 'put', exit_code: '0' })).to eq(1.0) + expect(duration_metric.get(labels: { operation: 'put', exit_code: '0' })['sum']).to eq(0.2) + end + + it 'is a no-op when storage cli metrics are not registered' do + allow(VCAP::CloudController::ExecutionContext).to receive(:from_process_type_env).and_return( + VCAP::CloudController::ExecutionContext::CLOCK + ) + expect { updater.report_storage_cli_metrics(operation: 'get', exit_code: 0, duration_seconds: 0.1) }.not_to raise_error + end + end end end diff --git a/spec/unit/lib/cloud_controller/packager/local_bits_packer_spec.rb b/spec/unit/lib/cloud_controller/packager/local_bits_packer_spec.rb index b8c421a83b8..0e855037b2a 100644 --- a/spec/unit/lib/cloud_controller/packager/local_bits_packer_spec.rb +++ b/spec/unit/lib/cloud_controller/packager/local_bits_packer_spec.rb @@ -368,6 +368,27 @@ module CloudController::Packager end end end + + it 'logs timing for each phase' do + logger = instance_double(Steno::Logger) + allow(Steno).to receive(:logger).and_return(logger) + allow(logger).to receive(:info) + allow(logger).to receive(:debug) + allow(VCAP::CloudController::FeatureFlag).to receive(:disabled?).with(:resource_matching).and_return(false) + global_app_bits_cache.instance_variable_set(:@logger, logger) + package_blobstore.instance_variable_set(:@logger, logger) + + packer.send_package_to_blobstore(blobstore_key, uploaded_files_path, cached_files_fingerprints) + + expect(logger).to have_received(:info).with('packer.unzip', hash_including(:duration_seconds)) + expect(logger).to have_received(:info).with('blobstore.cp_r.digest', hash_including(:duration_seconds, :count)) + expect(logger).to have_received(:info).with('blobstore.cp_r.exists', hash_including(:duration_seconds, :count)) + expect(logger).to have_received(:info).with('blobstore.cp_r.upload', hash_including(:duration_seconds, :count)) + expect(logger).to have_received(:info).with('packer.resource-cache-upload', hash_including(:duration_seconds)) + expect(logger).to have_received(:info).with('packer.resource-cache-download', hash_including(:duration_seconds, :count)) + expect(logger).to have_received(:info).with('packer.repackage', hash_including(:duration_seconds)) + expect(logger).to have_received(:info).with('packer.final-upload', hash_including(:duration_seconds, :blobstore_key)) + end end end end diff --git a/spec/unit/lib/cloud_controller/user_audit_info_spec.rb b/spec/unit/lib/cloud_controller/user_audit_info_spec.rb index 27b2cf625cb..19751786ee2 100644 --- a/spec/unit/lib/cloud_controller/user_audit_info_spec.rb +++ b/spec/unit/lib/cloud_controller/user_audit_info_spec.rb @@ -20,9 +20,14 @@ module VCAP::CloudController end describe '#hash_for_logs' do - it 'returns only the non-sensitive identity fields' do + it 'returns only the user_guid' do info = UserAuditInfo.new(user_email: 'e', user_name: 'n', user_guid: 'g') - expect(info.hash_for_logs).to eq(user_guid: 'g', user_email: 'e', user_name: 'n') + expect(info.hash_for_logs).to eq(user_guid: 'g') + end + + it 'includes user_guid key even when guid is nil' do + info = UserAuditInfo.new(user_email: 'e', user_name: 'n', user_guid: nil) + expect(info.hash_for_logs).to eq(user_guid: nil) end end diff --git a/spec/unit/lib/sequel/extensions/delayed_jobs_log_redaction_spec.rb b/spec/unit/lib/sequel/extensions/delayed_jobs_log_redaction_spec.rb index 04ca6346694..5bc969a6ca3 100644 --- a/spec/unit/lib/sequel/extensions/delayed_jobs_log_redaction_spec.rb +++ b/spec/unit/lib/sequel/extensions/delayed_jobs_log_redaction_spec.rb @@ -107,6 +107,52 @@ expect(logs.string).not_to include('[REDACTED]') end + it 'leaves last_error intact even when it contains !ruby content (e.g. job failed processing YAML input)' do + sql = %(UPDATE "delayed_jobs" SET "last_error" = '--- !ruby/object:Foo pw: s3cr3t', "attempts" = 2 WHERE "id" = 71) + db.log_connection_yield(sql, nil) {} + + expect(logs.string).to include('s3cr3t') + expect(logs.string).not_to include('[REDACTED]') + end + + it 'leaves last_error bound args intact even when they contain !ruby content' do + sql = 'UPDATE "delayed_jobs" SET "last_error" = $1 WHERE "id" = 71' + + db.log_connection_yield(sql, nil, ['--- !ruby/object:Foo pw: s3cr3t']) {} + + expect(logs.string).to include('s3cr3t') + expect(logs.string).not_to include('[REDACTED]') + end + + it 'redacts only the handler bound arg when UPDATE includes other !ruby-like args' do + sql = 'UPDATE "delayed_jobs" SET "handler" = $1, "last_error" = $2 WHERE "id" = 71' + + db.log_connection_yield(sql, nil, ['--- !ruby/object:Foo pw: s3cr3t', '--- !ruby/object:Bar debug detail']) {} + + expect(logs.string).to include('[REDACTED]') + expect(logs.string).to include('debug detail') + expect(logs.string).not_to include('s3cr3t') + end + + it 'redacts handler bound arg even when a value contains the word WHERE' do + # last_error may contain SQL snippets with WHERE; a lazy SET-clause regex would stop too early + sql = 'UPDATE "delayed_jobs" SET "handler" = $1, "last_error" = $2 WHERE "id" = 71' + + db.log_connection_yield(sql, nil, ['--- !ruby/object:Foo pw: s3cr3t', 'query failed WHERE x = 1']) {} + + expect(logs.string).to include('[REDACTED]') + expect(logs.string).to include('WHERE x = 1') + expect(logs.string).not_to include('s3cr3t') + end + + it 'does not redact column names that end in handler (e.g. request_handler)' do + sql = %(UPDATE "delayed_jobs" SET "request_handler" = 'some-value', "attempts" = 1 WHERE "id" = 5) + db.log_connection_yield(sql, nil) {} + + expect(logs.string).to include('some-value') + expect(logs.string).not_to include('[REDACTED]') + end + it 'leaves statements for other tables untouched' do sql = %(INSERT INTO "apps" ("name", "handler") VALUES ('my-app', 'not-a-secret')) db.log_connection_yield(sql, nil) {} @@ -115,6 +161,25 @@ expect(logs.string).not_to include('[REDACTED]') end + it 'does not redact tables whose names start with delayed_jobs (e.g. delayed_jobs_v2, delayed_jobs_staging)' do + handler = '--- !ruby/object:Foo systempassword: s3cr3t-value' + %w[delayed_jobs_v2 delayed_jobs_staging].each do |table| + sql = %(INSERT INTO "#{table}" ("handler") VALUES ('#{handler}')) + db.log_connection_yield(sql, nil) {} + end + + expect(logs.string).not_to include('[REDACTED]') + end + + it 'does not redact bound args for tables whose names start with delayed_jobs' do + sql = 'INSERT INTO "delayed_jobs_v2" ("handler") VALUES ($1)' + + db.log_connection_yield(sql, nil, ['--- !ruby/object:Foo systempassword: s3cr3t-value']) {} + + expect(logs.string).to include('s3cr3t-value') + expect(logs.string).not_to include('[REDACTED]') + end + it 'handles embedded doubled-quote escapes in the handler literal' do sql = %(INSERT INTO "delayed_jobs" ("handler") ) + %(VALUES ('--- !ruby/object:Foo note: it''s secret s3cr3t-value')) @@ -124,6 +189,14 @@ expect(logs.string).not_to include('s3cr3t-value') end + it 'redacts handler literals even when they have leading whitespace before the YAML tag' do + sql = %(INSERT INTO "delayed_jobs" ("handler") VALUES (' --- !ruby/object:Foo pw: s3cr3t-value')) + db.log_connection_yield(sql, nil) {} + + expect(logs.string).to include('[REDACTED]') + expect(logs.string).not_to include('s3cr3t-value') + end + # The base Sequel logger appends "; #{args.inspect}" when a statement is logged with # bound args (prepared statements). Redact there too, for any !ruby tag. ['!ruby/object:', '!ruby/struct:', '!ruby/hash:'].each do |tag| From 2ff1297852998a3a52f88fe8931c4eff7d7aac4f Mon Sep 17 00:00:00 2001 From: Wei Quan Date: Wed, 4 Nov 2026 13:48:42 +0100 Subject: [PATCH 2/7] feat(observability): add storage_cli.call.finish log per storage-cli invocation Log one structured entry per storage-cli subprocess call on cc.blobstore.storage_cli_client with operation, bucket, resource_type, operation-specific fields (key/source_path/destination_key etc.), duration_seconds, exit_code, and success. Linked to vcap-request-id so all storage-cli calls for a CF API request are traceable in Kibana, comparable to CCDB statement logs. Remove unrelated delayed_jobs_log_redaction changes These changes belong to PR #5513 (query log redaction), not this observability PR. --- lib/cloud_controller/blobstore/base_client.rb | 106 ++++++++++------ .../storage_cli/storage_cli_client.rb | 118 +++++++++++++++--- .../packager/local_bits_packer.rb | 2 + .../packager/shared_bits_packer.rb | 2 +- lib/cloud_controller/user_audit_info.rb | 1 + .../extensions/delayed_jobs_log_redaction.rb | 57 +++------ .../blobstore/local/local_client_spec.rb | 30 ++++- .../storage_cli/storage_cli_client_spec.rb | 59 +++++++-- .../packager/local_bits_packer_spec.rb | 9 +- .../delayed_jobs_log_redaction_spec.rb | 73 ----------- 10 files changed, 271 insertions(+), 186 deletions(-) diff --git a/lib/cloud_controller/blobstore/base_client.rb b/lib/cloud_controller/blobstore/base_client.rb index 40ac0f24484..bc567732ada 100644 --- a/lib/cloud_controller/blobstore/base_client.rb +++ b/lib/cloud_controller/blobstore/base_client.rb @@ -1,4 +1,3 @@ -require 'find' require 'cloud_controller/blobstore/blob' require 'cloud_controller/blobstore/blob_key_generator' @@ -6,13 +5,7 @@ module CloudController module Blobstore class BaseClient def cp_r_to_blobstore(source_dir) - digest_duration = 0 - exists_duration = 0 - upload_duration = 0 - digest_count = 0 - exists_count = 0 - upload_count = 0 - upload_attempts = 0 + counters = new_cp_r_counters traversal_completed = false begin @@ -31,38 +24,20 @@ def cp_r_to_blobstore(source_dir) next unless within_limits?(stat.size) next unless stat.mode.to_s(8)[3..5].to_i(8) >= 0o600 - t = Time.now.utc - begin - digest_count += 1 - sha1 = Digester.new.digest_path(path) - ensure - digest_duration += Time.now.utc - t - end + cp_r_digest_file(path, counters) + sha1 = counters[:last_sha1] - t = Time.now.utc - begin - exists_count += 1 - exists = exists?(sha1) - ensure - exists_duration += Time.now.utc - t - end + next unless sha1 + exists = cp_r_check_exists(sha1, counters) + next if exists.nil? # exists? raised, already logged next if exists - t = Time.now.utc - upload_attempts += 1 - begin - cp_to_blobstore(path, sha1) - upload_count += 1 - ensure - upload_duration += Time.now.utc - t - end + cp_r_upload_file(path, sha1, counters) end traversal_completed = true ensure - logger.info('blobstore.cp_r.digest', duration_seconds: digest_duration, count: digest_count, completed: traversal_completed) - logger.info('blobstore.cp_r.exists', duration_seconds: exists_duration, count: exists_count, completed: traversal_completed) - logger.info('blobstore.cp_r.upload', duration_seconds: upload_duration, count: upload_count, attempted: upload_attempts, completed: traversal_completed) + log_cp_r_phases(counters, traversal_completed) end end @@ -72,8 +47,65 @@ def cp_to_blobstore(_, _) private - def logger - @logger ||= Steno.logger('cc.blobstore') + def new_cp_r_counters + { digest_duration: 0, exists_duration: 0, upload_duration: 0, + digest_count: 0, exists_count: 0, upload_count: 0, + upload_attempts: 0, exists_errors: 0, last_sha1: nil } + end + + def cp_r_digest_file(path, counters) + t = Time.now.utc + counters[:digest_count] += 1 + counters[:last_sha1] = Digester.new.digest_path(path) + ensure + counters[:digest_duration] += Time.now.utc - t + end + + def cp_r_check_exists(sha1, counters) + t = Time.now.utc + counters[:exists_count] += 1 + exists?(sha1) + rescue StandardError => e + counters[:exists_errors] += 1 + logger.error('blobstore.cp_r.exists.error', sha1: sha1, error: e.message) + nil + ensure + counters[:exists_duration] += Time.now.utc - t + end + + def cp_r_upload_file(path, sha1, counters) + t = Time.now.utc + counters[:upload_attempts] += 1 + cp_to_blobstore(path, sha1) + counters[:upload_count] += 1 + ensure + counters[:upload_duration] += Time.now.utc - t + end + + def log_cp_r_phases(ctrs, completed) + logger.info('blobstore.cp_r.digest', + files_scanned: ctrs[:digest_count], + duration_seconds: ctrs[:digest_duration], + completed: completed) + ec = ctrs[:exists_count] + ea = ctrs[:upload_attempts] + ee = ctrs[:exists_errors] + logger.info('blobstore.cp_r.exists', + files_checked: ec, + duration_seconds: ctrs[:exists_duration], + avg_duration_seconds: ec > 0 ? ctrs[:exists_duration] / ec : 0, + cache_hits: ec - ea - ee, + cache_misses: ea, + cache_hit_rate: (ec - ee) > 0 ? (ec - ea - ee).to_f / (ec - ee) : 0, + process_spawns: ec, + error_count: ee, + completed: completed) + logger.info('blobstore.cp_r.upload', + files_to_upload: ea, + files_uploaded: ctrs[:upload_count], + files_failed: ea - ctrs[:upload_count], + duration_seconds: ctrs[:upload_duration], + completed: completed) end def partitioned_key(key) @@ -86,6 +118,10 @@ def partitioned_key(key) def within_limits?(size) size >= @min_size && (@max_size.nil? || size <= @max_size) end + + def logger + @logger ||= Steno.logger('cc.blobstore') + end end end end diff --git a/lib/cloud_controller/blobstore/storage_cli/storage_cli_client.rb b/lib/cloud_controller/blobstore/storage_cli/storage_cli_client.rb index e3b89137ac5..c3c16c4b95c 100644 --- a/lib/cloud_controller/blobstore/storage_cli/storage_cli_client.rb +++ b/lib/cloud_controller/blobstore/storage_cli/storage_cli_client.rb @@ -107,11 +107,11 @@ def cp_to_blobstore(source_path, destination_key) logger.info('cp-start', destination_key: destination_key, source_path: source_path, bucket: @directory_key) - state = { run_cli_called: false, run_cli_succeeded: false, skip_metric_emitted: false } + state = new_cp_state begin File.open(source_path) do |file| size = file.size - log_entry = cp_put_blob(source_path, destination_key, size, start, state) + log_entry = perform_put_or_skip(source_path, destination_key, size, start, state) end rescue Interrupt, SignalException log_entry = 'cp-error' @@ -119,24 +119,24 @@ def cp_to_blobstore(source_path, destination_key) raise rescue StandardError log_entry = 'cp-error' - safe_emit_metrics('put', -3, Time.now.utc - start, 'cp_to_blobstore') unless state[:run_cli_called] + safe_emit_metrics('put', -3, Time.now.utc - start, 'cp_to_blobstore') unless run_cli_called?(state) raise ensure safe_log_finish(log_entry, destination_key, start, size) end end - def cp_put_blob(source_path, destination_key, size, start, state) - if within_limits?(size) - state[:run_cli_called] = true - run_put_with_fatal_rescue(source_path, destination_key, size, start, state) - state[:run_cli_succeeded] = true - 'cp-finish' - else + def perform_put_or_skip(source_path, destination_key, size, start, state) + unless within_limits?(size) safe_emit_metrics('put', -4, Time.now.utc - start, 'cp_to_blobstore skip') - state[:skip_metric_emitted] = true - 'cp-skip' + mark_skip_metric_emitted!(state) + return 'cp-skip' end + + mark_run_cli_called!(state) + run_put_with_fatal_rescue(source_path, destination_key, size, start, state) + mark_run_cli_succeeded!(state) + 'cp-finish' end def run_put_with_fatal_rescue(source_path, destination_key, size, start, state) @@ -145,28 +145,68 @@ def run_put_with_fatal_rescue(source_path, destination_key, size, start, state) # run_cli already emitted a metric before re-raising; nothing to do here. raise rescue Exception => e # rubocop:disable Lint/RescueException + handle_fatal_put_exception(e, start, state) + raise + end + + def handle_fatal_put_exception(exception, start, state) # Catches fatal exceptions (NoMemoryError etc.) and signals (Interrupt, SignalException) # that StandardError does not cover. # # For signals: if Interrupt fired after run_cli returned, run_cli already emitted - # exit_code=0 — mark succeeded so the outer handler skips the -6 emit. + # exit_code=0, so mark succeeded to avoid emitting a duplicate signal metric. # For fatal exceptions: run_cli has not emitted, so emit -7 here. - if e.is_a?(Interrupt) || e.is_a?(SignalException) - state[:run_cli_succeeded] = true + if signal_exception?(exception) + mark_run_cli_succeeded!(state) else safe_emit_metrics('put', -7, Time.now.utc - start, 'fatal exception in run_cli') end - raise end def emit_signal_metric_if_needed(start, state) - return if state[:run_cli_succeeded] || state[:skip_metric_emitted] + return if run_cli_succeeded?(state) || skip_metric_emitted?(state) # -5: signal before CLI was invoked; -6: signal mid-execution after CLI was invoked. - signal_exit_code = state[:run_cli_called] ? -6 : -5 + signal_exit_code = run_cli_called?(state) ? -6 : -5 safe_emit_metrics('put', signal_exit_code, Time.now.utc - start, 'signal in cp_to_blobstore') end + def signal_exception?(exception) + exception.is_a?(Interrupt) || exception.is_a?(SignalException) + end + + def new_cp_state + { + run_cli_called: false, + run_cli_succeeded: false, + skip_metric_emitted: false + } + end + + def mark_run_cli_called!(state) + state[:run_cli_called] = true + end + + def mark_run_cli_succeeded!(state) + state[:run_cli_succeeded] = true + end + + def mark_skip_metric_emitted!(state) + state[:skip_metric_emitted] = true + end + + def run_cli_called?(state) + state[:run_cli_called] + end + + def run_cli_succeeded?(state) + state[:run_cli_succeeded] + end + + def skip_metric_emitted?(state) + state[:skip_metric_emitted] + end + def safe_emit_metrics(operation, exit_code, duration, context, blob_size: nil) emit_storage_cli_metrics(operation, exit_code, duration, blob_size: blob_size) rescue StandardError => e @@ -232,6 +272,8 @@ def additional_flags end def run_cli(command, *args, allow_exit_code_three: false, blob_size: nil) + log_fields = operation_log_fields(command, args, blob_size: blob_size) + logger.debug("running storage-cli: #{@cli_path} -s #{@storage_type} -c #{@config_file} #{additional_flags.join(' ')} #{command} #{args.join(' ')}") t = Time.now.utc @@ -243,6 +285,13 @@ def run_cli(command, *args, allow_exit_code_three: false, blob_size: nil) exit_code = resolve_exit_code(status) success = status.success? || (allow_exit_code_three && status.exitstatus == 3) + logger.info('storage_cli.call.finish', + log_fields.merge( + duration_seconds: duration, + exit_code: exit_code, + success: success + )) + unless success safe_emit_metrics(command, exit_code, duration, 'run_cli failure', blob_size: blob_size) raise "storage-cli #{command} failed with exit code #{exit_code.inspect}, output: '#{stdout}', error: '#{stderr}'" @@ -256,6 +305,39 @@ def run_cli(command, *args, allow_exit_code_three: false, blob_size: nil) [stdout, status] end + def operation_log_fields(command, args, blob_size: nil) + fields = { + operation: command, + bucket: @directory_key, + resource_type: @resource_type + } + + case command + when 'put' + fields[:source_path] = args[0] + fields[:destination_key] = args[1] + when 'get' + fields[:source_key] = args[0] + fields[:destination_path] = args[1] + when 'copy' + fields[:source_key] = args[0] + fields[:destination_key] = args[1] + when 'exists', 'delete', 'properties' + fields[:key] = args[0] + when 'list' + fields[:prefix] = args[0] + when 'delete-recursive' + fields[:path] = args[0] + when 'sign', 'sign-public', 'sign-internal' + fields[:key] = args[0] + fields[:verb] = args[1] + fields[:expires_in] = args[2] + end + + fields[:size] = blob_size if blob_size + fields + end + def capture_cli(command, args, start_time) Open3.capture3(@cli_path, '-s', @storage_type, '-c', @config_file, *additional_flags, command, *args) rescue StandardError => e diff --git a/lib/cloud_controller/packager/local_bits_packer.rb b/lib/cloud_controller/packager/local_bits_packer.rb index eae9a2fdce2..0532cb982e3 100644 --- a/lib/cloud_controller/packager/local_bits_packer.rb +++ b/lib/cloud_controller/packager/local_bits_packer.rb @@ -20,6 +20,7 @@ def send_package_to_blobstore(blobstore_key, uploaded_package_zip, cached_files_ Dir.mkdir(local_bits_packer_path) + pack_start = Time.now.utc begin complete_package_path = match_resources_and_validate_package(local_bits_packer_path, uploaded_package_zip, cached_files_fingerprints) @@ -35,6 +36,7 @@ def send_package_to_blobstore(blobstore_key, uploaded_package_zip, cached_files_ sha256: Digester.new(algorithm: OpenSSL::Digest::SHA256).digest_path(complete_package_path) } ensure + logger.info('packer.pack', duration_seconds: Time.now.utc - pack_start, blobstore_key: blobstore_key) FileUtils.remove_dir(local_bits_packer_path) end end diff --git a/lib/cloud_controller/packager/shared_bits_packer.rb b/lib/cloud_controller/packager/shared_bits_packer.rb index ede8a7febd9..1af296ce466 100644 --- a/lib/cloud_controller/packager/shared_bits_packer.rb +++ b/lib/cloud_controller/packager/shared_bits_packer.rb @@ -73,7 +73,7 @@ def append_matched_resources(app_packager, cached_files_fingerprints, root_path) download_count += 1 end ensure - logger.info('packer.resource-cache-download', duration_seconds: Time.now.utc - t, count: download_count, attempted: download_attempts) + logger.info('packer.resource-cache-download', duration_seconds: Time.now.utc - t, files_downloaded: download_count, files_attempted: download_attempts) end raise CloudController::Errors::ApiError.new_from_details('ResourceChecksumMismatch') if checksum_mismatch diff --git a/lib/cloud_controller/user_audit_info.rb b/lib/cloud_controller/user_audit_info.rb index 47537479123..db49560bc51 100644 --- a/lib/cloud_controller/user_audit_info.rb +++ b/lib/cloud_controller/user_audit_info.rb @@ -18,6 +18,7 @@ def self.from_context(context) ) end + # Non-sensitive identity fields for structured job logging. def hash_for_logs { user_guid: user_guid } end diff --git a/lib/sequel/extensions/delayed_jobs_log_redaction.rb b/lib/sequel/extensions/delayed_jobs_log_redaction.rb index 137a8d28c34..8fd87957616 100644 --- a/lib/sequel/extensions/delayed_jobs_log_redaction.rb +++ b/lib/sequel/extensions/delayed_jobs_log_redaction.rb @@ -4,65 +4,38 @@ module Sequel::DelayedJobsLogRedaction # Redact the serialized job payload (handler) from any logged SQL that writes the # delayed_jobs table. REDACTED = "'[REDACTED]'" - DELAYED_JOBS_TABLE = /(?:[`"]?\w+[`"]?\.)?[`"]?delayed_jobs[`"]?(?=\W|$)/i - HANDLER_COLUMN = /\b[`"]?handler[`"]?/i + DELAYED_JOBS_TABLE = /(?:[`"]?\w+[`"]?\.)?[`"]?delayed_jobs[`"]?/i + HANDLER_COLUMN = /[`"]?handler[`"]?/i def log_connection_yield(sql, conn, args=nil) - if @loggers.any? && delayed_jobs_write_sql?(sql) - # Compute redacted_indexes before mutating sql so the $N placeholders we scan for - # are from the original SQL, not the already-redacted literal form. - args = redact_args(sql, args) if args.is_a?(Array) + if @loggers.any? && sql.include?('delayed_jobs') sql = redact_delayed_jobs(sql) + # Sequel's base logger appends "; #{args.inspect}" to the logged line. If bound args + # carry the serialized handler, redact there too. + args = redact_args(args) if args.is_a?(Array) && args.any? { |a| sensitive_arg?(a) } end super end private - def delayed_jobs_write_sql?(sql) - /\b(?:INSERT INTO|UPDATE)\s+#{DELAYED_JOBS_TABLE}/io.match?(sql) - end - def redact_delayed_jobs(sql) + return sql unless /\b(?:INSERT INTO|UPDATE)\s+#{DELAYED_JOBS_TABLE}/io.match?(sql) + sql = sql.gsub(/(#{HANDLER_COLUMN}\s*=\s*)'(?:[^']|'')*'/io, "\\1#{REDACTED}") - # INSERT only: the handler is a positional value with no column-name context. - # Scoped to INSERT to avoid redacting last_error/cf_api_error on UPDATE statements, - # which may contain '--- !ruby' if a job failed while processing YAML input. - sql = sql.gsub(/'\s*--- !ruby(?:[^']|'')*'/i, REDACTED) if /\bINSERT\b/i.match?(sql) - sql + # INSERT: the handler is a Psych-serialized Ruby object graph, which always starts + # with the '--- !ruby' document marker regardless of the inner tag. + sql.gsub(/'--- !ruby(?:[^']|'')*'/i, REDACTED) end - def redact_args(sql, args) + def redact_args(args) return args unless args.is_a?(Array) - redacted_indexes = redacted_indexes(sql) - return args if redacted_indexes.empty? - - args.each_with_index.map { |a, index| redacted_indexes.include?(index) ? '[REDACTED]' : a } + args.map { |a| sensitive_arg?(a) ? '[REDACTED]' : a } end - def redacted_indexes(sql) - indexes = [] - - if (columns = sql[/\bINSERT INTO\s+#{DELAYED_JOBS_TABLE}\s*\((.*?)\)\s*VALUES/i, 1]) && - (values = sql[/\bVALUES\s*\((.*?)\)/i, 1]) - handler_index = columns.split(',').map(&:strip).index { |column| HANDLER_COLUMN.match?(column) } - # Sequel emits all-$N placeholders for bound INSERTs, so VALUES(...) contains no literal commas. - # Scan $N tokens explicitly rather than splitting on commas so a future literal value with a comma - # cannot shift the index arithmetic. - value_placeholders = values.scan(/\$(\d+)/).map { |m| m[0].to_i } - if handler_index && (n = value_placeholders[handler_index]) - indexes << (n - 1) - end - end - - # For UPDATE: scan each "column = $N" assignment directly in the SQL rather than - # extracting the SET clause (a lazy match would stop early if a value contains WHERE). - sql.scan(/#{HANDLER_COLUMN}\s*=\s*\$(\d+)/i) do |match| - indexes << (match[0].to_i - 1) - end - - indexes.uniq + def sensitive_arg?(value) + value.is_a?(String) && value.include?('!ruby') end end diff --git a/spec/unit/lib/cloud_controller/blobstore/local/local_client_spec.rb b/spec/unit/lib/cloud_controller/blobstore/local/local_client_spec.rb index 55715e3e645..a94d754ff11 100644 --- a/spec/unit/lib/cloud_controller/blobstore/local/local_client_spec.rb +++ b/spec/unit/lib/cloud_controller/blobstore/local/local_client_spec.rb @@ -112,9 +112,9 @@ module Blobstore client.cp_r_to_blobstore(base_path) end.to raise_error(Errno::EACCES) - expect(logger).to have_received(:info).with('blobstore.cp_r.digest', hash_including(count: 0, completed: false)) - expect(logger).to have_received(:info).with('blobstore.cp_r.exists', hash_including(count: 0, completed: false)) - expect(logger).to have_received(:info).with('blobstore.cp_r.upload', hash_including(count: 0, attempted: 0, completed: false)) + expect(logger).to have_received(:info).with('blobstore.cp_r.digest', hash_including(files_scanned: 0, completed: false)) + expect(logger).to have_received(:info).with('blobstore.cp_r.exists', hash_including(files_checked: 0, completed: false)) + expect(logger).to have_received(:info).with('blobstore.cp_r.upload', hash_including(files_uploaded: 0, files_to_upload: 0, completed: false)) end it 'skips broken symlinks without aborting traversal' do @@ -128,6 +128,28 @@ module Blobstore end.not_to raise_error end + it 'continues traversal and increments error_count when exists? raises' do + source_dir = File.join(base_path, 'source') + FileUtils.mkdir_p(source_dir) + File.write(File.join(source_dir, 'file1.txt'), 'x' * 100) + File.write(File.join(source_dir, 'file2.txt'), 'y' * 100) + + call_count = 0 + allow(client).to receive(:exists?) do + call_count += 1 + raise StandardError.new('exists failed') if call_count == 1 + + false + end + + expect do + client.cp_r_to_blobstore(source_dir) + end.not_to raise_error + + expect(logger).to have_received(:info).with('blobstore.cp_r.exists', + hash_including(files_checked: 2, error_count: 1, cache_hits: 0, cache_hit_rate: 0.0, completed: true)) + end + it 'counts a digest attempt even when digest_path raises' do source_dir = File.join(base_path, 'source') FileUtils.mkdir_p(source_dir) @@ -141,7 +163,7 @@ module Blobstore client.cp_r_to_blobstore(source_dir) end.to raise_error(StandardError, 'digest failed') - expect(logger).to have_received(:info).with('blobstore.cp_r.digest', hash_including(count: 1, completed: false)) + expect(logger).to have_received(:info).with('blobstore.cp_r.digest', hash_including(files_scanned: 1, completed: false)) end end diff --git a/spec/unit/lib/cloud_controller/blobstore/storage_cli/storage_cli_client_spec.rb b/spec/unit/lib/cloud_controller/blobstore/storage_cli/storage_cli_client_spec.rb index 3cf0ed8a930..b28c0c11bfe 100644 --- a/spec/unit/lib/cloud_controller/blobstore/storage_cli/storage_cli_client_spec.rb +++ b/spec/unit/lib/cloud_controller/blobstore/storage_cli/storage_cli_client_spec.rb @@ -497,10 +497,51 @@ def build_client(resource_type) end describe '#run_cli' do + let(:logger_double) { instance_double(Steno::Logger, info: nil, error: nil, debug: nil, warn: nil) } + before do + allow(Steno).to receive(:logger).and_return(logger_double) allow(client).to receive(:additional_flags).and_return([]) end + it 'logs structured finish fields for successful calls' do + status = instance_double(Process::Status, success?: true, exitstatus: 0) + allow(Open3).to receive(:capture3).and_return(['ok', '', status]) + + client.send(:run_cli, 'put', 'src-path', 'dest-key', blob_size: 1024) + + expect(logger_double).to have_received(:info).with('storage_cli.call.finish', hash_including( + operation: 'put', + bucket: directory_key, + resource_type: resource_type, + source_path: 'src-path', + destination_key: 'dest-key', + size: 1024, + exit_code: 0, + success: true, + duration_seconds: a_kind_of(Float) + )) + end + + it 'logs finish fields for failed calls' do + status = instance_double(Process::Status, success?: false, exitstatus: 1) + allow(Open3).to receive(:capture3).and_return(['', 'error message', status]) + + expect do + client.send(:run_cli, 'exists', 'arg1') + end.to raise_error(RuntimeError, /storage-cli exists failed with exit code 1/) + + expect(logger_double).to have_received(:info).with('storage_cli.call.finish', hash_including( + operation: 'exists', + bucket: directory_key, + resource_type: resource_type, + key: 'arg1', + exit_code: 1, + success: false, + duration_seconds: a_kind_of(Float) + )) + end + it 'returns output and status on success' do status = instance_double(Process::Status, success?: true, exitstatus: 0) allow(Open3).to receive(:capture3).and_return(['ok', '', status]) @@ -535,7 +576,7 @@ def build_client(resource_type) end it 'reports 128+signal when the storage-cli process is terminated by a signal' do - metrics_updater = instance_double(VCAP::CloudController::Metrics::PrometheusUpdater) + metrics_updater = double('metrics_updater') allow(metrics_updater).to receive(:report_storage_cli_metrics) signal_client = StorageCliClient.new( directory_key: directory_key, @@ -555,7 +596,7 @@ def build_client(resource_type) end it 'reports exit_code=-1 when Open3 raises (spawn failure)' do - metrics_updater = instance_double(VCAP::CloudController::Metrics::PrometheusUpdater) + metrics_updater = double('metrics_updater') allow(metrics_updater).to receive(:report_storage_cli_metrics) spawning_client = StorageCliClient.new( directory_key: directory_key, @@ -573,7 +614,7 @@ def build_client(resource_type) end it 'lets Interrupt propagate from Open3.capture3' do - metrics_updater = instance_double(VCAP::CloudController::Metrics::PrometheusUpdater) + metrics_updater = double('metrics_updater') allow(metrics_updater).to receive(:report_storage_cli_metrics) spawning_client = StorageCliClient.new( directory_key: directory_key, @@ -589,7 +630,7 @@ def build_client(resource_type) end context 'metrics' do - let(:metrics_updater) { instance_double(VCAP::CloudController::Metrics::PrometheusUpdater) } + let(:metrics_updater) { double('metrics_updater') } let(:client_with_metrics) do StorageCliClient.new( directory_key: directory_key, @@ -721,7 +762,7 @@ def build_client(resource_type) start_time = Time.utc(2026, 10, 16, 12, 0, 0) - metrics_updater = instance_double(VCAP::CloudController::Metrics::PrometheusUpdater) + metrics_updater = double('metrics_updater') allow(metrics_updater).to receive(:report_storage_cli_metrics) allow(Time).to receive(:now).and_return(start_time, start_time + 0.125, start_time + 0.250) @@ -745,7 +786,7 @@ def build_client(resource_type) end it 'emits exit_code=-3 metric and logs cp-error when File.open fails (missing source)' do - metrics_updater = instance_double(VCAP::CloudController::Metrics::PrometheusUpdater) + metrics_updater = double('metrics_updater') allow(metrics_updater).to receive(:report_storage_cli_metrics) client_with_metrics = StorageCliClient.new( @@ -769,7 +810,7 @@ def build_client(resource_type) source.write('x' * 1025) source.flush - metrics_updater = instance_double(VCAP::CloudController::Metrics::PrometheusUpdater) + metrics_updater = double('metrics_updater') allow(metrics_updater).to receive(:report_storage_cli_metrics) client_with_metrics = StorageCliClient.new( @@ -795,7 +836,7 @@ def build_client(resource_type) source.write('x' * 1025) source.flush - metrics_updater = instance_double(VCAP::CloudController::Metrics::PrometheusUpdater) + metrics_updater = double('metrics_updater') allow(metrics_updater).to receive(:report_storage_cli_metrics) client_with_metrics = StorageCliClient.new( @@ -820,7 +861,7 @@ def build_client(resource_type) source.write('x' * 1025) source.flush - metrics_updater = instance_double(VCAP::CloudController::Metrics::PrometheusUpdater) + metrics_updater = double('metrics_updater') allow(metrics_updater).to receive(:report_storage_cli_metrics) client_with_metrics = StorageCliClient.new( diff --git a/spec/unit/lib/cloud_controller/packager/local_bits_packer_spec.rb b/spec/unit/lib/cloud_controller/packager/local_bits_packer_spec.rb index 0e855037b2a..d0a1be7a9f4 100644 --- a/spec/unit/lib/cloud_controller/packager/local_bits_packer_spec.rb +++ b/spec/unit/lib/cloud_controller/packager/local_bits_packer_spec.rb @@ -381,13 +381,14 @@ module CloudController::Packager packer.send_package_to_blobstore(blobstore_key, uploaded_files_path, cached_files_fingerprints) expect(logger).to have_received(:info).with('packer.unzip', hash_including(:duration_seconds)) - expect(logger).to have_received(:info).with('blobstore.cp_r.digest', hash_including(:duration_seconds, :count)) - expect(logger).to have_received(:info).with('blobstore.cp_r.exists', hash_including(:duration_seconds, :count)) - expect(logger).to have_received(:info).with('blobstore.cp_r.upload', hash_including(:duration_seconds, :count)) + expect(logger).to have_received(:info).with('blobstore.cp_r.digest', hash_including(:duration_seconds, :files_scanned)) + expect(logger).to have_received(:info).with('blobstore.cp_r.exists', hash_including(:duration_seconds, :files_checked)) + expect(logger).to have_received(:info).with('blobstore.cp_r.upload', hash_including(:duration_seconds, :files_uploaded)) expect(logger).to have_received(:info).with('packer.resource-cache-upload', hash_including(:duration_seconds)) - expect(logger).to have_received(:info).with('packer.resource-cache-download', hash_including(:duration_seconds, :count)) + expect(logger).to have_received(:info).with('packer.resource-cache-download', hash_including(:duration_seconds, :files_downloaded, :files_attempted)) expect(logger).to have_received(:info).with('packer.repackage', hash_including(:duration_seconds)) expect(logger).to have_received(:info).with('packer.final-upload', hash_including(:duration_seconds, :blobstore_key)) + expect(logger).to have_received(:info).with('packer.pack', hash_including(:duration_seconds, :blobstore_key)) end end end diff --git a/spec/unit/lib/sequel/extensions/delayed_jobs_log_redaction_spec.rb b/spec/unit/lib/sequel/extensions/delayed_jobs_log_redaction_spec.rb index 5bc969a6ca3..04ca6346694 100644 --- a/spec/unit/lib/sequel/extensions/delayed_jobs_log_redaction_spec.rb +++ b/spec/unit/lib/sequel/extensions/delayed_jobs_log_redaction_spec.rb @@ -107,52 +107,6 @@ expect(logs.string).not_to include('[REDACTED]') end - it 'leaves last_error intact even when it contains !ruby content (e.g. job failed processing YAML input)' do - sql = %(UPDATE "delayed_jobs" SET "last_error" = '--- !ruby/object:Foo pw: s3cr3t', "attempts" = 2 WHERE "id" = 71) - db.log_connection_yield(sql, nil) {} - - expect(logs.string).to include('s3cr3t') - expect(logs.string).not_to include('[REDACTED]') - end - - it 'leaves last_error bound args intact even when they contain !ruby content' do - sql = 'UPDATE "delayed_jobs" SET "last_error" = $1 WHERE "id" = 71' - - db.log_connection_yield(sql, nil, ['--- !ruby/object:Foo pw: s3cr3t']) {} - - expect(logs.string).to include('s3cr3t') - expect(logs.string).not_to include('[REDACTED]') - end - - it 'redacts only the handler bound arg when UPDATE includes other !ruby-like args' do - sql = 'UPDATE "delayed_jobs" SET "handler" = $1, "last_error" = $2 WHERE "id" = 71' - - db.log_connection_yield(sql, nil, ['--- !ruby/object:Foo pw: s3cr3t', '--- !ruby/object:Bar debug detail']) {} - - expect(logs.string).to include('[REDACTED]') - expect(logs.string).to include('debug detail') - expect(logs.string).not_to include('s3cr3t') - end - - it 'redacts handler bound arg even when a value contains the word WHERE' do - # last_error may contain SQL snippets with WHERE; a lazy SET-clause regex would stop too early - sql = 'UPDATE "delayed_jobs" SET "handler" = $1, "last_error" = $2 WHERE "id" = 71' - - db.log_connection_yield(sql, nil, ['--- !ruby/object:Foo pw: s3cr3t', 'query failed WHERE x = 1']) {} - - expect(logs.string).to include('[REDACTED]') - expect(logs.string).to include('WHERE x = 1') - expect(logs.string).not_to include('s3cr3t') - end - - it 'does not redact column names that end in handler (e.g. request_handler)' do - sql = %(UPDATE "delayed_jobs" SET "request_handler" = 'some-value', "attempts" = 1 WHERE "id" = 5) - db.log_connection_yield(sql, nil) {} - - expect(logs.string).to include('some-value') - expect(logs.string).not_to include('[REDACTED]') - end - it 'leaves statements for other tables untouched' do sql = %(INSERT INTO "apps" ("name", "handler") VALUES ('my-app', 'not-a-secret')) db.log_connection_yield(sql, nil) {} @@ -161,25 +115,6 @@ expect(logs.string).not_to include('[REDACTED]') end - it 'does not redact tables whose names start with delayed_jobs (e.g. delayed_jobs_v2, delayed_jobs_staging)' do - handler = '--- !ruby/object:Foo systempassword: s3cr3t-value' - %w[delayed_jobs_v2 delayed_jobs_staging].each do |table| - sql = %(INSERT INTO "#{table}" ("handler") VALUES ('#{handler}')) - db.log_connection_yield(sql, nil) {} - end - - expect(logs.string).not_to include('[REDACTED]') - end - - it 'does not redact bound args for tables whose names start with delayed_jobs' do - sql = 'INSERT INTO "delayed_jobs_v2" ("handler") VALUES ($1)' - - db.log_connection_yield(sql, nil, ['--- !ruby/object:Foo systempassword: s3cr3t-value']) {} - - expect(logs.string).to include('s3cr3t-value') - expect(logs.string).not_to include('[REDACTED]') - end - it 'handles embedded doubled-quote escapes in the handler literal' do sql = %(INSERT INTO "delayed_jobs" ("handler") ) + %(VALUES ('--- !ruby/object:Foo note: it''s secret s3cr3t-value')) @@ -189,14 +124,6 @@ expect(logs.string).not_to include('s3cr3t-value') end - it 'redacts handler literals even when they have leading whitespace before the YAML tag' do - sql = %(INSERT INTO "delayed_jobs" ("handler") VALUES (' --- !ruby/object:Foo pw: s3cr3t-value')) - db.log_connection_yield(sql, nil) {} - - expect(logs.string).to include('[REDACTED]') - expect(logs.string).not_to include('s3cr3t-value') - end - # The base Sequel logger appends "; #{args.inspect}" when a statement is logged with # bound args (prepared statements). Redact there too, for any !ruby tag. ['!ruby/object:', '!ruby/struct:', '!ruby/hash:'].each do |tag| From b8427c3ee76c1d1c54cb467805f77a3e89b86db1 Mon Sep 17 00:00:00 2001 From: Wei Quan Date: Fri, 6 Nov 2026 10:30:45 +0100 Subject: [PATCH 3/7] Improve storage_cli log message readability - Add operation and key args to storage_cli.call.finish message for quick scanning - Use labeled args (src=, dest=, key=, verb=, expires_in=) for clarity - Use File.basename to keep message concise without losing context - Log spawn errors with storage_cli.call.error including duration and error detail - Fix symbol key serialization bug in operation_log_fields (was logging :operation instead of operation) Revert user_audit_info changes unrelated to this PR --- .../storage_cli/storage_cli_client.rb | 78 ++++++++++++++----- lib/cloud_controller/user_audit_info.rb | 2 +- .../storage_cli/storage_cli_client_spec.rb | 72 ++++++++++++----- .../cloud_controller/user_audit_info_spec.rb | 9 +-- 4 files changed, 112 insertions(+), 49 deletions(-) diff --git a/lib/cloud_controller/blobstore/storage_cli/storage_cli_client.rb b/lib/cloud_controller/blobstore/storage_cli/storage_cli_client.rb index c3c16c4b95c..4fb08670e36 100644 --- a/lib/cloud_controller/blobstore/storage_cli/storage_cli_client.rb +++ b/lib/cloud_controller/blobstore/storage_cli/storage_cli_client.rb @@ -285,11 +285,11 @@ def run_cli(command, *args, allow_exit_code_three: false, blob_size: nil) exit_code = resolve_exit_code(status) success = status.success? || (allow_exit_code_three && status.exitstatus == 3) - logger.info('storage_cli.call.finish', + logger.info("storage_cli.call.finish #{command}#{log_message_arg_suffix(command, args)}", log_fields.merge( - duration_seconds: duration, - exit_code: exit_code, - success: success + 'duration_seconds' => duration, + 'exit_code' => exit_code, + 'success' => success )) unless success @@ -307,34 +307,34 @@ def run_cli(command, *args, allow_exit_code_three: false, blob_size: nil) def operation_log_fields(command, args, blob_size: nil) fields = { - operation: command, - bucket: @directory_key, - resource_type: @resource_type + 'operation' => command, + 'bucket' => @directory_key, + 'resource_type' => @resource_type } case command when 'put' - fields[:source_path] = args[0] - fields[:destination_key] = args[1] + fields['source_path'] = args[0] + fields['destination_key'] = args[1] when 'get' - fields[:source_key] = args[0] - fields[:destination_path] = args[1] + fields['source_key'] = args[0] + fields['destination_path'] = args[1] when 'copy' - fields[:source_key] = args[0] - fields[:destination_key] = args[1] + fields['source_key'] = args[0] + fields['destination_key'] = args[1] when 'exists', 'delete', 'properties' - fields[:key] = args[0] + fields['key'] = args[0] when 'list' - fields[:prefix] = args[0] + fields['prefix'] = args[0] when 'delete-recursive' - fields[:path] = args[0] + fields['path'] = args[0] when 'sign', 'sign-public', 'sign-internal' - fields[:key] = args[0] - fields[:verb] = args[1] - fields[:expires_in] = args[2] + fields['key'] = args[0] + fields['verb'] = args[1] + fields['expires_in'] = args[2] end - fields[:size] = blob_size if blob_size + fields['size'] = blob_size if blob_size fields end @@ -342,10 +342,46 @@ def capture_cli(command, args, start_time) Open3.capture3(@cli_path, '-s', @storage_type, '-c', @config_file, *additional_flags, command, *args) rescue StandardError => e # exit_code=-1 is a sentinel for spawn failures (binary missing, permission denied). - safe_emit_metrics(command, -1, Time.now.utc - start_time, 'spawn error') + duration = Time.now.utc - start_time + logger.error("storage_cli.call.error #{command}#{log_message_arg_suffix(command, args)}", + 'operation' => command, + 'bucket' => @directory_key, + 'resource_type' => @resource_type, + 'duration_seconds' => duration, + 'error' => e.inspect) + safe_emit_metrics(command, -1, duration, 'spawn error') raise BlobstoreError.new(e.inspect) end + def log_message_arg_suffix(command, args) + printable_args = + case command + when 'put', 'copy', 'get' + ["src=#{summarize_log_arg(args[0])}", "dest=#{summarize_log_arg(args[1])}"] + when 'sign', 'sign-public', 'sign-internal' + [ + "key=#{summarize_log_arg(args[0])}", + "verb=#{args[1]}", + "expires_in=#{args[2]}" + ] + when 'exists', 'delete', 'properties' + ["key=#{summarize_log_arg(args[0])}"] + when 'list' + ["prefix=#{summarize_log_arg(args[0])}"] + when 'delete-recursive' + ["path=#{summarize_log_arg(args[0])}"] + else + [] + end + + printable_args = printable_args.compact.map(&:to_s).reject(&:empty?) + printable_args.empty? ? '' : " #{printable_args.join(' ')}" + end + + def summarize_log_arg(arg) + File.basename(arg.to_s) + end + def resolve_exit_code(status) if status.exitstatus status.exitstatus diff --git a/lib/cloud_controller/user_audit_info.rb b/lib/cloud_controller/user_audit_info.rb index db49560bc51..d3909bf8539 100644 --- a/lib/cloud_controller/user_audit_info.rb +++ b/lib/cloud_controller/user_audit_info.rb @@ -20,7 +20,7 @@ def self.from_context(context) # Non-sensitive identity fields for structured job logging. def hash_for_logs - { user_guid: user_guid } + { user_guid: user_guid, user_email: user_email, user_name: user_name }.compact end end end diff --git a/spec/unit/lib/cloud_controller/blobstore/storage_cli/storage_cli_client_spec.rb b/spec/unit/lib/cloud_controller/blobstore/storage_cli/storage_cli_client_spec.rb index b28c0c11bfe..3927a63a0cb 100644 --- a/spec/unit/lib/cloud_controller/blobstore/storage_cli/storage_cli_client_spec.rb +++ b/spec/unit/lib/cloud_controller/blobstore/storage_cli/storage_cli_client_spec.rb @@ -510,17 +510,17 @@ def build_client(resource_type) client.send(:run_cli, 'put', 'src-path', 'dest-key', blob_size: 1024) - expect(logger_double).to have_received(:info).with('storage_cli.call.finish', hash_including( - operation: 'put', - bucket: directory_key, - resource_type: resource_type, - source_path: 'src-path', - destination_key: 'dest-key', - size: 1024, - exit_code: 0, - success: true, - duration_seconds: a_kind_of(Float) - )) + expect(logger_double).to have_received(:info).with('storage_cli.call.finish put src=src-path dest=dest-key', hash_including( + 'operation' => 'put', + 'bucket' => directory_key, + 'resource_type' => resource_type, + 'source_path' => 'src-path', + 'destination_key' => 'dest-key', + 'size' => 1024, + 'exit_code' => 0, + 'success' => true, + 'duration_seconds' => a_kind_of(Float) + )) end it 'logs finish fields for failed calls' do @@ -531,15 +531,40 @@ def build_client(resource_type) client.send(:run_cli, 'exists', 'arg1') end.to raise_error(RuntimeError, /storage-cli exists failed with exit code 1/) - expect(logger_double).to have_received(:info).with('storage_cli.call.finish', hash_including( - operation: 'exists', - bucket: directory_key, - resource_type: resource_type, - key: 'arg1', - exit_code: 1, - success: false, - duration_seconds: a_kind_of(Float) - )) + expect(logger_double).to have_received(:info).with('storage_cli.call.finish exists key=arg1', hash_including( + 'operation' => 'exists', + 'bucket' => directory_key, + 'resource_type' => resource_type, + 'key' => 'arg1', + 'exit_code' => 1, + 'success' => false, + 'duration_seconds' => a_kind_of(Float) + )) + end + + it 'uses basename of key arg in message text with key= label but keeps full structured key' do + status = instance_double(Process::Status, success?: true, exitstatus: 0) + allow(Open3).to receive(:capture3).and_return(['ok', '', status]) + + long_key = 'app_bits_cache/97/d0/97d004b6ef4a8c8f5e3b6a0f4c1d2e3f7a8b9c00112233445566778899aabbcc' + client.send(:run_cli, 'exists', long_key) + + expect(logger_double).to have_received(:info).with( + 'storage_cli.call.finish exists key=97d004b6ef4a8c8f5e3b6a0f4c1d2e3f7a8b9c00112233445566778899aabbcc', + hash_including('key' => long_key, 'success' => true) + ) + end + + it 'labels sign args in message text' do + status = instance_double(Process::Status, success?: true, exitstatus: 0) + allow(Open3).to receive(:capture3).and_return(['ok', '', status]) + + client.send(:run_cli, 'sign', 'abc123def456', 'get', '3600s') + + expect(logger_double).to have_received(:info).with( + 'storage_cli.call.finish sign key=abc123def456 verb=get expires_in=3600s', + hash_including('key' => 'abc123def456', 'verb' => 'get', 'expires_in' => '3600s', 'success' => true) + ) end it 'returns output and status on success' do @@ -611,6 +636,13 @@ def build_client(resource_type) expect(metrics_updater).to have_received(:report_storage_cli_metrics).with( operation: 'get', exit_code: -1, duration_seconds: a_kind_of(Float), blob_size: nil ) + expect(logger_double).to have_received(:error).with('storage_cli.call.error get src=some-key dest=', hash_including( + 'operation' => 'get', + 'bucket' => directory_key, + 'resource_type' => resource_type, + 'duration_seconds' => a_kind_of(Float), + 'error' => a_string_matching(/Errno::ENOENT/) + )) end it 'lets Interrupt propagate from Open3.capture3' do diff --git a/spec/unit/lib/cloud_controller/user_audit_info_spec.rb b/spec/unit/lib/cloud_controller/user_audit_info_spec.rb index 19751786ee2..27b2cf625cb 100644 --- a/spec/unit/lib/cloud_controller/user_audit_info_spec.rb +++ b/spec/unit/lib/cloud_controller/user_audit_info_spec.rb @@ -20,14 +20,9 @@ module VCAP::CloudController end describe '#hash_for_logs' do - it 'returns only the user_guid' do + it 'returns only the non-sensitive identity fields' do info = UserAuditInfo.new(user_email: 'e', user_name: 'n', user_guid: 'g') - expect(info.hash_for_logs).to eq(user_guid: 'g') - end - - it 'includes user_guid key even when guid is nil' do - info = UserAuditInfo.new(user_email: 'e', user_name: 'n', user_guid: nil) - expect(info.hash_for_logs).to eq(user_guid: nil) + expect(info.hash_for_logs).to eq(user_guid: 'g', user_email: 'e', user_name: 'n') end end From f479098cef166af4d014c102be6c7794c2f74c89 Mon Sep 17 00:00:00 2001 From: Wei Quan Date: Mon, 9 Nov 2026 14:21:08 +0100 Subject: [PATCH 4/7] Centralize storage-cli metrics in run_cli, add sentinel exit codes --- .../storage_cli/storage_cli_client.rb | 277 +++++++----------- .../metrics/prometheus_updater.rb | 6 +- .../storage_cli/storage_cli_client_spec.rb | 144 ++++++++- 3 files changed, 231 insertions(+), 196 deletions(-) diff --git a/lib/cloud_controller/blobstore/storage_cli/storage_cli_client.rb b/lib/cloud_controller/blobstore/storage_cli/storage_cli_client.rb index 4fb08670e36..f14bacab702 100644 --- a/lib/cloud_controller/blobstore/storage_cli/storage_cli_client.rb +++ b/lib/cloud_controller/blobstore/storage_cli/storage_cli_client.rb @@ -104,124 +104,56 @@ def cp_to_blobstore(source_path, destination_key) start = Time.now.utc log_entry = 'cp-skip' size = nil + metric_emitted = false logger.info('cp-start', destination_key: destination_key, source_path: source_path, bucket: @directory_key) - state = new_cp_state begin File.open(source_path) do |file| size = file.size - log_entry = perform_put_or_skip(source_path, destination_key, size, start, state) + if within_limits?(size) + dest_key = partitioned_key(destination_key) + begin + run_cli('put', source_path, dest_key, blob_size: size) + ensure + metric_emitted = true + end + log_entry = 'cp-finish' + else + safe_emit_metrics('put', -4, Time.now.utc - start, 'cp_to_blobstore skip') + metric_emitted = true + log_entry = 'cp-skip' + end end rescue Interrupt, SignalException log_entry = 'cp-error' - emit_signal_metric_if_needed(start, state) + safe_emit_metrics('put', -5, Time.now.utc - start, 'signal before CLI') unless metric_emitted raise rescue StandardError log_entry = 'cp-error' - safe_emit_metrics('put', -3, Time.now.utc - start, 'cp_to_blobstore') unless run_cli_called?(state) + safe_emit_metrics('put', -3, Time.now.utc - start, 'cp_to_blobstore') unless metric_emitted + raise + rescue Exception # rubocop:disable Lint/RescueException + log_entry = 'cp-error' raise ensure - safe_log_finish(log_entry, destination_key, start, size) - end - end - - def perform_put_or_skip(source_path, destination_key, size, start, state) - unless within_limits?(size) - safe_emit_metrics('put', -4, Time.now.utc - start, 'cp_to_blobstore skip') - mark_skip_metric_emitted!(state) - return 'cp-skip' - end - - mark_run_cli_called!(state) - run_put_with_fatal_rescue(source_path, destination_key, size, start, state) - mark_run_cli_succeeded!(state) - 'cp-finish' - end - - def run_put_with_fatal_rescue(source_path, destination_key, size, start, state) - run_cli('put', source_path, partitioned_key(destination_key), blob_size: size) - rescue StandardError - # run_cli already emitted a metric before re-raising; nothing to do here. - raise - rescue Exception => e # rubocop:disable Lint/RescueException - handle_fatal_put_exception(e, start, state) - raise - end - - def handle_fatal_put_exception(exception, start, state) - # Catches fatal exceptions (NoMemoryError etc.) and signals (Interrupt, SignalException) - # that StandardError does not cover. - # - # For signals: if Interrupt fired after run_cli returned, run_cli already emitted - # exit_code=0, so mark succeeded to avoid emitting a duplicate signal metric. - # For fatal exceptions: run_cli has not emitted, so emit -7 here. - if signal_exception?(exception) - mark_run_cli_succeeded!(state) - else - safe_emit_metrics('put', -7, Time.now.utc - start, 'fatal exception in run_cli') + begin + logger.info(log_entry, + destination_key: destination_key, + duration_seconds: Time.now.utc - start, + size: size) + rescue StandardError => e + logger.warn("cp_to_blobstore ensure log failed: #{e.inspect}") + end end end - def emit_signal_metric_if_needed(start, state) - return if run_cli_succeeded?(state) || skip_metric_emitted?(state) - - # -5: signal before CLI was invoked; -6: signal mid-execution after CLI was invoked. - signal_exit_code = run_cli_called?(state) ? -6 : -5 - safe_emit_metrics('put', signal_exit_code, Time.now.utc - start, 'signal in cp_to_blobstore') - end - - def signal_exception?(exception) - exception.is_a?(Interrupt) || exception.is_a?(SignalException) - end - - def new_cp_state - { - run_cli_called: false, - run_cli_succeeded: false, - skip_metric_emitted: false - } - end - - def mark_run_cli_called!(state) - state[:run_cli_called] = true - end - - def mark_run_cli_succeeded!(state) - state[:run_cli_succeeded] = true - end - - def mark_skip_metric_emitted!(state) - state[:skip_metric_emitted] = true - end - - def run_cli_called?(state) - state[:run_cli_called] - end - - def run_cli_succeeded?(state) - state[:run_cli_succeeded] - end - - def skip_metric_emitted?(state) - state[:skip_metric_emitted] - end - def safe_emit_metrics(operation, exit_code, duration, context, blob_size: nil) emit_storage_cli_metrics(operation, exit_code, duration, blob_size: blob_size) rescue StandardError => e logger.warn("emit_storage_cli_metrics failed in #{context}: #{e.inspect}") end - def safe_log_finish(log_entry, destination_key, start, size) - logger.info(log_entry, - destination_key: destination_key, - duration_seconds: Time.now.utc - start, - size: size) - rescue StandardError => e - logger.warn("cp_to_blobstore ensure log failed: #{e.inspect}") - end - def cp_file_between_keys(source_key, destination_key) run_cli('copy', partitioned_key(source_key), partitioned_key(destination_key)) end @@ -272,116 +204,96 @@ def additional_flags end def run_cli(command, *args, allow_exit_code_three: false, blob_size: nil) - log_fields = operation_log_fields(command, args, blob_size: blob_size) - - logger.debug("running storage-cli: #{@cli_path} -s #{@storage_type} -c #{@config_file} #{additional_flags.join(' ')} #{command} #{args.join(' ')}") - t = Time.now.utc - stdout, stderr, status = capture_cli(command, args, t) - duration = Time.now.utc - t + emitted = false + capture3_called = false + begin + flags = additional_flags + logger.debug("running storage-cli: #{@cli_path} -s #{@storage_type} -c #{@config_file} #{flags.join(' ')} #{command} #{args.join(' ')}") + capture3_called = true + stdout, stderr, status = Open3.capture3(@cli_path, '-s', @storage_type, '-c', @config_file, *flags, command, *args) + rescue StandardError => e + duration = Time.now.utc - t + # -1: spawn failure (binary missing/permission); -3: setup error before capture3 (e.g. config load) + pre_spawn_code = capture3_called ? -1 : -3 + safe_emit_metrics(command, pre_spawn_code, duration, 'spawn error') + emitted = true # set before logger.error so a logging failure can't trigger a second metric + logger.error("storage_cli.call.error #{command}#{log_message_arg_suffix(command, args)}", + log_fields(command, args, blob_size: blob_size).merge('duration_seconds' => duration, 'error' => e.inspect)) + raise BlobstoreError.new(e.inspect) + ensure + unless emitted + duration = Time.now.utc - t + if status + exit_code = resolve_exit_code(status) + success = status.success? || (allow_exit_code_three && status.exitstatus == 3) + metric_exit_code = allow_exit_code_three && exit_code == 3 ? 0 : exit_code + safe_emit_metrics(command, metric_exit_code, duration, 'run_cli', blob_size: blob_size) + logger.info("storage_cli.call.finish #{command}#{log_message_arg_suffix(command, args)}", + log_fields(command, args, blob_size: blob_size).merge('duration_seconds' => duration, + 'exit_code' => exit_code, + 'success' => success)) + else + mid_exec_code = mid_execution_exit_code(capture3_called) + safe_emit_metrics(command, mid_exec_code, duration, 'run_cli no status') + logger.error("storage_cli.call.error #{command}#{log_message_arg_suffix(command, args)}", + log_fields(command, args, blob_size: blob_size).merge('duration_seconds' => duration, + 'exit_code' => mid_exec_code, + 'error' => $!.inspect)) # rubocop:disable Style/SpecialGlobalVars + end + true + end + end stderr.split("\n").each { |line| logger.info("[INFO] storage-cli: #{line}") } - exit_code = resolve_exit_code(status) - success = status.success? || (allow_exit_code_three && status.exitstatus == 3) - - logger.info("storage_cli.call.finish #{command}#{log_message_arg_suffix(command, args)}", - log_fields.merge( - 'duration_seconds' => duration, - 'exit_code' => exit_code, - 'success' => success - )) - - unless success - safe_emit_metrics(command, exit_code, duration, 'run_cli failure', blob_size: blob_size) - raise "storage-cli #{command} failed with exit code #{exit_code.inspect}, output: '#{stdout}', error: '#{stderr}'" - end - - # Remap allowed exit 3 (e.g. key-not-found on exists) to 0 so Prometheus only - # records non-zero exit_codes for genuine failures. - metric_exit_code = allow_exit_code_three && exit_code == 3 ? 0 : exit_code - safe_emit_metrics(command, metric_exit_code, duration, 'run_cli success', blob_size: blob_size) + raise "storage-cli #{command} failed with exit code #{exit_code.inspect}, output: '#{stdout}', error: '#{stderr}'" unless success [stdout, status] end - def operation_log_fields(command, args, blob_size: nil) - fields = { - 'operation' => command, - 'bucket' => @directory_key, - 'resource_type' => @resource_type - } + def log_message_arg_suffix(command, args) + case command + when 'put', 'get', 'copy' + " src=#{File.basename(args[0].to_s)} dest=#{File.basename(args[1].to_s)}" + when 'exists', 'delete', 'properties' + " key=#{File.basename(args[0].to_s)}" + when 'sign', 'sign-internal', 'sign-public' + " key=#{File.basename(args[0].to_s)} verb=#{args[1]} expires_in=#{args[2]}" + when 'list' + " prefix=#{File.basename(args[0].to_s)}" + else + args.empty? ? '' : " #{args.map { |a| File.basename(a.to_s) }.join(' ')}" + end + end + def log_fields(command, args, blob_size: nil) + fields = { 'operation' => command, 'bucket' => @directory_key, 'resource_type' => @resource_type } case command when 'put' fields['source_path'] = args[0] fields['destination_key'] = args[1] + fields['blob_size'] = blob_size unless blob_size.nil? when 'get' fields['source_key'] = args[0] fields['destination_path'] = args[1] + when 'exists', 'delete', 'properties' + fields['key'] = args[0] + when 'sign', 'sign-internal', 'sign-public' + fields['key'] = args[0] + fields['verb'] = args[1] + fields['expires_in'] = args[2] when 'copy' fields['source_key'] = args[0] fields['destination_key'] = args[1] - when 'exists', 'delete', 'properties' - fields['key'] = args[0] when 'list' fields['prefix'] = args[0] when 'delete-recursive' fields['path'] = args[0] - when 'sign', 'sign-public', 'sign-internal' - fields['key'] = args[0] - fields['verb'] = args[1] - fields['expires_in'] = args[2] end - - fields['size'] = blob_size if blob_size fields end - def capture_cli(command, args, start_time) - Open3.capture3(@cli_path, '-s', @storage_type, '-c', @config_file, *additional_flags, command, *args) - rescue StandardError => e - # exit_code=-1 is a sentinel for spawn failures (binary missing, permission denied). - duration = Time.now.utc - start_time - logger.error("storage_cli.call.error #{command}#{log_message_arg_suffix(command, args)}", - 'operation' => command, - 'bucket' => @directory_key, - 'resource_type' => @resource_type, - 'duration_seconds' => duration, - 'error' => e.inspect) - safe_emit_metrics(command, -1, duration, 'spawn error') - raise BlobstoreError.new(e.inspect) - end - - def log_message_arg_suffix(command, args) - printable_args = - case command - when 'put', 'copy', 'get' - ["src=#{summarize_log_arg(args[0])}", "dest=#{summarize_log_arg(args[1])}"] - when 'sign', 'sign-public', 'sign-internal' - [ - "key=#{summarize_log_arg(args[0])}", - "verb=#{args[1]}", - "expires_in=#{args[2]}" - ] - when 'exists', 'delete', 'properties' - ["key=#{summarize_log_arg(args[0])}"] - when 'list' - ["prefix=#{summarize_log_arg(args[0])}"] - when 'delete-recursive' - ["path=#{summarize_log_arg(args[0])}"] - else - [] - end - - printable_args = printable_args.compact.map(&:to_s).reject(&:empty?) - printable_args.empty? ? '' : " #{printable_args.join(' ')}" - end - - def summarize_log_arg(arg) - File.basename(arg.to_s) - end - def resolve_exit_code(status) if status.exitstatus status.exitstatus @@ -393,6 +305,15 @@ def resolve_exit_code(status) end end + def mid_execution_exit_code(capture3_called) + signal = $!.is_a?(Interrupt) || $!.is_a?(SignalException) # rubocop:disable Style/SpecialGlobalVars + if capture3_called + signal ? -6 : -7 + else + signal ? -5 : -7 + end + end + def sign_url(key, verb:, expires_in_seconds:, use_internal_url: false) command = if @storage_type == 'dav' diff --git a/lib/cloud_controller/metrics/prometheus_updater.rb b/lib/cloud_controller/metrics/prometheus_updater.rb index 88d4b24d401..da274c9115d 100644 --- a/lib/cloud_controller/metrics/prometheus_updater.rb +++ b/lib/cloud_controller/metrics/prometheus_updater.rb @@ -75,11 +75,11 @@ def self.allow_pid_label STORAGE_CLI_OPERATIONS_TOTAL_DOCSTRING = 'Total storage-cli subprocess invocations by operation and exit_code. ' \ 'exit_code=0: success; exit_code=3: not-found (expected for exists); ' \ - 'exit_code=-1: spawn failure (binary missing or permission denied); ' \ + 'exit_code=-1: spawn failure (binary missing or permission denied) after setup succeeds; ' \ 'exit_code=-2: process exited with neither exitstatus nor termsig (platform anomaly); ' \ - 'exit_code=-3: source file open/read failure before CLI invocation; ' \ + 'exit_code=-3: pre-spawn StandardError (config load, flags, or source file read failure); ' \ 'exit_code=-4: upload skipped locally because blob size is outside configured limits; ' \ - 'exit_code=-5: local non-StandardError before CLI invocation (for example Interrupt or SignalException); ' \ + 'exit_code=-5: Interrupt or SignalException before Open3.capture3 was called; ' \ 'exit_code=-6: signal received after CLI invocation began (Interrupt or SignalException mid-execution); ' \ 'exit_code=-7: fatal non-signal exception escaping run_cli (e.g. NoMemoryError)'.freeze STORAGE_CLI_METRICS = [ diff --git a/spec/unit/lib/cloud_controller/blobstore/storage_cli/storage_cli_client_spec.rb b/spec/unit/lib/cloud_controller/blobstore/storage_cli/storage_cli_client_spec.rb index 3927a63a0cb..25535398a76 100644 --- a/spec/unit/lib/cloud_controller/blobstore/storage_cli/storage_cli_client_spec.rb +++ b/spec/unit/lib/cloud_controller/blobstore/storage_cli/storage_cli_client_spec.rb @@ -516,7 +516,7 @@ def build_client(resource_type) 'resource_type' => resource_type, 'source_path' => 'src-path', 'destination_key' => 'dest-key', - 'size' => 1024, + 'blob_size' => 1024, 'exit_code' => 0, 'success' => true, 'duration_seconds' => a_kind_of(Float) @@ -645,8 +645,8 @@ def build_client(resource_type) )) end - it 'lets Interrupt propagate from Open3.capture3' do - metrics_updater = double('metrics_updater') + it 'emits exit_code=-6 and propagates Interrupt from Open3.capture3' do + metrics_updater = instance_double(VCAP::CloudController::Metrics::PrometheusUpdater) allow(metrics_updater).to receive(:report_storage_cli_metrics) spawning_client = StorageCliClient.new( directory_key: directory_key, @@ -657,8 +657,44 @@ def build_client(resource_type) allow(spawning_client).to receive(:additional_flags).and_return([]) allow(Open3).to receive(:capture3).and_raise(Interrupt) - expect(metrics_updater).not_to receive(:report_storage_cli_metrics) expect { spawning_client.send(:run_cli, 'get', 'some-key') }.to raise_error(Interrupt) + expect(metrics_updater).to have_received(:report_storage_cli_metrics).with( + operation: 'get', exit_code: -6, duration_seconds: a_kind_of(Float), blob_size: nil + ) + end + + it 'emits exit_code=-3 when additional_flags raises (pre-spawn StandardError)' do + metrics_updater = instance_double(VCAP::CloudController::Metrics::PrometheusUpdater) + allow(metrics_updater).to receive(:report_storage_cli_metrics) + spawning_client = StorageCliClient.new( + directory_key: directory_key, + resource_type: resource_type, + root_dir: 'bommel', + metrics_updater: metrics_updater + ) + allow(spawning_client).to receive(:additional_flags).and_raise(StandardError.new('config unavailable')) + + expect { spawning_client.send(:run_cli, 'get', 'some-key') }.to raise_error(BlobstoreError, /config unavailable/) + expect(metrics_updater).to have_received(:report_storage_cli_metrics).with( + operation: 'get', exit_code: -3, duration_seconds: a_kind_of(Float), blob_size: nil + ) + end + + it 'emits exit_code=-5 and propagates Interrupt from additional_flags (pre-spawn signal)' do + metrics_updater = instance_double(VCAP::CloudController::Metrics::PrometheusUpdater) + allow(metrics_updater).to receive(:report_storage_cli_metrics) + spawning_client = StorageCliClient.new( + directory_key: directory_key, + resource_type: resource_type, + root_dir: 'bommel', + metrics_updater: metrics_updater + ) + allow(spawning_client).to receive(:additional_flags).and_raise(Interrupt) + + expect { spawning_client.send(:run_cli, 'get', 'some-key') }.to raise_error(Interrupt) + expect(metrics_updater).to have_received(:report_storage_cli_metrics).with( + operation: 'get', exit_code: -5, duration_seconds: a_kind_of(Float), blob_size: nil + ) end context 'metrics' do @@ -709,6 +745,19 @@ def build_client(resource_type) ) end + it 'remaps exit_code 3 to 0 in the metric when allow_exit_code_three is true (not-found is expected, not an error)' do + # The log records the actual process exit code (3); the metric uses 0 so that + # "exists returned not-found" is indistinguishable from success in dashboards. + status = instance_double(Process::Status, success?: false, exitstatus: 3, termsig: nil) + allow(Open3).to receive(:capture3).and_return(['', '', status]) + + client_with_metrics.send(:run_cli, 'exists', 'some-key', allow_exit_code_three: true) + + expect(metrics_updater).to have_received(:report_storage_cli_metrics).with( + operation: 'exists', exit_code: 0, duration_seconds: a_kind_of(Float), blob_size: nil + ) + end + it 'forwards blob_size to report_storage_cli_metrics even on failure (PrometheusUpdater suppresses the histogram observation)' do status = instance_double(Process::Status, success?: false, exitstatus: 1) allow(Open3).to receive(:capture3).and_return(['', 'err', status]) @@ -728,6 +777,49 @@ def build_client(resource_type) expect { client.send(:run_cli, 'get', 'some-key') }.not_to raise_error end + + it 'logs the actual process exit_code in storage_cli.call.finish, not the remapped metric code' do + logger_double = double(info: nil, error: nil, debug: nil, warn: nil) + allow(Steno).to receive(:logger).and_return(logger_double) + # exit code 3 is remapped to 0 in the metric; log should record 3 + status = instance_double(Process::Status, success?: false, exitstatus: 3, termsig: nil) + allow(Open3).to receive(:capture3).and_return(['', '', status]) + + client_with_metrics.send(:run_cli, 'exists', 'some-key', allow_exit_code_three: true) + + expect(logger_double).to have_received(:info).with( + a_string_starting_with('storage_cli.call.finish'), + a_hash_including('exit_code' => 3) + ) + end + + it 'includes blob_size in structured log fields for put operations' do + logger_double = double(info: nil, error: nil, debug: nil, warn: nil) + allow(Steno).to receive(:logger).and_return(logger_double) + status = instance_double(Process::Status, success?: true, exitstatus: 0, termsig: nil) + allow(Open3).to receive(:capture3).and_return(['', '', status]) + + client_with_metrics.send(:run_cli, 'put', '/tmp/src.zip', 'dest-key', blob_size: 4096) + + expect(logger_double).to have_received(:info).with( + a_string_starting_with('storage_cli.call.finish'), + a_hash_including('blob_size' => 4096) + ) + end + + it 'uses File.basename in finish log message text for conciseness' do + logger_double = double(info: nil, error: nil, debug: nil, warn: nil) + allow(Steno).to receive(:logger).and_return(logger_double) + status = instance_double(Process::Status, success?: true, exitstatus: 0, termsig: nil) + allow(Open3).to receive(:capture3).and_return(['', '', status]) + + client_with_metrics.send(:run_cli, 'get', 'ab/cd/fullhash', '/var/vcap/data/dest/fullhash') + + expect(logger_double).to have_received(:info).with( + a_string_including('src=fullhash dest=fullhash'), + anything + ) + end end end @@ -863,7 +955,7 @@ def build_client(resource_type) source.close! end - it 'does not emit a duplicate signal metric when run_cli raises Interrupt' do + it 'does not double-emit when the subprocess is killed by a signal (cp_to_blobstore defers to run_cli)' do source = Tempfile.new('src') source.write('x' * 1025) source.flush @@ -878,17 +970,17 @@ def build_client(resource_type) metrics_updater: metrics_updater ) allow(client_with_metrics).to receive(:additional_flags).and_return([]) - allow(client_with_metrics).to receive(:run_cli).and_raise(Interrupt) - expect { client_with_metrics.cp_to_blobstore(source.path, 'some-key') }.to raise_error(Interrupt) - expect(metrics_updater).not_to have_received(:report_storage_cli_metrics).with( - operation: 'put', exit_code: -6, duration_seconds: anything, blob_size: nil - ) + status = instance_double(Process::Status, success?: false, exitstatus: nil, termsig: 2) + allow(Open3).to receive(:capture3).and_return(['', '', status]) + + expect { client_with_metrics.cp_to_blobstore(source.path, 'some-key') }.to raise_error(RuntimeError, /exit code 130/) + expect(metrics_updater).to have_received(:report_storage_cli_metrics).once ensure source.close! end - it 'emits exit_code=-7 when a fatal non-signal exception escapes run_cli' do + it 'does not double-emit when Open3 raises Interrupt after cli is called' do source = Tempfile.new('src') source.write('x' * 1025) source.flush @@ -903,12 +995,34 @@ def build_client(resource_type) metrics_updater: metrics_updater ) allow(client_with_metrics).to receive(:additional_flags).and_return([]) - allow(client_with_metrics).to receive(:run_cli).and_raise(NoMemoryError) + allow(Open3).to receive(:capture3).and_raise(Interrupt) - expect { client_with_metrics.cp_to_blobstore(source.path, 'some-key') }.to raise_error(NoMemoryError) - expect(metrics_updater).to have_received(:report_storage_cli_metrics).with( - operation: 'put', exit_code: -7, duration_seconds: anything, blob_size: nil + expect { client_with_metrics.cp_to_blobstore(source.path, 'some-key') }.to raise_error(Interrupt) + expect(metrics_updater).to have_received(:report_storage_cli_metrics).once + ensure + source.close! + end + + it 'logs cp-error and propagates when run_cli raises a fatal exception' do + source = Tempfile.new('src') + source.write('x' * 1025) + source.flush + + metrics_updater = instance_double(VCAP::CloudController::Metrics::PrometheusUpdater) + allow(metrics_updater).to receive(:report_storage_cli_metrics) + + client_with_metrics = StorageCliClient.new( + directory_key: directory_key, + resource_type: resource_type, + root_dir: 'bommel', + metrics_updater: metrics_updater ) + allow(client_with_metrics).to receive(:additional_flags).and_return([]) + allow(Open3).to receive(:capture3).and_raise(NoMemoryError) + + expect { client_with_metrics.cp_to_blobstore(source.path, 'some-key') }.to raise_error(NoMemoryError) + expect(logger_double).to have_received(:info).with('cp-error', anything) + expect(metrics_updater).to have_received(:report_storage_cli_metrics).once ensure source.close! end From 5fe779c2e0fbd8a0780e67dabbd6d9782758c32c Mon Sep 17 00:00:00 2001 From: Wei Quan Date: Thu, 12 Nov 2026 14:23:06 +0100 Subject: [PATCH 5/7] Extract log_exists_phase and safe_div from log_cp_r_phases --- lib/cloud_controller/blobstore/base_client.rb | 40 ++++++++++++------- 1 file changed, 25 insertions(+), 15 deletions(-) diff --git a/lib/cloud_controller/blobstore/base_client.rb b/lib/cloud_controller/blobstore/base_client.rb index bc567732ada..b6a9e8006b4 100644 --- a/lib/cloud_controller/blobstore/base_client.rb +++ b/lib/cloud_controller/blobstore/base_client.rb @@ -87,27 +87,37 @@ def log_cp_r_phases(ctrs, completed) files_scanned: ctrs[:digest_count], duration_seconds: ctrs[:digest_duration], completed: completed) - ec = ctrs[:exists_count] - ea = ctrs[:upload_attempts] - ee = ctrs[:exists_errors] - logger.info('blobstore.cp_r.exists', - files_checked: ec, - duration_seconds: ctrs[:exists_duration], - avg_duration_seconds: ec > 0 ? ctrs[:exists_duration] / ec : 0, - cache_hits: ec - ea - ee, - cache_misses: ea, - cache_hit_rate: (ec - ee) > 0 ? (ec - ea - ee).to_f / (ec - ee) : 0, - process_spawns: ec, - error_count: ee, - completed: completed) + log_exists_phase(ctrs, completed) + ua = ctrs[:upload_attempts] logger.info('blobstore.cp_r.upload', - files_to_upload: ea, + files_to_upload: ua, files_uploaded: ctrs[:upload_count], - files_failed: ea - ctrs[:upload_count], + files_failed: ua - ctrs[:upload_count], duration_seconds: ctrs[:upload_duration], completed: completed) end + def log_exists_phase(ctrs, completed) + checks = ctrs[:exists_count] + attempts = ctrs[:upload_attempts] + errors = ctrs[:exists_errors] + hits = checks - attempts - errors + resolved = checks - errors # checks that did not error + + logger.info('blobstore.cp_r.exists', + files_checked: checks, + duration_seconds: ctrs[:exists_duration], + avg_duration_seconds: safe_div(ctrs[:exists_duration], checks), + cache_hits: hits, + cache_misses: attempts, + cache_hit_rate: safe_div(hits, resolved), + process_spawns: checks, + error_count: errors, + completed: completed) + end + + def safe_div(num, denom) = denom.positive? ? num.to_f / denom : 0 + def partitioned_key(key) key = key.to_s.downcase partitioned_key = BlobKeyGenerator.full_path_from_key(key) From 0750a12f0948dbfb75eac866b3574aa11c8d0f32 Mon Sep 17 00:00:00 2001 From: Wei Quan Date: Mon, 16 Nov 2026 11:00:10 +0100 Subject: [PATCH 6/7] Fix non-throwing telemetry in ensure blocks and shared metrics PID collision --- .../storage_cli/storage_cli_client.rb | 57 +++++++++++-------- .../packager/local_bits_packer.rb | 4 +- lib/tasks/jobs.rake | 1 + 3 files changed, 36 insertions(+), 26 deletions(-) diff --git a/lib/cloud_controller/blobstore/storage_cli/storage_cli_client.rb b/lib/cloud_controller/blobstore/storage_cli/storage_cli_client.rb index f14bacab702..431c2807d8b 100644 --- a/lib/cloud_controller/blobstore/storage_cli/storage_cli_client.rb +++ b/lib/cloud_controller/blobstore/storage_cli/storage_cli_client.rb @@ -207,42 +207,26 @@ def run_cli(command, *args, allow_exit_code_three: false, blob_size: nil) t = Time.now.utc emitted = false capture3_called = false + exit_code = nil + success = false begin flags = additional_flags logger.debug("running storage-cli: #{@cli_path} -s #{@storage_type} -c #{@config_file} #{flags.join(' ')} #{command} #{args.join(' ')}") capture3_called = true stdout, stderr, status = Open3.capture3(@cli_path, '-s', @storage_type, '-c', @config_file, *flags, command, *args) + exit_code = resolve_exit_code(status) + success = status.success? || (allow_exit_code_three && status.exitstatus == 3) rescue StandardError => e duration = Time.now.utc - t # -1: spawn failure (binary missing/permission); -3: setup error before capture3 (e.g. config load) pre_spawn_code = capture3_called ? -1 : -3 safe_emit_metrics(command, pre_spawn_code, duration, 'spawn error') - emitted = true # set before logger.error so a logging failure can't trigger a second metric - logger.error("storage_cli.call.error #{command}#{log_message_arg_suffix(command, args)}", - log_fields(command, args, blob_size: blob_size).merge('duration_seconds' => duration, 'error' => e.inspect)) + emitted = true # set before safe_log so a logging failure can't trigger a second metric + safe_log(:error, "storage_cli.call.error #{command}#{log_message_arg_suffix(command, args)}", + log_fields(command, args, blob_size: blob_size).merge('duration_seconds' => duration, 'error' => e.inspect)) raise BlobstoreError.new(e.inspect) ensure - unless emitted - duration = Time.now.utc - t - if status - exit_code = resolve_exit_code(status) - success = status.success? || (allow_exit_code_three && status.exitstatus == 3) - metric_exit_code = allow_exit_code_three && exit_code == 3 ? 0 : exit_code - safe_emit_metrics(command, metric_exit_code, duration, 'run_cli', blob_size: blob_size) - logger.info("storage_cli.call.finish #{command}#{log_message_arg_suffix(command, args)}", - log_fields(command, args, blob_size: blob_size).merge('duration_seconds' => duration, - 'exit_code' => exit_code, - 'success' => success)) - else - mid_exec_code = mid_execution_exit_code(capture3_called) - safe_emit_metrics(command, mid_exec_code, duration, 'run_cli no status') - logger.error("storage_cli.call.error #{command}#{log_message_arg_suffix(command, args)}", - log_fields(command, args, blob_size: blob_size).merge('duration_seconds' => duration, - 'exit_code' => mid_exec_code, - 'error' => $!.inspect)) # rubocop:disable Style/SpecialGlobalVars - end - true - end + emit_and_log_cli_result(command, args, status, exit_code, success, capture3_called, allow_exit_code_three, t, blob_size) unless emitted end stderr.split("\n").each { |line| logger.info("[INFO] storage-cli: #{line}") } @@ -252,6 +236,31 @@ def run_cli(command, *args, allow_exit_code_three: false, blob_size: nil) [stdout, status] end + def safe_log(level, message, fields) + logger.public_send(level, message, fields) + rescue StandardError + nil + end + + def emit_and_log_cli_result(command, args, status, exit_code, success, capture3_called, allow_exit_code_three, start_time, blob_size) + duration = Time.now.utc - start_time + if status + metric_exit_code = allow_exit_code_three && exit_code == 3 ? 0 : exit_code + safe_emit_metrics(command, metric_exit_code, duration, 'run_cli', blob_size: blob_size) + safe_log(:info, "storage_cli.call.finish #{command}#{log_message_arg_suffix(command, args)}", + log_fields(command, args, blob_size: blob_size).merge('duration_seconds' => duration, + 'exit_code' => exit_code, + 'success' => success)) + else + mid_exec_code = mid_execution_exit_code(capture3_called) + safe_emit_metrics(command, mid_exec_code, duration, 'run_cli no status') + safe_log(:error, "storage_cli.call.error #{command}#{log_message_arg_suffix(command, args)}", + log_fields(command, args, blob_size: blob_size).merge('duration_seconds' => duration, + 'exit_code' => mid_exec_code, + 'error' => $!.inspect)) # rubocop:disable Style/SpecialGlobalVars + end + end + def log_message_arg_suffix(command, args) case command when 'put', 'get', 'copy' diff --git a/lib/cloud_controller/packager/local_bits_packer.rb b/lib/cloud_controller/packager/local_bits_packer.rb index 0532cb982e3..9680984e0ac 100644 --- a/lib/cloud_controller/packager/local_bits_packer.rb +++ b/lib/cloud_controller/packager/local_bits_packer.rb @@ -28,7 +28,7 @@ def send_package_to_blobstore(blobstore_key, uploaded_package_zip, cached_files_ begin package_blobstore.cp_to_blobstore(complete_package_path, blobstore_key) ensure - logger.info('packer.final-upload', duration_seconds: Time.now.utc - t, blobstore_key: blobstore_key) + logger.info('packer.final-upload', duration_seconds: Time.now.utc - t, blobstore_key: blobstore_key) rescue nil # rubocop:disable Style/RescueModifier end { @@ -36,8 +36,8 @@ def send_package_to_blobstore(blobstore_key, uploaded_package_zip, cached_files_ sha256: Digester.new(algorithm: OpenSSL::Digest::SHA256).digest_path(complete_package_path) } ensure - logger.info('packer.pack', duration_seconds: Time.now.utc - pack_start, blobstore_key: blobstore_key) FileUtils.remove_dir(local_bits_packer_path) + logger.info('packer.pack', duration_seconds: Time.now.utc - pack_start, blobstore_key: blobstore_key) rescue nil # rubocop:disable Style/RescueModifier end end diff --git a/lib/tasks/jobs.rake b/lib/tasks/jobs.rake index 9c2aa46cf33..74fb469dd68 100644 --- a/lib/tasks/jobs.rake +++ b/lib/tasks/jobs.rake @@ -34,6 +34,7 @@ namespace :jobs do RakeConfig.context = :api VCAP::CloudController::ExecutionContext::API_PUMA_WORKER.set_process_type_env + require 'cloud_controller/metrics/custom_process_id' require 'prometheus/client/data_stores/direct_file_store' prometheus_dir = File.join(RakeConfig.config.get(:directories, :tmpdir), 'prometheus') FileUtils.mkdir_p(prometheus_dir) From 9098d09ed96f2bc1df63721c664de6d007cae456 Mon Sep 17 00:00:00 2001 From: Wei Quan Date: Fri, 27 Nov 2026 11:35:26 +0100 Subject: [PATCH 7/7] Configure storage-cli logging and harden telemetry Add independent CLI log-level validation and retain failure stderr at error level without suppressing upload summaries or metrics. Preserve storage errors, cancellation, and cleanup when logging or reporting fails. Exclude unresolved cache checks from cache hits. Namespace local-worker metric files while preserving generic-worker identities, and keep live worker files during API startup resets. Remove redundant helpers and digest state, and add regression coverage. --- lib/cloud_controller/blobstore/base_client.rb | 33 ++- .../storage_cli/storage_cli_client.rb | 60 +++-- .../config_schemas/api_schema.rb | 2 + .../blobstore_benchmarks_schema.rb | 2 + .../config_schemas/clock_schema.rb | 2 + .../deployment_updater_schema.rb | 2 + .../config_schemas/worker_schema.rb | 2 + .../metrics/custom_process_id.rb | 10 +- .../metrics/prometheus_updater.rb | 9 +- .../packager/shared_bits_packer.rb | 8 +- lib/cloud_controller/runner.rb | 4 +- .../blobstore/local/local_client_spec.rb | 17 +- .../storage_cli/storage_cli_client_spec.rb | 213 +++++++++++++++++- spec/unit/lib/cloud_controller/config_spec.rb | 29 +++ .../metrics/custom_process_id_spec.rb | 72 ++++++ .../metrics/prometheus_updater_spec.rb | 15 +- .../packager/local_bits_packer_spec.rb | 21 ++ spec/unit/lib/cloud_controller/runner_spec.rb | 42 ++++ 18 files changed, 452 insertions(+), 91 deletions(-) create mode 100644 spec/unit/lib/cloud_controller/metrics/custom_process_id_spec.rb diff --git a/lib/cloud_controller/blobstore/base_client.rb b/lib/cloud_controller/blobstore/base_client.rb index b6a9e8006b4..3c4a2b41a7d 100644 --- a/lib/cloud_controller/blobstore/base_client.rb +++ b/lib/cloud_controller/blobstore/base_client.rb @@ -10,7 +10,7 @@ def cp_r_to_blobstore(source_dir) begin unless File.directory?(source_dir) - logger.error('blobstore.cp_r.source_dir_missing', source_dir: source_dir) + logger.error('blobstore.cp_r.source_dir_missing', source_dir: source_dir) rescue nil # rubocop:disable Style/RescueModifier raise Errno::ENOENT.new(source_dir) end @@ -24,14 +24,9 @@ def cp_r_to_blobstore(source_dir) next unless within_limits?(stat.size) next unless stat.mode.to_s(8)[3..5].to_i(8) >= 0o600 - cp_r_digest_file(path, counters) - sha1 = counters[:last_sha1] + sha1 = cp_r_digest_file(path, counters) - next unless sha1 - - exists = cp_r_check_exists(sha1, counters) - next if exists.nil? # exists? raised, already logged - next if exists + next if cp_r_check_exists(sha1, counters) cp_r_upload_file(path, sha1, counters) end @@ -50,13 +45,13 @@ def cp_to_blobstore(_, _) def new_cp_r_counters { digest_duration: 0, exists_duration: 0, upload_duration: 0, digest_count: 0, exists_count: 0, upload_count: 0, - upload_attempts: 0, exists_errors: 0, last_sha1: nil } + upload_attempts: 0, exists_errors: 0 } end def cp_r_digest_file(path, counters) t = Time.now.utc counters[:digest_count] += 1 - counters[:last_sha1] = Digester.new.digest_path(path) + Digester.new.digest_path(path) ensure counters[:digest_duration] += Time.now.utc - t end @@ -64,11 +59,14 @@ def cp_r_digest_file(path, counters) def cp_r_check_exists(sha1, counters) t = Time.now.utc counters[:exists_count] += 1 - exists?(sha1) - rescue StandardError => e + # A check stays unresolved unless it returns a result, including on cancellation. counters[:exists_errors] += 1 - logger.error('blobstore.cp_r.exists.error', sha1: sha1, error: e.message) - nil + exists = exists?(sha1) + counters[:exists_errors] -= 1 + exists + rescue StandardError => e + logger.error('blobstore.cp_r.exists.error', sha1: sha1, error: e.message) rescue nil # rubocop:disable Style/RescueModifier + raise ensure counters[:exists_duration] += Time.now.utc - t end @@ -86,7 +84,7 @@ def log_cp_r_phases(ctrs, completed) logger.info('blobstore.cp_r.digest', files_scanned: ctrs[:digest_count], duration_seconds: ctrs[:digest_duration], - completed: completed) + completed: completed) rescue nil # rubocop:disable Style/RescueModifier log_exists_phase(ctrs, completed) ua = ctrs[:upload_attempts] logger.info('blobstore.cp_r.upload', @@ -94,7 +92,7 @@ def log_cp_r_phases(ctrs, completed) files_uploaded: ctrs[:upload_count], files_failed: ua - ctrs[:upload_count], duration_seconds: ctrs[:upload_duration], - completed: completed) + completed: completed) rescue nil # rubocop:disable Style/RescueModifier end def log_exists_phase(ctrs, completed) @@ -111,9 +109,8 @@ def log_exists_phase(ctrs, completed) cache_hits: hits, cache_misses: attempts, cache_hit_rate: safe_div(hits, resolved), - process_spawns: checks, error_count: errors, - completed: completed) + completed: completed) rescue nil # rubocop:disable Style/RescueModifier end def safe_div(num, denom) = denom.positive? ? num.to_f / denom : 0 diff --git a/lib/cloud_controller/blobstore/storage_cli/storage_cli_client.rb b/lib/cloud_controller/blobstore/storage_cli/storage_cli_client.rb index 431c2807d8b..1926577a07f 100644 --- a/lib/cloud_controller/blobstore/storage_cli/storage_cli_client.rb +++ b/lib/cloud_controller/blobstore/storage_cli/storage_cli_client.rb @@ -106,7 +106,7 @@ def cp_to_blobstore(source_path, destination_key) size = nil metric_emitted = false - logger.info('cp-start', destination_key: destination_key, source_path: source_path, bucket: @directory_key) + logger.info('cp-start', destination_key: destination_key, source_path: source_path, bucket: @directory_key) rescue nil # rubocop:disable Style/RescueModifier begin File.open(source_path) do |file| @@ -137,21 +137,19 @@ def cp_to_blobstore(source_path, destination_key) log_entry = 'cp-error' raise ensure - begin - logger.info(log_entry, - destination_key: destination_key, - duration_seconds: Time.now.utc - start, - size: size) - rescue StandardError => e - logger.warn("cp_to_blobstore ensure log failed: #{e.inspect}") - end + logger.info(log_entry, + destination_key: destination_key, + duration_seconds: Time.now.utc - start, + size: size) rescue nil # rubocop:disable Style/RescueModifier end end def safe_emit_metrics(operation, exit_code, duration, context, blob_size: nil) - emit_storage_cli_metrics(operation, exit_code, duration, blob_size: blob_size) + return if @metrics_updater.nil? + + @metrics_updater.report_storage_cli_metrics(operation: operation, exit_code: exit_code, duration_seconds: duration, blob_size: blob_size) rescue StandardError => e - logger.warn("emit_storage_cli_metrics failed in #{context}: #{e.inspect}") + logger.warn("storage-cli metrics failed in #{context}: #{e.inspect}") rescue nil # rubocop:disable Style/RescueModifier end def cp_file_between_keys(source_key, destination_key) @@ -211,7 +209,7 @@ def run_cli(command, *args, allow_exit_code_three: false, blob_size: nil) success = false begin flags = additional_flags - logger.debug("running storage-cli: #{@cli_path} -s #{@storage_type} -c #{@config_file} #{flags.join(' ')} #{command} #{args.join(' ')}") + cli_logger.debug("running storage-cli: #{@cli_path} -s #{@storage_type} -c #{@config_file} #{flags.join(' ')} #{command} #{args.join(' ')}") rescue nil # rubocop:disable Style/RescueModifier capture3_called = true stdout, stderr, status = Open3.capture3(@cli_path, '-s', @storage_type, '-c', @config_file, *flags, command, *args) exit_code = resolve_exit_code(status) @@ -221,43 +219,36 @@ def run_cli(command, *args, allow_exit_code_three: false, blob_size: nil) # -1: spawn failure (binary missing/permission); -3: setup error before capture3 (e.g. config load) pre_spawn_code = capture3_called ? -1 : -3 safe_emit_metrics(command, pre_spawn_code, duration, 'spawn error') - emitted = true # set before safe_log so a logging failure can't trigger a second metric - safe_log(:error, "storage_cli.call.error #{command}#{log_message_arg_suffix(command, args)}", - log_fields(command, args, blob_size: blob_size).merge('duration_seconds' => duration, 'error' => e.inspect)) + emitted = true # Set before logging so failures cannot trigger a second metric. + cli_logger.error("storage_cli.call.error #{command}#{log_message_arg_suffix(command, args)}", + log_fields(command, args, blob_size: blob_size).merge('duration_seconds' => duration, 'error' => e.inspect)) rescue nil # rubocop:disable Style/RescueModifier raise BlobstoreError.new(e.inspect) ensure emit_and_log_cli_result(command, args, status, exit_code, success, capture3_called, allow_exit_code_three, t, blob_size) unless emitted end - stderr.split("\n").each { |line| logger.info("[INFO] storage-cli: #{line}") } + stderr_log_level = success ? :info : :error + stderr.split("\n").each do |line| + cli_logger.public_send(stderr_log_level, "[#{stderr_log_level.upcase}] storage-cli: #{line}") rescue nil # rubocop:disable Style/RescueModifier + end raise "storage-cli #{command} failed with exit code #{exit_code.inspect}, output: '#{stdout}', error: '#{stderr}'" unless success [stdout, status] end - def safe_log(level, message, fields) - logger.public_send(level, message, fields) - rescue StandardError - nil - end - def emit_and_log_cli_result(command, args, status, exit_code, success, capture3_called, allow_exit_code_three, start_time, blob_size) duration = Time.now.utc - start_time if status metric_exit_code = allow_exit_code_three && exit_code == 3 ? 0 : exit_code safe_emit_metrics(command, metric_exit_code, duration, 'run_cli', blob_size: blob_size) - safe_log(:info, "storage_cli.call.finish #{command}#{log_message_arg_suffix(command, args)}", - log_fields(command, args, blob_size: blob_size).merge('duration_seconds' => duration, - 'exit_code' => exit_code, - 'success' => success)) + cli_logger.public_send(success ? :info : :error, "storage_cli.call.finish #{command}#{log_message_arg_suffix(command, args)}", + log_fields(command, args, blob_size: blob_size).merge('duration_seconds' => duration, 'exit_code' => exit_code, 'success' => success)) rescue nil # rubocop:disable Style/RescueModifier else mid_exec_code = mid_execution_exit_code(capture3_called) safe_emit_metrics(command, mid_exec_code, duration, 'run_cli no status') - safe_log(:error, "storage_cli.call.error #{command}#{log_message_arg_suffix(command, args)}", - log_fields(command, args, blob_size: blob_size).merge('duration_seconds' => duration, - 'exit_code' => mid_exec_code, - 'error' => $!.inspect)) # rubocop:disable Style/SpecialGlobalVars + cli_logger.error("storage_cli.call.error #{command}#{log_message_arg_suffix(command, args)}", + log_fields(command, args, blob_size: blob_size).merge('duration_seconds' => duration, 'exit_code' => mid_exec_code, 'error' => $!.inspect)) rescue nil # rubocop:disable Style/RescueModifier, Style/SpecialGlobalVars end end @@ -363,10 +354,11 @@ def logger @logger ||= Steno.logger('cc.blobstore.storage_cli_client') end - def emit_storage_cli_metrics(operation, exit_code, duration_seconds, blob_size: nil) - return if @metrics_updater.nil? - - @metrics_updater.report_storage_cli_metrics(operation:, exit_code:, duration_seconds:, blob_size:) + def cli_logger + @cli_logger ||= Steno.logger('cc.blobstore.storage_cli').tap do |log| + level = VCAP::CloudController::Config.config.get(:storage_cli_logging_level) + log.level = level.to_sym if level + end end end end diff --git a/lib/cloud_controller/config_schemas/api_schema.rb b/lib/cloud_controller/config_schemas/api_schema.rb index d0389dc1389..fd1e6042421 100644 --- a/lib/cloud_controller/config_schemas/api_schema.rb +++ b/lib/cloud_controller/config_schemas/api_schema.rb @@ -1,4 +1,5 @@ require 'vcap/config' +require 'steno/logger' require 'cloud_controller/resource_pool' module VCAP::CloudController @@ -101,6 +102,7 @@ class ApiSchema < VCAP::Config optional(:storage_cli_config_file_resource_pool) => String, optional(:storage_cli_config_file_droplets) => String, optional(:storage_cli_optional_flags) => String, + optional(:storage_cli_logging_level) => enum(*Steno::Logger::LEVELS.keys.map(&:to_s), NilClass), newrelic_enabled: bool, diff --git a/lib/cloud_controller/config_schemas/blobstore_benchmarks_schema.rb b/lib/cloud_controller/config_schemas/blobstore_benchmarks_schema.rb index 2f68d70198e..5f610347c0c 100644 --- a/lib/cloud_controller/config_schemas/blobstore_benchmarks_schema.rb +++ b/lib/cloud_controller/config_schemas/blobstore_benchmarks_schema.rb @@ -1,4 +1,5 @@ require 'vcap/config' +require 'steno/logger' module VCAP::CloudController module ConfigSchemas @@ -46,6 +47,7 @@ class BlobstoreBenchmarksSchema < VCAP::Config optional(:storage_cli_config_file_packages) => String, optional(:storage_cli_config_file_droplets) => String, optional(:storage_cli_optional_flags) => String, + optional(:storage_cli_logging_level) => enum(*Steno::Logger::LEVELS.keys.map(&:to_s), NilClass), db_encryption_key: enum(String, NilClass), diff --git a/lib/cloud_controller/config_schemas/clock_schema.rb b/lib/cloud_controller/config_schemas/clock_schema.rb index 9f0e735f686..46653474643 100644 --- a/lib/cloud_controller/config_schemas/clock_schema.rb +++ b/lib/cloud_controller/config_schemas/clock_schema.rb @@ -1,4 +1,5 @@ require 'vcap/config' +require 'steno/logger' module VCAP::CloudController module ConfigSchemas @@ -67,6 +68,7 @@ class ClockSchema < VCAP::Config optional(:storage_cli_config_file_resource_pool) => String, optional(:storage_cli_config_file_droplets) => String, optional(:storage_cli_optional_flags) => String, + optional(:storage_cli_logging_level) => enum(*Steno::Logger::LEVELS.keys.map(&:to_s), NilClass), newrelic_enabled: bool, diff --git a/lib/cloud_controller/config_schemas/deployment_updater_schema.rb b/lib/cloud_controller/config_schemas/deployment_updater_schema.rb index e582c6519a2..53353d12d16 100644 --- a/lib/cloud_controller/config_schemas/deployment_updater_schema.rb +++ b/lib/cloud_controller/config_schemas/deployment_updater_schema.rb @@ -1,4 +1,5 @@ require 'vcap/config' +require 'steno/logger' module VCAP::CloudController module ConfigSchemas @@ -19,6 +20,7 @@ class DeploymentUpdaterSchema < VCAP::Config optional(:storage_cli_config_file_resource_pool) => String, optional(:storage_cli_config_file_droplets) => String, optional(:storage_cli_optional_flags) => String, + optional(:storage_cli_logging_level) => enum(*Steno::Logger::LEVELS.keys.map(&:to_s), NilClass), readiness_port: { deployment_updater: Integer diff --git a/lib/cloud_controller/config_schemas/worker_schema.rb b/lib/cloud_controller/config_schemas/worker_schema.rb index f678bf6039b..29a6cfa9044 100644 --- a/lib/cloud_controller/config_schemas/worker_schema.rb +++ b/lib/cloud_controller/config_schemas/worker_schema.rb @@ -1,4 +1,5 @@ require 'vcap/config' +require 'steno/logger' module VCAP::CloudController module ConfigSchemas @@ -47,6 +48,7 @@ class WorkerSchema < VCAP::Config optional(:storage_cli_config_file_resource_pool) => String, optional(:storage_cli_config_file_droplets) => String, optional(:storage_cli_optional_flags) => String, + optional(:storage_cli_logging_level) => enum(*Steno::Logger::LEVELS.keys.map(&:to_s), NilClass), newrelic_enabled: bool, diff --git a/lib/cloud_controller/metrics/custom_process_id.rb b/lib/cloud_controller/metrics/custom_process_id.rb index 59f1931480b..664299edfd3 100644 --- a/lib/cloud_controller/metrics/custom_process_id.rb +++ b/lib/cloud_controller/metrics/custom_process_id.rb @@ -1,12 +1,16 @@ # Storing the metrics of several worker processes on cc-worker VMs in a DirectFileStore residing in a single directory # did not work because the different processes are isolated by bpm and several processes used the same pid within their container. # This pid is used for the filename and resulted in corrupted data because several processes were writing data to the same files. -# When requiring this file, the process_id method of the MetricStore will be overridden to first check for `INDEX` in -# env variables before returning the actual pid. The `INDEX` is provided for cc-worker processes. +# Local workers are prefixed to avoid API PID collisions; generic workers retain their existing numeric identities. +# shortcut: legacy local files are reset in BOSH pre-start; manual code upgrades need a reset with writers stopped. module CustomProcessId def process_id - ENV.fetch('INDEX', Process.pid).to_i + index = ENV.fetch('INDEX', nil) + return Process.pid unless index + + # shortcut: other INDEX-based roles keep numeric IDs; namespace them if they share API metric storage. + ENV.fetch('PROCESS_TYPE', nil) == 'puma_worker' ? "index-#{index.to_i}" : index.to_i end end diff --git a/lib/cloud_controller/metrics/prometheus_updater.rb b/lib/cloud_controller/metrics/prometheus_updater.rb index da274c9115d..71678797131 100644 --- a/lib/cloud_controller/metrics/prometheus_updater.rb +++ b/lib/cloud_controller/metrics/prometheus_updater.rb @@ -73,8 +73,8 @@ def self.allow_pid_label ].freeze STORAGE_CLI_OPERATIONS_TOTAL_DOCSTRING = - 'Total storage-cli subprocess invocations by operation and exit_code. ' \ - 'exit_code=0: success; exit_code=3: not-found (expected for exists); ' \ + 'Total storage-cli operation attempts by operation and exit_code, including local skips and pre-spawn failures. ' \ + 'Non-negative values are process exit statuses; expected exists exit_code=3 is recorded as 0. ' \ 'exit_code=-1: spawn failure (binary missing or permission denied) after setup succeeds; ' \ 'exit_code=-2: process exited with neither exitstatus nor termsig (platform anomaly); ' \ 'exit_code=-3: pre-spawn StandardError (config load, flags, or source file read failure); ' \ @@ -87,7 +87,7 @@ def self.allow_pid_label docstring: STORAGE_CLI_OPERATIONS_TOTAL_DOCSTRING, labels: %i[operation exit_code] }, { type: :histogram, name: :cc_storage_cli_duration_seconds, - docstring: 'Duration of individual storage-cli subprocess invocations. ' \ + docstring: 'Duration of storage-cli operation attempts, including local skips and pre-spawn failures. ' \ 'Counts per-retry, not per logical operation.', labels: %i[operation exit_code], buckets: STORAGE_CLI_DURATION_BUCKETS }, { type: :histogram, name: :cc_storage_cli_blob_size_bytes, @@ -111,8 +111,7 @@ def initialize(registry: Prometheus::Client.registry) @registry = registry @execution_context = VCAP::CloudController::ExecutionContext.from_process_type_env - register_metrics_for_process unless @execution_context.nil? - return if @execution_context.nil? + register_metrics_for_process initialize_cc_db_connection_pool_timeouts_total end diff --git a/lib/cloud_controller/packager/shared_bits_packer.rb b/lib/cloud_controller/packager/shared_bits_packer.rb index 1af296ce466..6f39b7451da 100644 --- a/lib/cloud_controller/packager/shared_bits_packer.rb +++ b/lib/cloud_controller/packager/shared_bits_packer.rb @@ -30,7 +30,7 @@ def populate_resource_cache(app_packager, app_contents_path) begin app_packager.unzip(app_contents_path) ensure - logger.info('packer.unzip', duration_seconds: Time.now.utc - t) + logger.info('packer.unzip', duration_seconds: Time.now.utc - t) rescue nil # rubocop:disable Style/RescueModifier end remove_symlinks(app_contents_path) @@ -39,7 +39,7 @@ def populate_resource_cache(app_packager, app_contents_path) begin global_app_bits_cache.cp_r_to_blobstore(app_contents_path) ensure - logger.info('packer.resource-cache-upload', duration_seconds: Time.now.utc - t) + logger.info('packer.resource-cache-upload', duration_seconds: Time.now.utc - t) rescue nil # rubocop:disable Style/RescueModifier end end @@ -73,7 +73,7 @@ def append_matched_resources(app_packager, cached_files_fingerprints, root_path) download_count += 1 end ensure - logger.info('packer.resource-cache-download', duration_seconds: Time.now.utc - t, files_downloaded: download_count, files_attempted: download_attempts) + logger.info('packer.resource-cache-download', duration_seconds: Time.now.utc - t, files_downloaded: download_count, files_attempted: download_attempts) rescue nil # rubocop:disable Style/RescueModifier end raise CloudController::Errors::ApiError.new_from_details('ResourceChecksumMismatch') if checksum_mismatch @@ -82,7 +82,7 @@ def append_matched_resources(app_packager, cached_files_fingerprints, root_path) begin app_packager.append_dir_contents(cached_resources_dir) ensure - logger.info('packer.repackage', duration_seconds: Time.now.utc - t) + logger.info('packer.repackage', duration_seconds: Time.now.utc - t) rescue nil # rubocop:disable Style/RescueModifier end end diff --git a/lib/cloud_controller/runner.rb b/lib/cloud_controller/runner.rb index 2b32bfea526..684020c05ce 100644 --- a/lib/cloud_controller/runner.rb +++ b/lib/cloud_controller/runner.rb @@ -123,8 +123,10 @@ def setup_metrics prometheus_dir = File.join(@config.get(:directories, :tmpdir), 'prometheus') FileUtils.mkdir_p(prometheus_dir) - # Resetting metrics on startup + # Local worker files may already be open; reset only API files here. Dir["#{prometheus_dir}/*.bin"].each do |file_path| + next if File.basename(file_path).include?('___index-') + File.unlink(file_path) end diff --git a/spec/unit/lib/cloud_controller/blobstore/local/local_client_spec.rb b/spec/unit/lib/cloud_controller/blobstore/local/local_client_spec.rb index a94d754ff11..7ed23110c6a 100644 --- a/spec/unit/lib/cloud_controller/blobstore/local/local_client_spec.rb +++ b/spec/unit/lib/cloud_controller/blobstore/local/local_client_spec.rb @@ -105,6 +105,17 @@ module Blobstore end describe '#cp_r_to_blobstore' do + it 'preserves traversal errors when phase logging fails' do + client + error = Errno::EACCES.new('resource traversal denied') + allow(Find).to receive(:find).and_raise(error) + allow(logger).to receive(:info).and_raise(IOError, 'log sink unavailable') + + expect do + client.cp_r_to_blobstore(base_path) + end.to(raise_error { |raised| expect(raised).to equal(error) }) + end + it 'logs completed: false when traversal is interrupted before any files are processed' do allow(Find).to receive(:find).and_raise(Errno::EACCES) @@ -128,7 +139,7 @@ module Blobstore end.not_to raise_error end - it 'continues traversal and increments error_count when exists? raises' do + it 'propagates existence check failures and logs incomplete traversal' do source_dir = File.join(base_path, 'source') FileUtils.mkdir_p(source_dir) File.write(File.join(source_dir, 'file1.txt'), 'x' * 100) @@ -144,10 +155,10 @@ module Blobstore expect do client.cp_r_to_blobstore(source_dir) - end.not_to raise_error + end.to raise_error(StandardError, 'exists failed') expect(logger).to have_received(:info).with('blobstore.cp_r.exists', - hash_including(files_checked: 2, error_count: 1, cache_hits: 0, cache_hit_rate: 0.0, completed: true)) + hash_including(files_checked: 1, error_count: 1, cache_hits: 0, cache_hit_rate: 0.0, completed: false)) end it 'counts a digest attempt even when digest_path raises' do diff --git a/spec/unit/lib/cloud_controller/blobstore/storage_cli/storage_cli_client_spec.rb b/spec/unit/lib/cloud_controller/blobstore/storage_cli/storage_cli_client_spec.rb index 25535398a76..475eda34f52 100644 --- a/spec/unit/lib/cloud_controller/blobstore/storage_cli/storage_cli_client_spec.rb +++ b/spec/unit/lib/cloud_controller/blobstore/storage_cli/storage_cli_client_spec.rb @@ -354,6 +354,87 @@ def build_client(resource_type) end end + describe 'dedicated CLI logging level' do + let(:configured_level) { 'warn' } + let(:inherited_level) { :info } + let(:cli_sink) { Steno::Sink::Counter.new } + let(:summary_sink) { Steno::Sink::Counter.new } + let(:cli_logger) { Steno::Logger.new('cc.blobstore.storage_cli', [cli_sink], level: inherited_level) } + let(:summary_logger) { Steno::Logger.new('cc.blobstore.storage_cli_client', [summary_sink], level: :info) } + let(:metrics_dir) { Dir.mktmpdir('storage-cli-metrics') } + let(:metrics_registry) do + Prometheus::Client.config.data_store = Prometheus::Client::DataStores::DirectFileStore.new(dir: metrics_dir) + Prometheus::Client::Registry.new + end + let(:metrics_updater) { VCAP::CloudController::Metrics::PrometheusUpdater.new(registry: metrics_registry) } + + subject(:client) do + StorageCliClient.new(directory_key: directory_key, resource_type: resource_type, root_dir: 'bommel', metrics_updater: metrics_updater) + end + + around do |example| + original_store = Prometheus::Client.config.data_store + example.run + ensure + Prometheus::Client.config.data_store = original_store + FileUtils.remove_entry(metrics_dir) + end + + before do + allow(Steno).to receive(:logger).with('cc.blobstore.storage_cli').and_return(cli_logger) + allow(Steno).to receive(:logger).with('cc.blobstore.storage_cli_client').and_return(summary_logger) + allow(VCAP::CloudController::Config.config).to receive(:get).with(:storage_cli_logging_level).and_return(configured_level) + end + + it 'suppresses successful CLI logs without suppressing upload summaries or metrics' do + status = instance_double(Process::Status, success?: true, exitstatus: 0) + allow(Open3).to receive(:capture3).and_return(['', 'CLI diagnostic', status]) + + Tempfile.create('src') do |source| + source.write('application package') + source.flush + client.cp_to_blobstore(source.path, 'some-key') + end + + expect(cli_sink.counts).to be_empty + expect(summary_sink.counts).to eq('info' => 2) + expect(metrics_registry.get(:cc_storage_cli_operations_total).get(labels: { operation: 'put', exit_code: '0' })).to eq(1.0) + end + + it 'keeps failed CLI calls and stderr visible when successful call logs are suppressed' do + status = instance_double(Process::Status, success?: false, exitstatus: 1) + allow(Open3).to receive(:capture3).and_return(['CLI output', "storage unavailable\nrequest failed", status]) + allow(cli_sink).to receive(:add_record).and_call_original + + Tempfile.create('src') do |source| + source.write('application package') + source.flush + + expect do + client.cp_to_blobstore(source.path, 'some-key') + end.to raise_error(RuntimeError, "storage-cli put failed with exit code 1, output: 'CLI output', error: 'storage unavailable\nrequest failed'") + end + + expect(cli_sink.counts).to eq('error' => 3) + expect(cli_sink).to have_received(:add_record).with(have_attributes(log_level: :error, message: '[ERROR] storage-cli: storage unavailable')) + expect(cli_sink).to have_received(:add_record).with(have_attributes(log_level: :error, message: '[ERROR] storage-cli: request failed')) + expect(metrics_registry.get(:cc_storage_cli_operations_total).get(labels: { operation: 'put', exit_code: '1' })).to eq(1.0) + end + + context 'when the dedicated level is omitted' do + let(:configured_level) { nil } + let(:inherited_level) { :warn } + + it 'keeps the inherited logging threshold' do + status = instance_double(Process::Status, success?: true, exitstatus: 0) + allow(Open3).to receive(:capture3).and_return(['', '', status]) + + expect(client.exists?('some-key')).to be true + expect(cli_sink.counts).to be_empty + end + end + end + describe '#exists?' do context 'when the blob exists' do before { allow(client).to receive(:run_cli).with('exists', any_args).and_return([nil, instance_double(Process::Status, exitstatus: 0)]) } @@ -531,15 +612,18 @@ def build_client(resource_type) client.send(:run_cli, 'exists', 'arg1') end.to raise_error(RuntimeError, /storage-cli exists failed with exit code 1/) - expect(logger_double).to have_received(:info).with('storage_cli.call.finish exists key=arg1', hash_including( - 'operation' => 'exists', - 'bucket' => directory_key, - 'resource_type' => resource_type, - 'key' => 'arg1', - 'exit_code' => 1, - 'success' => false, - 'duration_seconds' => a_kind_of(Float) - )) + expect(logger_double).to have_received(:error).with( + 'storage_cli.call.finish exists key=arg1', + hash_including( + 'operation' => 'exists', + 'bucket' => directory_key, + 'resource_type' => resource_type, + 'key' => 'arg1', + 'exit_code' => 1, + 'success' => false, + 'duration_seconds' => a_kind_of(Float) + ) + ) end it 'uses basename of key arg in message text with key= label but keeps full structured key' do @@ -569,11 +653,13 @@ def build_client(resource_type) it 'returns output and status on success' do status = instance_double(Process::Status, success?: true, exitstatus: 0) - allow(Open3).to receive(:capture3).and_return(['ok', '', status]) + allow(Open3).to receive(:capture3).and_return(['ok', 'CLI diagnostic', status]) output, returned_status = client.send(:run_cli, 'list', 'arg1') expect(output).to eq('ok') expect(returned_status).to eq(status) + expect(logger_double).to have_received(:info).with('[INFO] storage-cli: CLI diagnostic') + expect(logger_double).not_to have_received(:error) end it 'raises an error on failure' do @@ -592,6 +678,20 @@ def build_client(resource_type) output, returned_status = client.send(:run_cli, 'list', 'arg1', allow_exit_code_three: true) expect(output).to eq('') expect(returned_status).to eq(status) + expect(logger_double).to have_received(:info).with('[INFO] storage-cli: error message') + expect(logger_double).not_to have_received(:error) + end + + it 'preserves the CLI failure when stderr logging fails' do + status = instance_double(Process::Status, success?: false, exitstatus: 1) + allow(Open3).to receive(:capture3).and_return(['CLI output', 'storage unavailable', status]) + allow(logger_double).to receive(:error).with('[ERROR] storage-cli: storage unavailable').and_raise(IOError, 'log sink unavailable') + + expect do + client.send(:run_cli, 'list', 'arg1') + end.to raise_error(RuntimeError, "storage-cli list failed with exit code 1, output: 'CLI output', error: 'storage unavailable'") + + expect(logger_double).to have_received(:error).with('[ERROR] storage-cli: storage unavailable') end it 'raises BlobstoreError on Open3 failure' do @@ -823,6 +923,41 @@ def build_client(resource_type) end end + describe '#cp_r_to_blobstore' do + it 'does not report interrupted existence checks as cache hits' do + Dir.mktmpdir('resources') do |source_dir| + File.write(File.join(source_dir, 'resource.txt'), 'application resource') + cancellation = Interrupt.new('cancelled check') + log = instance_double(Steno::Logger, info: nil, error: nil, debug: nil, warn: nil) + allow(Steno).to receive(:logger).and_return(log) + allow(Open3).to receive(:capture3).and_raise(cancellation) + + expect do + client.cp_r_to_blobstore(source_dir) + end.to(raise_error { |error| expect(error).to equal(cancellation) }) + + expect(log).to have_received(:info).with( + 'blobstore.cp_r.exists', + hash_including(files_checked: 1, cache_hits: 0, cache_hit_rate: 0.0, error_count: 1, completed: false) + ) + end + end + + it 'retries and propagates failed resource-cache existence checks' do + Dir.mktmpdir('resources') do |source_dir| + File.write(File.join(source_dir, 'resource.txt'), 'application resource') + allow(Open3).to receive(:capture3).and_raise(IOError, 'storage unavailable') + retrying_client = RetryableClient.new(client: client, errors: [StandardError], logger: Steno.logger('cc.blobstore.storage_cli_client')) + + expect do + retrying_client.cp_r_to_blobstore(source_dir) + end.to raise_error(BlobstoreError, /storage unavailable/) + + expect(Open3).to have_received(:capture3).exactly(3).times + end + end + end + describe '#cp_to_blobstore' do let(:logger_double) { double(info: nil, error: nil, debug: nil, warn: nil) } @@ -859,6 +994,64 @@ def build_client(resource_type) source.close! end + it 'does not retry cancellation when completion logging and its fallback warning fail' do + Tempfile.create('src') do |source| + source.write('x' * 1025) + source.flush + cancellation = Interrupt.new('cancelled upload') + allow(Open3).to receive(:capture3).and_raise(cancellation) + allow(logger_double).to receive(:info).with('cp-error', anything).and_raise(IOError, 'log sink unavailable') + allow(logger_double).to receive(:warn).and_raise(IOError, 'log sink unavailable') + retrying_client = RetryableClient.new(client: client, errors: [StandardError], logger: logger_double) + + expect do + retrying_client.cp_to_blobstore(source.path, 'some-key') + end.to(raise_error { |error| expect(error).to equal(cancellation) }) + + expect(Open3).to have_received(:capture3).once + end + end + + it 'does not retry cancellation when metrics and warning logging fail' do + Tempfile.create('src') do |source| + source.write('application package') + source.flush + registry = Prometheus::Client::Registry.new + metrics_updater = VCAP::CloudController::Metrics::PrometheusUpdater.new(registry: registry) + allow(registry.get(:cc_storage_cli_operations_total)).to receive(:increment).and_raise(IOError, 'metric store unavailable') + metrics_client = StorageCliClient.new(directory_key: directory_key, resource_type: resource_type, root_dir: 'bommel', metrics_updater: metrics_updater) + cancellation = Interrupt.new('cancelled upload') + allow(Open3).to receive(:capture3).and_raise(cancellation) + allow(logger_double).to receive(:warn).and_raise(IOError, 'log sink unavailable') + retrying_client = RetryableClient.new(client: metrics_client, errors: [StandardError], logger: logger_double) + + expect do + retrying_client.cp_to_blobstore(source.path, 'some-key') + end.to(raise_error { |error| expect(error).to equal(cancellation) }) + + expect(Open3).to have_received(:capture3).once + end + end + + it 'does not fail or retry successful uploads when all logging fails' do + Tempfile.create('src') do |source| + source.write('application package') + source.flush + status = instance_double(Process::Status, success?: true, exitstatus: 0) + allow(Open3).to receive(:capture3).and_return(['', 'CLI diagnostic', status]) + %i[info error debug warn].each do |level| + allow(logger_double).to receive(level).and_raise(IOError, 'log sink unavailable') + end + retrying_client = RetryableClient.new(client: client, errors: [StandardError], logger: logger_double) + + expect do + retrying_client.cp_to_blobstore(source.path, 'some-key') + end.not_to raise_error + + expect(Open3).to have_received(:capture3).once + end + end + it 'logs cp-skip when file is outside size limits' do source = Tempfile.new('src') source.write('x') diff --git a/spec/unit/lib/cloud_controller/config_spec.rb b/spec/unit/lib/cloud_controller/config_spec.rb index dd91faa8c64..ff061a1ec49 100644 --- a/spec/unit/lib/cloud_controller/config_spec.rb +++ b/spec/unit/lib/cloud_controller/config_spec.rb @@ -82,6 +82,35 @@ module VCAP::CloudController end describe '.load_from_hash' do + %i[api worker clock deployment_updater blobstore_benchmarks].each do |context| + it "accepts a dedicated storage-cli logging level in #{context}" do + config_hash = YAMLConfig.safe_load_file('config/cloud_controller.yml') + config_hash['storage_cli_logging_level'] = 'warn' + + loaded_config = Config.load_from_hash(config_hash, context: context) + + expect(loaded_config.get(:storage_cli_logging_level)).to eq('warn') + end + end + + it 'rejects an invalid storage-cli logging level' do + config_hash = YAMLConfig.safe_load_file('config/cloud_controller.yml') + config_hash['storage_cli_logging_level'] = 'invalid' + + expect do + Config.load_from_hash(config_hash, context: :api) + end.to raise_error(Membrane::SchemaValidationError) + end + + it 'accepts a null storage-cli logging level to inherit global logging' do + config_hash = YAMLConfig.safe_load_file('config/cloud_controller.yml') + config_hash['storage_cli_logging_level'] = nil + + loaded_config = Config.load_from_hash(config_hash, context: :api) + + expect(loaded_config.get(:storage_cli_logging_level)).to be_nil + end + it 'raises error if an empty hash is provided' do expect do Config.load_from_hash({}, context: :api) diff --git a/spec/unit/lib/cloud_controller/metrics/custom_process_id_spec.rb b/spec/unit/lib/cloud_controller/metrics/custom_process_id_spec.rb new file mode 100644 index 00000000000..71dba54bce5 --- /dev/null +++ b/spec/unit/lib/cloud_controller/metrics/custom_process_id_spec.rb @@ -0,0 +1,72 @@ +require 'lightweight_spec_helper' +require 'prometheus/client' +require 'prometheus/client/data_stores/direct_file_store' +require 'cloud_controller/metrics/custom_process_id' + +RSpec.describe 'Local worker metric isolation' do + let(:tmpdir) { Dir.mktmpdir('worker-metrics') } + + around do |example| + original_store = Prometheus::Client.config.data_store + original_index = ENV.fetch('INDEX', nil) + original_process_type = ENV.fetch('PROCESS_TYPE', nil) + Prometheus::Client.config.data_store = Prometheus::Client::DataStores::DirectFileStore.new(dir: tmpdir) + example.run + ensure + Prometheus::Client.config.data_store = original_store + ENV['INDEX'] = original_index + ENV['PROCESS_TYPE'] = original_process_type + FileUtils.remove_entry(tmpdir) + end + + it 'keeps separate metric files for worker indexes sharing the same process ID' do + ENV['PROCESS_TYPE'] = 'puma_worker' + ENV['INDEX'] = '1' + first_registry = Prometheus::Client::Registry.new + first_counter = first_registry.counter(:cc_storage_cli_operations_total, docstring: 'Storage CLI operations', labels: %i[operation exit_code]) + first_counter.increment(labels: { operation: 'put', exit_code: '0' }) + + ENV['INDEX'] = '2' + second_registry = Prometheus::Client::Registry.new + second_counter = second_registry.counter(:cc_storage_cli_operations_total, docstring: 'Storage CLI operations', labels: %i[operation exit_code]) + second_counter.increment(by: 2, labels: { operation: 'put', exit_code: '0' }) + + expect(Dir.glob(File.join(tmpdir, '*.bin')).size).to eq(2) + expect(first_counter.values).to eq({ { operation: 'put', exit_code: '0' } => 3.0 }) + end + + it 'keeps API PIDs separate from equal worker indexes' do + allow(Process).to receive(:pid).and_return(2) + ENV['PROCESS_TYPE'] = 'main' + ENV.delete('INDEX') + api_registry = Prometheus::Client::Registry.new + api_counter = api_registry.counter(:cc_storage_cli_operations_total, docstring: 'Storage CLI operations', labels: %i[operation exit_code]) + api_counter.increment(labels: { operation: 'put', exit_code: '0' }) + + ENV['INDEX'] = '2' + ENV['PROCESS_TYPE'] = 'puma_worker' + worker_registry = Prometheus::Client::Registry.new + worker_counter = worker_registry.counter(:cc_storage_cli_operations_total, docstring: 'Storage CLI operations', labels: %i[operation exit_code]) + worker_counter.increment(by: 2, labels: { operation: 'put', exit_code: '0' }) + + expect(Dir.glob(File.join(tmpdir, '*.bin')).size).to eq(2) + expect(api_counter.values).to eq({ { operation: 'put', exit_code: '0' } => 3.0 }) + end + + it 'reuses existing generic-worker metric files after a restart' do + ENV['PROCESS_TYPE'] = 'cc-worker' + allow(Process).to receive(:pid).and_return(1) + ENV.delete('INDEX') + legacy_registry = Prometheus::Client::Registry.new + legacy_gauge = legacy_registry.gauge(:cc_acquired_db_connections_total, docstring: 'Active DB connections', labels: [:process_type]) + legacy_gauge.set(7, labels: { process_type: 'cc-worker' }) + + ENV['INDEX'] = '1' + restarted_registry = Prometheus::Client::Registry.new + restarted_gauge = restarted_registry.gauge(:cc_acquired_db_connections_total, docstring: 'Active DB connections', labels: [:process_type]) + restarted_gauge.set(0, labels: { process_type: 'cc-worker' }) + + expect(restarted_gauge.values).to eq({ { pid: '1', process_type: 'cc-worker' } => 0.0 }) + expect(Dir.glob(File.join(tmpdir, '*.bin')).size).to eq(1) + end +end diff --git a/spec/unit/lib/cloud_controller/metrics/prometheus_updater_spec.rb b/spec/unit/lib/cloud_controller/metrics/prometheus_updater_spec.rb index bb4260b9399..35727cdc57b 100644 --- a/spec/unit/lib/cloud_controller/metrics/prometheus_updater_spec.rb +++ b/spec/unit/lib/cloud_controller/metrics/prometheus_updater_spec.rb @@ -34,20 +34,9 @@ module VCAP::CloudController::Metrics it_behaves_like 'metric registration based on execution context', VCAP::CloudController::ExecutionContext::DEPLOYMENT_UPDATER, [PrometheusUpdater::DB_CONNECTION_POOL_METRICS, PrometheusUpdater::VITAL_METRICS] - it 'skips metric registration when execution context is nil and PROCESS_TYPE is unset' do + it 'raises error when execution context is nil' do allow(VCAP::CloudController::ExecutionContext).to receive(:from_process_type_env).and_return(nil) - allow(ENV).to receive(:fetch).with('PROCESS_TYPE', nil).and_return(nil) - - expect { updater }.not_to raise_error - expect(prom_client.metrics).to be_empty - end - - it 'skips metric registration when execution context is nil even if PROCESS_TYPE is set' do - allow(VCAP::CloudController::ExecutionContext).to receive(:from_process_type_env).and_return(nil) - allow(ENV).to receive(:fetch).with('PROCESS_TYPE', nil).and_return('mystery') - - expect { updater }.not_to raise_error - expect(prom_client.metrics).to be_empty + expect { updater }.to raise_error('Could not register Prometheus metrics: Unexpected execution context: nil') end context 'when execution context is set' do diff --git a/spec/unit/lib/cloud_controller/packager/local_bits_packer_spec.rb b/spec/unit/lib/cloud_controller/packager/local_bits_packer_spec.rb index d0a1be7a9f4..fb73d7df8ca 100644 --- a/spec/unit/lib/cloud_controller/packager/local_bits_packer_spec.rb +++ b/spec/unit/lib/cloud_controller/packager/local_bits_packer_spec.rb @@ -71,6 +71,17 @@ module CloudController::Packager expect(package_blobstore.exists?(blobstore_key)).to be true end + it 'uploads and cleans up successfully when packer logging fails' do + allow(Steno.logger('cc.packer')).to receive(:info).and_raise(IOError, 'log sink unavailable') + + expect do + packer.send_package_to_blobstore(blobstore_key, uploaded_files_path, cached_files_fingerprints) + end.not_to raise_error + + expect(package_blobstore.exists?(blobstore_key)).to be true + expect(Dir.exist?(File.join(local_tmp_dir, "local_bits_packer-#{blobstore_key}"))).to be false + end + it 'returns the sha1 and sha256 of the uploaded package' do sha1_digester = instance_double(Digester, digest_path: 'expected-sha1') sha256_digester = instance_double(Digester, digest_path: 'expected-sha256') @@ -163,6 +174,16 @@ module CloudController::Packager packer.send_package_to_blobstore(blobstore_key, uploaded_files_path, cached_files_fingerprints) end.to raise_error(CloudController::Errors::ApiError, /invalid/) end + + it 'preserves the archive error and cleans up when logging fails' do + allow(Steno.logger('cc.packer')).to receive(:info).and_raise(IOError, 'log sink unavailable') + + expect do + packer.send_package_to_blobstore(blobstore_key, uploaded_files_path, cached_files_fingerprints) + end.to raise_error(CloudController::Errors::ApiError, /invalid/) + + expect(Dir.exist?(File.join(local_tmp_dir, "local_bits_packer-#{blobstore_key}"))).to be false + end end context 'when there are leftovers from the previous run on the filesystem' do diff --git a/spec/unit/lib/cloud_controller/runner_spec.rb b/spec/unit/lib/cloud_controller/runner_spec.rb index bb593a7da48..687bf9a8072 100644 --- a/spec/unit/lib/cloud_controller/runner_spec.rb +++ b/spec/unit/lib/cloud_controller/runner_spec.rb @@ -1,4 +1,5 @@ require 'spec_helper' +require 'cloud_controller/metrics/custom_process_id' module VCAP::CloudController RSpec.describe Runner do @@ -297,6 +298,47 @@ module VCAP::CloudController subject end + + context 'when a local worker has already opened its metrics' do + let(:metrics_tmpdir) { Dir.mktmpdir('startup-metrics') } + let(:test_config_overrides) { super().merge(directories: { tmpdir: metrics_tmpdir }) } + + around do |example| + original_store = Prometheus::Client.config.data_store + original_index = ENV.fetch('INDEX', nil) + example.run + ensure + Prometheus::Client.config.data_store = original_store + ENV['INDEX'] = original_index + FileUtils.remove_entry(metrics_tmpdir) + end + + it 'keeps worker metric writes visible after API startup resets its own metrics' do + metrics_dir = File.join(metrics_tmpdir, 'prometheus') + Prometheus::Client.config.data_store = Prometheus::Client::DataStores::DirectFileStore.new(dir: metrics_dir) + ENV['PROCESS_TYPE'] = 'main' + ENV.delete('INDEX') + api_registry = Prometheus::Client::Registry.new + api_counter = api_registry.counter(:cc_storage_cli_operations_total, docstring: 'Storage CLI operations', labels: %i[operation exit_code]) + api_counter.increment(by: 3, labels: { operation: 'put', exit_code: '0' }) + + ENV['PROCESS_TYPE'] = 'puma_worker' + ENV['INDEX'] = '1' + worker_registry = Prometheus::Client::Registry.new + worker_counter = worker_registry.counter(:cc_storage_cli_operations_total, docstring: 'Storage CLI operations', labels: %i[operation exit_code]) + worker_counter.increment(labels: { operation: 'put', exit_code: '0' }) + ENV.delete('INDEX') + allow_any_instance_of(ApiMetricsWebserver).to receive(:start) + + subject + + ENV['PROCESS_TYPE'] = 'puma_worker' + ENV['INDEX'] = '1' + worker_counter.increment(labels: { operation: 'put', exit_code: '0' }) + + expect(worker_counter.values).to eq({ { operation: 'put', exit_code: '0' } => 2.0 }) + end + end end end end