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
Improving git management for remote sync (#65249)
Nathan Voxland8f3730dd45e2
diff --git a/.clj-kondo/config/modules/config.edn b/.clj-kondo/config/modules/config.ednindex 81ebd29e725..cb045e42545 100644--- a/.clj-kondo/config/modules/config.edn+++ b/.clj-kondo/config/modules/config.edn@@ -1917,7 +1917,6 @@modelspremium-featuressettings- startuptasktask-historyutildiff --git a/enterprise/backend/src/metabase_enterprise/remote_sync/impl.clj b/enterprise/backend/src/metabase_enterprise/remote_sync/impl.cljindex 1c9fdd24d59..3e3083a4bca 100644--- a/enterprise/backend/src/metabase_enterprise/remote_sync/impl.clj+++ b/enterprise/backend/src/metabase_enterprise/remote_sync/impl.clj@@ -305,6 +305,8 @@(defn finish-remote-config!"Based on the current configuration, fill in any missing settings and finalize remote sync setup.+ Will attempt, import the remote collection if no remote-collection exists locally or you are in production mode.+Returns the async-task id if an async task was started, otherwise nil."[](if (settings/remote-sync-enabled)diff --git a/enterprise/backend/src/metabase_enterprise/remote_sync/init.clj b/enterprise/backend/src/metabase_enterprise/remote_sync/init.cljindex e8b75977aea..6d5b3d3f4c2 100644--- a/enterprise/backend/src/metabase_enterprise/remote_sync/init.clj+++ b/enterprise/backend/src/metabase_enterprise/remote_sync/init.clj@@ -2,12 +2,9 @@(:require[clojure.java.io :as io][metabase-enterprise.remote-sync.events]- [metabase-enterprise.remote-sync.impl :as impl]- [metabase-enterprise.remote-sync.settings :as settings]+ [metabase-enterprise.remote-sync.settings][metabase-enterprise.remote-sync.task.import]- [metabase-enterprise.remote-sync.task.table-cleanup]- [metabase.startup.core :as startup]- [metabase.util.log :as log])+ [metabase-enterprise.remote-sync.task.table-cleanup])(:import(org.eclipse.jgit.storage.file FileBasedConfig)(org.eclipse.jgit.util FS SystemReader SystemReader$Delegate)))@@ -36,12 +33,3 @@(save [] nil))))))(SystemReader/setInstance (create-isolated-system-reader))--(defmethod startup/def-startup-logic! ::RemoteSyncInit [_]- ;; Initialize Remote Sync features- (future- (try- (settings/check-git-settings!)- (impl/finish-remote-config!)- (catch Throwable e- (log/error e "Error during Remote Sync initialization: " (ex-message e))))))diff --git a/enterprise/backend/src/metabase_enterprise/remote_sync/settings.clj b/enterprise/backend/src/metabase_enterprise/remote_sync/settings.cljindex bb6aac788f2..e9c126a6c17 100644--- a/enterprise/backend/src/metabase_enterprise/remote_sync/settings.clj+++ b/enterprise/backend/src/metabase_enterprise/remote_sync/settings.clj@@ -23,7 +23,8 @@:type :string:visibility :admin:encryption :no- :export? false)+ :export? false+ :can-read-from-env? false)(defsetting remote-sync-token(deferred-tru "An Authorization Bearer token allowing access to the git repo over HTTP")@@ -33,14 +34,16 @@:export? false:sensitive? true:encryption :when-encryption-key-set- :audit :getter)+ :audit :getter+ :can-read-from-env? false)(defsetting remote-sync-url(deferred-tru "The location of your git repository, e.g. https://github.com/acme-inco/metabase.git"):type :string:visibility :admin:encryption :no- :export? false)+ :export? false+ :can-read-from-env? false)(defsetting remote-sync-type(deferred-tru "Git synchronization type - :development or :production")@@ -56,7 +59,8 @@(throw (ex-info "Remote-sync-type set to an unsupported value"{:value new-value:options (seq valid-types)})))]- (setting/set-value-of-type! :keyword :remote-sync-type value))))+ (setting/set-value-of-type! :keyword :remote-sync-type value)))+ :can-read-from-env? false)(defsetting remote-sync-auto-import(deferred-tru "Whether to automatically import from the remote git repository. Only applies if remote-sync-type is :production.")@@ -104,10 +108,7 @@(let [source (git/git-source remote-sync-url "HEAD" remote-sync-token)](when (and (= :production remote-sync-type) (not (str/blank? remote-sync-branch)) (not (some #{remote-sync-branch} (git/branches source))))- (throw (ex-info "Invalid branch name" {:url remote-sync-url :branch remote-sync-branch})))- (git/fetch! source)- (when-not (git/has-data? source)- (throw (ex-info "Cannot connect to an uninitialized repository" {:url remote-sync-url}))))))+ (throw (ex-info "Invalid branch name" {:url remote-sync-url :branch remote-sync-branch}))))))(defn check-and-update-remote-settings!"Validates and updates git sync settings in the application database.diff --git a/enterprise/backend/src/metabase_enterprise/remote_sync/source.clj b/enterprise/backend/src/metabase_enterprise/remote_sync/source.cljindex 3c76eb4eef3..36b44af860e 100644--- a/enterprise/backend/src/metabase_enterprise/remote_sync/source.clj+++ b/enterprise/backend/src/metabase_enterprise/remote_sync/source.clj@@ -58,9 +58,6 @@(methodical/defmethod source.p/->ingestable GitSource[{:keys [remote-url] :as source} opts](git/fetch! source)- (when-not (git/has-data? source)- (throw (ex-info (str "Cannot connect to uninitialized repository " remote-url)- {:url remote-url})))(if-let [commit-ref (git/commit-sha source)](next-method (assoc source :commit-ish commit-ref) opts)(throw (ex-info (str "Unable to find branch " (:commit-ish source) " to read from") {:url remote-urldiff --git a/enterprise/backend/src/metabase_enterprise/remote_sync/source/git.clj b/enterprise/backend/src/metabase_enterprise/remote_sync/source/git.cljindex 421dc62ade3..b50a3716fca 100644--- a/enterprise/backend/src/metabase_enterprise/remote_sync/source/git.clj+++ b/enterprise/backend/src/metabase_enterprise/remote_sync/source/git.clj@@ -9,6 +9,7 @@[metabase.util :as u][metabase.util.log :as log])(:import+ (java.io File)(org.apache.commons.io FileUtils)(org.eclipse.jgit.api Git GitCommand TransportCommand)(org.eclipse.jgit.dircache DirCache DirCacheEntry)@@ -75,18 +76,10 @@(u/prog1 (call-remote-command (.fetch git) git-source))(log/info "Successfully fetched repository")))-(defn- existing-git-repo [^java.io.File dir {:keys [^String token]}]- (io/make-parents dir)- (try- (when (.exists dir)- (u/prog1 (Git/open dir)- (fetch! {:git <> :token token})))- (catch Exception e- (log/warnf e "Existing git repo at %s is not configured correctly. Deleting it" dir)- (FileUtils/deleteDirectory dir)- nil)))+(defn- repo-path [{:keys [^String url ^String token]}]+ (io/file (System/getProperty "java.io.tmpdir") "metabase-git" (-> (str/join ":" [url token]) buddy-hash/sha1 codecs/bytes->hex)))-(defn clone-repository!+(defn- clone-repository!"Clones a git repository to a temporary directory using JGit.Takes a map with :url (the git repository URL) and optional :token (authentication token for private@@ -94,22 +87,27 @@directory and is valid, returns the existing repository after fetching.Throws ExceptionInfo if cloning fails due to network issues, invalid URL, authentication failure, etc."- [{:keys [^String url ^String token] :as args}]- (let [dir (io/file (System/getProperty "java.io.tmpdir") "metabase-git" (-> (str/join ":" [url token]) buddy-hash/sha1 codecs/bytes->hex))]- (if-let [repo (existing-git-repo dir args)]- repo- (try- (log/info "Cloning repository" {:url url :dir dir})- (u/prog1 (call-remote-command (-> (Git/cloneRepository)- (.setDirectory dir)- (.setURI url)- (.setBare true)) {:token token})- (log/info "Successfully cloned repository" {:dir dir}))- (catch Exception e- (throw (ex-info (format "Failed to clone git repository: %s" (ex-message e))- {:url url- :dir dir- :error (.getMessage e)} e)))))))+ [repo-path {:keys [^String url ^String token]}]+ (log/info "Cloning repository" {:url url :repo-path repo-path})+ (io/make-parents repo-path)+ (try+ (u/prog1 (call-remote-command (-> (Git/cloneRepository)+ (.setDirectory repo-path)+ (.setURI url)+ (.setBare true)) {:token token})+ (log/info "Successfully cloned repository" {:repo-path repo-path}))+ (catch Exception e+ (throw (ex-info (format "Failed to clone git repository: %s" (ex-message e))+ {:url url+ :repo-path repo-path+ :error (.getMessage e)} e)))))++(defn- open-jgit [^File repo-path args]+ (if (.exists repo-path)+ (do+ (log/debugf "Opening existing at %" repo-path)+ (Git/open repo-path))+ (clone-repository! repo-path args)))(defn commit-sha"Resolves a branch name or commit-ish string to a full commit reference SHA.@@ -144,15 +142,6 @@:id (.name (.abbreviate commit 8)):parent (when (< 0 (.getParentCount commit)) (.name (.abbreviate (.getParent commit 0) 8)))}) log-result)))))-(defn has-data?- "Checks if the git repository has any commits/data.-- Takes a source map containing a :git Git instance and :commit-ish to check for data.-- Returns true if the repository has at least one commit, false otherwise."- [{:keys [^Git git]}]- (< 0 (count (call-command (.branchList git)))))-(defn list-files"Lists all files in the git repository at the current commit.@@ -314,6 +303,15 @@(map #(str/replace-first (.getName ^Ref %) "refs/heads/" ""))sort))+(defn has-data?+ "Checks if the remote git repository has any commits/data.++ Takes a source map to check for data.++ Returns true if the repository has at least one commit, false otherwise."+ [source]+ (< 0 (count (branches source))))+(defn- delete-branches-without-remote![{:keys [^Git git] :as source}](let [remote-branches (set (branches source))@@ -380,11 +378,17 @@(version [this](commit-sha this)))-(def ^:private get-repo- (memoize- (fn [url token]- (clone-repository! {:url url- :token token}))))+(def ^:private jgit (atom {}))++(defn- get-jgit [^File path {:keys [url token] :as args}]+ (if-let [obj (get @jgit (.getPath path))]+ obj+ (get (swap! jgit assoc (.getPath path) (u/prog1 (open-jgit path {:url url+ :token token})+ (when-not (has-data? (assoc args :git <>))+ (FileUtils/deleteDirectory path)+ (throw (ex-info "Cannot connect to uninitialized repository" {:url url})))))+ (.getPath path))))(defn git-source"Creates a new GitSource instance for a git repository.@@ -394,5 +398,5 @@Returns a GitSource record implementing the Source protocol."[url commit-ish token]- (->GitSource (get-repo url token)+ (->GitSource (get-jgit (repo-path {:url url :token token}) {:url url :token token})url commit-ish token))diff --git a/enterprise/backend/test/metabase_enterprise/remote_sync/source/git_test.clj b/enterprise/backend/test/metabase_enterprise/remote_sync/source/git_test.cljindex cf6e3526258..51621a7bc4f 100644--- a/enterprise/backend/test/metabase_enterprise/remote_sync/source/git_test.clj+++ b/enterprise/backend/test/metabase_enterprise/remote_sync/source/git_test.clj@@ -7,6 +7,7 @@[metabase.test :as mt][metabase.util :as u])(:import (java.io File)+ (org.apache.commons.io FileUtils)(org.eclipse.jgit.api Git)(org.eclipse.jgit.lib PersonIdent)))@@ -85,11 +86,12 @@(.toURI)(.toURL)(.toExternalForm))- local-repo (git/clone-repository! {:url remote-url})]+ local-repo (#'git/get-jgit (#'git/repo-path {:url remote-url}) {:url remote-url})](git/->GitSource local-repo remote-url branch nil)))(defn- init-source![branch dir & config]+ (FileUtils/deleteDirectory (io/file dir))(let [remote-repo (apply init-remote! dir config)][(->source! branch remote-repo) remote-repo]))@@ -118,17 +120,6 @@(is (= "refs/heads/main" (#'git/qualify-branch "main")))(is (= "refs/heads/main" (#'git/qualify-branch "refs/heads/main"))))-(deftest get-commit-ref- (mt/with-temp-dir [remote-dir nil]- (let [[source _remote] (init-source! "master" remote-dir :branches ["branch-1" "branch-2"])- master-ref (git/commit-sha source "master")]- (is (string? master-ref))- (is (= master-ref (git/commit-sha source (#'git/commit-sha source "master"))))- (is (not= master-ref (git/commit-sha source (#'git/commit-sha source "branch-1"))))- (is (not= master-ref (git/commit-sha source (#'git/commit-sha source "branch-2"))))-- (is (nil? (git/commit-sha source "invalid"))))))-(deftest log(mt/with-temp-dir [remote-dir nil](let [[master remote] (init-source! "master" remote-dir :branches ["branch-1" "branch-2"])diff --git a/enterprise/backend/test/metabase_enterprise/remote_sync/source/ingestable_test.clj b/enterprise/backend/test/metabase_enterprise/remote_sync/source/ingestable_test.cljindex c73a79eb125..e9cb1d3e6ba 100644--- a/enterprise/backend/test/metabase_enterprise/remote_sync/source/ingestable_test.clj+++ b/enterprise/backend/test/metabase_enterprise/remote_sync/source/ingestable_test.clj@@ -72,7 +72,7 @@(mt/with-model-cleanup [:model/User :model/RemoteSyncTask](let [user (first (t2/insert-returning-instances! :model/User {:first_name "Test":last_name "User"- :email "[email protected]"+ :email "[email protected]":password "password123"}))task (first (t2/insert-returning-instances! :model/RemoteSyncTask {:sync_task_type "import":initiated_by (:id user)}))diff --git a/src/metabase/cmd/env_var_dox.clj b/src/metabase/cmd/env_var_dox.cljindex c89399b688b..a893d01d949 100644--- a/src/metabase/cmd/env_var_dox.clj+++ b/src/metabase/cmd/env_var_dox.clj@@ -169,6 +169,7 @@"Used to filter out environment variables with high foot-gun indices."[env-var](or (false? (:doc env-var))+ (false? (:can-read-from-env? env-var));; Ideally, we'd move off of this list completely,;; but not all environment variables are defsettings.(contains? env-vars-not-to-mess-with (format-prefix env-var))))diff --git a/src/metabase/settings/models/setting.clj b/src/metabase/settings/models/setting.cljindex a07f1d98afb..c2f6b4d1554 100644--- a/src/metabase/settings/models/setting.clj+++ b/src/metabase/settings/models/setting.clj@@ -1347,6 +1347,11 @@A map which can provide values for any of the above options, except for :export?.Any top level options will override what's in this base map.The use case for this map is sharing strongly coupled options between similar settings, see [[uuid-nonce-base]].++ ##### `:can-read-from-env?`++ Boolean that determines if this setting can be configured from an environment variable.+ If false, a value set in an environment variable will be ignored."{:style/indent 1}[setting-symbol description & {:as options}]