diff --git a/lib/cloud_controller/blobstore/base_client.rb b/lib/cloud_controller/blobstore/base_client.rb index 585d934f543..3c4a2b41a7d 100644 --- a/lib/cloud_controller/blobstore/base_client.rb +++ b/lib/cloud_controller/blobstore/base_client.rb @@ -5,15 +5,34 @@ 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 + counters = new_cp_r_counters + 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) rescue nil # rubocop:disable Style/RescueModifier + 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 + + sha1 = cp_r_digest_file(path, counters) + + next if cp_r_check_exists(sha1, counters) + + cp_r_upload_file(path, sha1, counters) + end + traversal_completed = true + ensure + log_cp_r_phases(counters, traversal_completed) end end @@ -23,6 +42,79 @@ def cp_to_blobstore(_, _) private + 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 } + end + + def cp_r_digest_file(path, counters) + t = Time.now.utc + counters[:digest_count] += 1 + 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 + # A check stays unresolved unless it returns a result, including on cancellation. + counters[:exists_errors] += 1 + 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 + + 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) rescue nil # rubocop:disable Style/RescueModifier + log_exists_phase(ctrs, completed) + ua = ctrs[:upload_attempts] + logger.info('blobstore.cp_r.upload', + files_to_upload: ua, + files_uploaded: ctrs[:upload_count], + files_failed: ua - ctrs[:upload_count], + duration_seconds: ctrs[:upload_duration], + completed: completed) rescue nil # rubocop:disable Style/RescueModifier + 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), + error_count: errors, + completed: completed) rescue nil # rubocop:disable Style/RescueModifier + 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) @@ -33,6 +125,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/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..1926577a07f 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,53 @@ 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 + 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 - File.open(source_path) do |file| - size = file.size - next unless within_limits?(size) - - run_cli('put', source_path, partitioned_key(destination_key)) - log_entry = 'cp-finish' + begin + File.open(source_path) do |file| + size = file.size + 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' + 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 metric_emitted + raise + rescue Exception # rubocop:disable Lint/RescueException + log_entry = 'cp-error' + raise + ensure + logger.info(log_entry, + destination_key: destination_key, + duration_seconds: Time.now.utc - start, + size: size) rescue nil # rubocop:disable Style/RescueModifier end + end - duration = Time.now.utc - start - logger.info(log_entry, - destination_key: destination_key, - duration_seconds: duration, - size: size) + def safe_emit_metrics(operation, exit_code, duration, context, blob_size: nil) + 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("storage-cli metrics failed in #{context}: #{e.inspect}") rescue nil # rubocop:disable Style/RescueModifier end def cp_file_between_keys(source_key, destination_key) @@ -170,25 +201,119 @@ def additional_flags flags_string.split end - def run_cli(command, *args, allow_exit_code_three: false) - logger.debug("running storage-cli: #{@cli_path} -s #{@storage_type} -c #{@config_file} #{additional_flags.join(' ')} #{command} #{args.join(' ')}") - + 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 - 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 + flags = additional_flags + 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) + 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 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 - unless status.success? || (allow_exit_code_three && status.exitstatus == 3) - raise "storage-cli #{command} failed with exit code #{status.exitstatus}, output: '#{stdout}', error: '#{stderr}'" + 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 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) + 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') + 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 + + 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 'list' + fields['prefix'] = args[0] + when 'delete-recursive' + fields['path'] = args[0] + end + fields + 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 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' @@ -228,6 +353,13 @@ def tmpdir def logger @logger ||= Steno.logger('cc.blobstore.storage_cli_client') end + + 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 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 fc03f27e68a..71678797131 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 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); ' \ + 'exit_code=-4: upload skipped locally because blob size is outside configured limits; ' \ + '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 = [ + { 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 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, + 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 }, @@ -79,7 +112,6 @@ def initialize(registry: Prometheus::Client.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 initialize_cc_db_connection_pool_timeouts_total end @@ -92,6 +124,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 +132,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 +244,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 +292,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..9680984e0ac 100644 --- a/lib/cloud_controller/packager/local_bits_packer.rb +++ b/lib/cloud_controller/packager/local_bits_packer.rb @@ -20,10 +20,16 @@ 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) - 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) rescue nil # rubocop:disable Style/RescueModifier + end { sha1: Digester.new.digest_path(complete_package_path), @@ -31,6 +37,7 @@ def send_package_to_blobstore(blobstore_key, uploaded_package_zip, cached_files_ } ensure 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/cloud_controller/packager/shared_bits_packer.rb b/lib/cloud_controller/packager/shared_bits_packer.rb index 8182a3c8c38..6f39b7451da 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) rescue nil # rubocop:disable Style/RescueModifier + 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) rescue nil # rubocop:disable Style/RescueModifier + 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, 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 - 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) rescue nil # rubocop:disable Style/RescueModifier + 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/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/lib/tasks/jobs.rake b/lib/tasks/jobs.rake index 671e4ec6b05..74fb469dd68 100644 --- a/lib/tasks/jobs.rake +++ b/lib/tasks/jobs.rake @@ -32,6 +32,13 @@ namespace :jobs do args.with_defaults(name: queue) 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) + 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..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 @@ -104,6 +104,80 @@ module Blobstore end 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) + + 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(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 + 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 '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) + 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.to raise_error(StandardError, 'exists failed') + + expect(logger).to have_received(:info).with('blobstore.cp_r.exists', + 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 + 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(files_scanned: 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..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 @@ -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! } @@ -351,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)]) } @@ -494,17 +578,88 @@ 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 'returns output and status on success' do + 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 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', + 'blob_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(: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 + 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 + status = instance_double(Process::Status, success?: true, exitstatus: 0) + 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 @@ -523,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 @@ -530,6 +699,526 @@ 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 = double('metrics_updater') + 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 = double('metrics_updater') + 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 + ) + 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 '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, + 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 { 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 + let(:metrics_updater) { double('metrics_updater') } + 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 '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]) + + # 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 + + 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 + + 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) } + + 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 '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') + 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 = 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) + + 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 = double('metrics_updater') + 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 = double('metrics_updater') + 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 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 + + metrics_updater = double('metrics_updater') + 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([]) + + 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 'does not double-emit when Open3 raises Interrupt after cli is called' do + source = Tempfile.new('src') + source.write('x' * 1025) + source.flush + + metrics_updater = double('metrics_updater') + 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(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).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 end end end 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 b69d38929ac..35727cdc57b 100644 --- a/spec/unit/lib/cloud_controller/metrics/prometheus_updater_spec.rb +++ b/spec/unit/lib/cloud_controller/metrics/prometheus_updater_spec.rb @@ -23,11 +23,13 @@ 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] @@ -275,5 +277,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..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 @@ -368,6 +389,28 @@ 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, :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, :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 end 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