The easy-to-use open source Business Intelligence and Embedded Analytics tool that lets everyone work with data :bar_chart:
TypeScript analyticsbibusiness-intelligencebusinessintelligenceclojuredashboarddatadata-analysisdata-visualizationdatabasemetabasemysqlpostgrespostgresqlreportingslacksql-editorvisualization
Added MB_MONITOR_PERFORMANCE option (#69298)
Nathan Voxland89bb889883ba
diff --git a/src/metabase/cmd/resources/other-env-vars.md b/src/metabase/cmd/resources/other-env-vars.mdindex dc0712fb45d..590704352bb 100644--- a/src/metabase/cmd/resources/other-env-vars.md+++ b/src/metabase/cmd/resources/other-env-vars.md@@ -320,6 +320,20 @@ Default: TrueWhether to include the Sample Database in your Metabase. To exclude the Sample Database, set `MB_LOAD_SAMPLE_CONTENT=false`.+### `MB_MONITOR_PERFORMANCE`++Type: string<br>+Default: `""`++When set, starts a Java Flight Recorder (JFR) recording at startup that can be analyzed with JDK Mission Control or other JFR tools.++- `"true"` generates a timestamped output file like `metabase-2026_01_15.jfr`+- Any other non-empty value is used as the output filename (`.jfr` extension is appended if missing)+- `""` or `"false"` disables monitoring (the default)++The performance recording stores only method signature calls and other code execution metrics.+It does not store any sensitive information such as environment variables, system properties, or other machine information.+### `MB_NO_SURVEYS`Type: boolean<br>diff --git a/src/metabase/config/core.clj b/src/metabase/config/core.cljindex 91508babe77..4cba8c00294 100644--- a/src/metabase/config/core.clj+++ b/src/metabase/config/core.clj@@ -63,7 +63,8 @@:mb-emoji-in-logs (str (not is-windows?)) ; disable them by default when running on Windows. Otherwise they're enabled:mb-log-team-attribution "false":mb-qp-cache-backend "db"- :mb-jetty-async-response-timeout (str (* 10 60 1000))}) ; 10m+ :mb-jetty-async-response-timeout (str (* 10 60 1000)) ; 10m+ :mb-monitor-performance ""});; separate map for EE stuff so merge conflicts aren't annoying.(def ^:private ee-app-defaultsdiff --git a/src/metabase/core/core.clj b/src/metabase/core/core.cljindex bcc5fca843a..14499530da1 100644--- a/src/metabase/core/core.clj+++ b/src/metabase/core/core.clj@@ -13,6 +13,7 @@[metabase.config.core :as config][metabase.core.config-from-file :as config-from-file][metabase.core.init]+ [metabase.core.perf :as perf][metabase.driver.h2][metabase.driver.mysql][metabase.driver.postgres]@@ -110,6 +111,7 @@;; This timeout was chosen based on a 30s default termination grace period in Kubernetes.(let [timeout-seconds 20](mdb/release-migration-locks! timeout-seconds))+ (perf/stop-monitoring!)(log/info "Metabase Shutdown COMPLETE"))(defenterprise ensure-audit-db-installed!@@ -157,6 +159,7 @@[](log/infof "Starting Metabase version %s ..." config/mb-version-string)(log/infof "System info:\n %s" (u/pprint-to-str (u.system-info/system-info)))+ (perf/maybe-enable-monitoring!)(init-signal-logging!)(init-status/set-progress! 0.1);; First of all, lets register a shutdown hook that will tidy things up for us on app exitdiff --git a/src/metabase/core/perf.clj b/src/metabase/core/perf.cljnew file mode 100644index 00000000000..e8a5b3e6a91--- /dev/null+++ b/src/metabase/core/perf.clj@@ -0,0 +1,109 @@+(ns metabase.core.perf+ "Java Flight Recorder (JFR) performance monitoring support.+ When `MB_MONITOR_PERFORMANCE` is set, starts a JFR recording at startup+ that can be analyzed with JDK Mission Control or other JFR tools."+ (:require+ [clojure.string :as str]+ [metabase.config.core :as config]+ [metabase.util.log :as log])+ (:import+ (java.nio.file Files)+ (java.nio.file.attribute FileAttribute)+ (java.time LocalDate)+ (java.time.format DateTimeFormatter)+ (java.util.concurrent ScheduledThreadPoolExecutor TimeUnit)+ (jdk.jfr Configuration Recording)))++(set! *warn-on-reflection* true)++(defonce ^:private recording-atom (atom nil))+(defonce ^:private dump-executor-atom (atom nil))++(def ^:private sensitive-events+ "JFR events that may contain sensitive information and should be disabled."+ ["jdk.InitialEnvironmentVariable"+ "jdk.InitialSystemProperty"+ "jdk.SystemProcess"+ "jdk.JVMInformation"])++(defn- resolve-output-path+ "Determine the output path for the JFR recording file.+ - `\"true\"` generates a timestamped filename like `metabase-2026_01_15.jfr`+ - Any other value is used as a filename (`.jfr` is appended if missing)"+ ^java.nio.file.Path [setting-value]+ (let [filename (if (= "true" setting-value)+ (str "metabase-"+ (.format (LocalDate/now)+ (DateTimeFormatter/ofPattern "yyyy_MM_dd"))+ ".jfr")+ (if (str/ends-with? setting-value ".jfr")+ setting-value+ (str setting-value ".jfr")))]+ (.. (java.nio.file.Path/of filename (into-array String []))+ (toAbsolutePath))))++(defn- disable-sensitive-events!+ "Disable JFR events that may contain sensitive information."+ [^Recording recording]+ (doseq [^String event-name sensitive-events]+ (.disable recording event-name)))++(defn- start-periodic-dump!+ "Starts a background thread that periodically dumps the JFR recording to disk.+ This ensures data survives hard kills (SIGKILL, OOM) where shutdown hooks don't run."+ [^Recording recording ^java.nio.file.Path output-path interval-seconds]+ (let [executor (ScheduledThreadPoolExecutor. 1+ (reify java.util.concurrent.ThreadFactory+ (newThread [_ r]+ (doto (Thread. r "jfr-periodic-dump")+ (.setDaemon true)))))]+ (.scheduleAtFixedRate executor+ ^Runnable (fn [] (.dump recording output-path))+ (long interval-seconds)+ (long interval-seconds)+ TimeUnit/SECONDS)+ (reset! dump-executor-atom executor)))++(defn maybe-enable-monitoring!+ "If `MB_MONITOR_PERFORMANCE` is set, starts a JFR recording.+ - Value `\"true\"` auto-generates a timestamped filename+ - Any other non-empty/non-`\"false\"` string is used as filename+ - Recording uses the `\"profile\"` configuration with `dumpOnExit=true`"+ []+ (try+ (let [setting (config/config-str :mb-monitor-performance)]+ (when (and (not (str/blank? setting))+ (not= "false" setting))+ (let [output-path (resolve-output-path setting)+ parent-dir (.getParent output-path)+ config (Configuration/getConfiguration "profile")+ recording (Recording. config)]+ (when parent-dir+ (Files/createDirectories parent-dir (into-array FileAttribute [])))+ (.setToDisk recording true)+ (.setDumpOnExit recording true)+ (.setMaxSize recording 0)+ (.setMaxAge recording nil)+ (.setDestination recording output-path)+ (disable-sensitive-events! recording)+ (.start recording)+ (reset! recording-atom recording)+ (start-periodic-dump! recording output-path 60)+ (log/infof "Performance monitoring started. Output file: %s" (str output-path)))))+ (catch Throwable e+ (log/warn e "Failed to start performance monitoring"))))++(defn stop-monitoring!+ "Stops and closes the JFR recording if one is active."+ []+ (when-let [^Recording recording @recording-atom]+ (try+ (when-let [^ScheduledThreadPoolExecutor executor @dump-executor-atom]+ (.shutdownNow executor)+ (reset! dump-executor-atom nil))+ (.stop recording)+ (.close recording)+ (reset! recording-atom nil)+ (log/info "Performance monitoring stopped")+ (catch Throwable e+ (log/warn e "Error stopping performance monitoring")))))diff --git a/test/metabase/core/perf_test.clj b/test/metabase/core/perf_test.cljnew file mode 100644index 00000000000..e34e1a21293--- /dev/null+++ b/test/metabase/core/perf_test.clj@@ -0,0 +1,21 @@+(ns metabase.core.perf-test+ (:require+ [clojure.test :refer [deftest is testing]]+ [metabase.core.perf :as perf])+ (:import+ (java.nio.file Path)))++(set! *warn-on-reflection* true)++(deftest ^:parallel resolve-output-path-test+ (testing "\"true\" generates a timestamped filename"+ (let [^Path path (#'perf/resolve-output-path "true")]+ (is (instance? Path path))+ (is (.isAbsolute path))+ (is (re-matches #".*metabase-\d{4}_\d{2}_\d{2}\.jfr" (str path)))))+ (testing "custom filename is used as-is when it has .jfr extension"+ (let [^Path path (#'perf/resolve-output-path "my-profile.jfr")]+ (is (= "my-profile.jfr" (str (.getFileName path))))))+ (testing ".jfr extension is appended when missing"+ (let [^Path path (#'perf/resolve-output-path "my-profile")]+ (is (= "my-profile.jfr" (str (.getFileName path)))))))