001package io.prometheus.metrics.config;
002
003import io.prometheus.metrics.annotations.StableApi;
004import java.io.IOException;
005import java.io.InputStream;
006import java.nio.file.Files;
007import java.nio.file.Paths;
008import java.util.HashMap;
009import java.util.Map;
010import java.util.Properties;
011import java.util.Set;
012
013/**
014 * Loads Prometheus client configuration from supported property sources.
015 *
016 * <p>Configuration is read from a classpath {@code prometheus.properties} file, an optional
017 * properties file selected by {@code prometheus.config} or {@code PROMETHEUS_CONFIG}, Java system
018 * properties, {@code IO_PROMETHEUS_*} environment variables, and properties supplied explicitly to
019 * {@link #load(Map)}. Precedence is explicit properties, environment variables, system properties,
020 * the selected file, then the classpath file. {@code PROMETHEUS_CONFIG}, when set, takes precedence
021 * over the {@code prometheus.config} system property when selecting the optional file. Property
022 * names use dot-separated keys such as {@code io.prometheus.exporter.include_created_timestamps};
023 * environment variable names use underscores, such as {@code
024 * IO_PROMETHEUS_EXPORTER_INCLUDE_CREATED_TIMESTAMPS}.
025 *
026 * <p>Unrecognized properties under the {@code io.prometheus} or {@code io_prometheus} prefixes
027 * cause configuration loading to fail, which can help identify misspelled property names.
028 */
029@StableApi
030public class PrometheusPropertiesLoader {
031
032  /** See {@link PrometheusProperties#get()}. */
033  public static PrometheusProperties load() throws PrometheusPropertiesException {
034    return load(new Properties());
035  }
036
037  /**
038   * Loads configuration, using the supplied properties in addition to the standard property
039   * sources. Values in {@code externalProperties} take precedence over environment variables,
040   * system properties, and properties files.
041   *
042   * @param externalProperties properties supplied by the caller
043   * @return the loaded configuration
044   * @throws PrometheusPropertiesException if the selected properties file cannot be read or the
045   *     configuration contains an invalid or unrecognized property
046   */
047  public static PrometheusProperties load(Map<Object, Object> externalProperties)
048      throws PrometheusPropertiesException {
049    PropertySource propertySource = loadProperties(externalProperties);
050    PrometheusProperties.MetricPropertiesMap metricsConfigs = loadMetricsConfigs(propertySource);
051    MetricsProperties defaultMetricsProperties =
052        MetricsProperties.load("io.prometheus.metrics", propertySource);
053    ExemplarsProperties exemplarConfig = ExemplarsProperties.load(propertySource);
054    ExporterProperties exporterProperties = ExporterProperties.load(propertySource);
055    ExporterFilterProperties exporterFilterProperties =
056        ExporterFilterProperties.load(propertySource);
057    ExporterHttpServerProperties exporterHttpServerProperties =
058        ExporterHttpServerProperties.load(propertySource);
059    ExporterPushgatewayProperties exporterPushgatewayProperties =
060        ExporterPushgatewayProperties.load(propertySource);
061    ExporterOpenTelemetryProperties exporterOpenTelemetryProperties =
062        ExporterOpenTelemetryProperties.load(propertySource);
063    OpenMetrics2Properties openMetrics2Properties = OpenMetrics2Properties.load(propertySource);
064    validateAllPropertiesProcessed(propertySource);
065    return new PrometheusProperties(
066        defaultMetricsProperties,
067        metricsConfigs,
068        exemplarConfig,
069        exporterProperties,
070        exporterFilterProperties,
071        exporterHttpServerProperties,
072        exporterPushgatewayProperties,
073        exporterOpenTelemetryProperties,
074        openMetrics2Properties);
075  }
076
077  // This will remove entries from propertySource when they are processed.
078  static PrometheusProperties.MetricPropertiesMap loadMetricsConfigs(
079      PropertySource propertySource) {
080    PrometheusProperties.MetricPropertiesMap result =
081        new PrometheusProperties.MetricPropertiesMap();
082    // Note that the metric name in the properties file must be as exposed in the Prometheus
083    // exposition formats,
084    // i.e. all dots replaced with underscores.
085
086    // Get a snapshot of all keys for pattern matching. Entries will be removed
087    // when MetricsProperties.load(...) is called.
088    Set<String> propertyNames = propertySource.getAllKeys();
089    for (String propertyName : propertyNames) {
090      String metricName = null;
091
092      if (propertyName.startsWith("io.prometheus.metrics.")) {
093        // Dot-separated format (from regular properties, system properties, or files)
094        String remainder = propertyName.substring("io.prometheus.metrics.".length());
095        // Try to match against known property suffixes
096        for (String suffix : MetricsProperties.PROPERTY_SUFFIXES) {
097          if (remainder.endsWith("." + suffix)) {
098            // Metric name in dot format, convert dots to underscores for exposition format
099            metricName =
100                remainder.substring(0, remainder.length() - suffix.length() - 1).replace(".", "_");
101            break;
102          }
103        }
104      } else if (propertyName.startsWith("io_prometheus_metrics_")) {
105        // Underscore-separated format (from environment variables)
106        String remainder = propertyName.substring("io_prometheus_metrics_".length());
107        // Try to match against known property suffixes
108        for (String suffix : MetricsProperties.PROPERTY_SUFFIXES) {
109          if (remainder.endsWith("_" + suffix)) {
110            metricName = remainder.substring(0, remainder.length() - suffix.length() - 1);
111            break;
112          }
113        }
114      }
115
116      if (metricName != null && result.get(metricName) == null) {
117        result.put(
118            metricName,
119            MetricsProperties.load("io.prometheus.metrics." + metricName, propertySource));
120      }
121    }
122    return result;
123  }
124
125  // If there are properties left starting with io.prometheus it's likely a typo,
126  // because we didn't use that property.
127  // Throw a config error to let the user know that this property doesn't exist.
128  private static void validateAllPropertiesProcessed(PropertySource propertySource) {
129    for (String key : propertySource.getRemainingKeys()) {
130      if (key.startsWith("io.prometheus") || key.startsWith("io_prometheus")) {
131        throw new PrometheusPropertiesException(key + ": Unknown property");
132      }
133    }
134  }
135
136  private static PropertySource loadProperties(Map<Object, Object> externalProperties) {
137    // Regular properties (lowest priority): classpath, file, system properties
138    Map<Object, Object> regularProperties = new HashMap<>();
139    // Normalize all properties at load time to handle camelCase in files for backward compatibility
140    normalizeAndPutAll(regularProperties, loadPropertiesFromClasspath());
141    normalizeAndPutAll(
142        regularProperties,
143        loadPropertiesFromFile()); // overriding the entries from the classpath file
144    // overriding the entries from the properties file
145    // copy System properties to avoid ConcurrentModificationException
146    // normalize camelCase system properties to snake_case for backward compatibility
147    System.getProperties().stringPropertyNames().stream()
148        .filter(key -> key.startsWith("io.prometheus"))
149        .forEach(key -> regularProperties.put(normalizePropertyKey(key), System.getProperty(key)));
150
151    // Environment variables (second priority): just lowercase, keep underscores
152    Map<Object, Object> envVarProperties = loadPropertiesFromEnvironment();
153
154    // External properties (highest priority): normalize camelCase for backward compatibility
155    Map<Object, Object> normalizedExternalProperties = new HashMap<>();
156    externalProperties.forEach(
157        (key, value) ->
158            normalizedExternalProperties.put(normalizePropertyKey(key.toString()), value));
159
160    return new PropertySource(normalizedExternalProperties, envVarProperties, regularProperties);
161  }
162
163  private static void normalizeAndPutAll(Map<Object, Object> target, Map<Object, Object> source) {
164    source.forEach((key, value) -> target.put(normalizePropertyKey(key.toString()), value));
165  }
166
167  private static Properties loadPropertiesFromClasspath() {
168    Properties properties = new Properties();
169    try (InputStream stream =
170        Thread.currentThread()
171            .getContextClassLoader()
172            .getResourceAsStream("prometheus.properties")) {
173      properties.load(stream);
174    } catch (Exception ignored) {
175      // No properties file found on the classpath.
176    }
177    return properties;
178  }
179
180  private static Properties loadPropertiesFromFile() throws PrometheusPropertiesException {
181    Properties properties = new Properties();
182    String path = System.getProperty("prometheus.config");
183    if (System.getenv("PROMETHEUS_CONFIG") != null) {
184      path = System.getenv("PROMETHEUS_CONFIG");
185    }
186    if (path != null) {
187      try (InputStream stream = Files.newInputStream(Paths.get(path))) {
188        properties.load(stream);
189      } catch (IOException e) {
190        throw new PrometheusPropertiesException("Failed to read Prometheus properties file.", e);
191      }
192    }
193    return properties;
194  }
195
196  /**
197   * Load properties from environment variables.
198   *
199   * <p>Environment variables are converted to lowercase but keep underscores as-is. For example,
200   * the environment variable IO_PROMETHEUS_METRICS_EXEMPLARS_ENABLED becomes
201   * io_prometheus_metrics_exemplars_enabled.
202   *
203   * <p>The transformation to dot notation happens at access time in PropertySource.
204   *
205   * <p>Only environment variables starting with IO_PROMETHEUS are considered.
206   *
207   * @return properties loaded from environment variables (with lowercase keys and underscores)
208   */
209  private static Map<Object, Object> loadPropertiesFromEnvironment() {
210    Map<Object, Object> properties = new HashMap<>();
211    System.getenv()
212        .forEach(
213            (key, value) -> {
214              if (key.startsWith("IO_PROMETHEUS")) {
215                String normalizedKey = key.toLowerCase(java.util.Locale.ROOT);
216                properties.put(normalizedKey, value);
217              }
218            });
219    return properties;
220  }
221
222  /**
223   * Normalize a property key for consistent lookup.
224   *
225   * <p>Converts camelCase property keys to snake_case. This allows both snake_case (preferred) and
226   * camelCase (deprecated) property names to be used.
227   *
228   * <p>For example: exemplarsEnabled → exemplars_enabled exemplars_enabled → exemplars_enabled
229   * (unchanged)
230   *
231   * <p>In metric-specific keys like {@code io.prometheus.metrics.<metric>.<property>} only the
232   * property name is normalized, because metric names are case-sensitive.
233   *
234   * @param key the property key
235   * @return the normalized property key
236   */
237  static String normalizePropertyKey(String key) {
238    String metricsPrefix = "io.prometheus.metrics.";
239    int lastDot = key.lastIndexOf('.');
240    if (key.startsWith(metricsPrefix) && lastDot >= metricsPrefix.length()) {
241      return key.substring(0, lastDot + 1) + normalizePropertyKey(key.substring(lastDot + 1));
242    }
243    // Insert underscores before uppercase letters to convert camelCase to snake_case
244    String withUnderscores = key.replaceAll("([a-z])([A-Z])", "$1_$2");
245    return withUnderscores.toLowerCase(java.util.Locale.ROOT);
246  }
247}