NotebookUtils 在 Fabric 上的檔案掛載與卸載

NotebookUtils 支援透過 Microsoft Spark Utilities 套件進行檔案掛載與卸載操作。 你可以使用 mount、 unmount、 getMountPath()和 mounts() API 來將遠端儲存(ADLS Gen2、Azure Blob 儲存體、OneLake)附加到所有工作節點(驅動節點和工作節點)。 儲存載入點就緒之後,請使用本機檔案 API 來存取資料,就好像儲存在本機文件系統中一樣。

掛載作業特別有用的情況有:

  • 與期待本地檔案路徑的函式庫合作。
  • 需要在雲端儲存間保持一致的檔案系統語意。
  • 有效率地存取 OneLake 捷徑(S3/GCS)。
  • 建立能支援多個儲存後端的可攜式程式碼。

API 參考資料

下表總結了可用的掛載 API:

方法 Signature 說明
mount mount(source: String, mountPoint: String, extraConfigs: Map[String, Any] = None): Boolean 將遠端儲存掛載到指定的掛載點。
unmount unmount(mountPoint: String, extraConfigs: Map[String, Any] = None): Boolean 解除並移除掛載點。
mounts mounts(extraOptions: Map[String, Any] = None): Array[MountPointInfo] 列出所有現有的掛點及詳細資訊。
getMountPath getMountPath(mountPoint: String, scope: String = ""): String 取得掛載點的本地檔案系統路徑。

驗證方法

掛載操作支援多種認證方法。 根據您的儲存類型和安全需求來選擇方法。

Microsoft Entra 令牌認證使用筆記本執行者的身份,無論是使用者身份或服務主體身份。 掛載呼叫時不需要明確的憑證,這讓它成為最安全的選擇。 使用此選項用於湖邊屋安裝和 Fabric 工作空間儲存。

# Mount using Microsoft Entra token (no credentials needed)
notebookutils.fs.mount(
    "abfss://mycontainer@mystorageaccount.dfs.core.windows.net",
    "/mydata"
)

小提示

盡可能使用 Microsoft Entra 令牌認證。 它消除憑證暴露風險,且不需額外設定 Fabric 工作空間儲存。

帳戶金鑰

當儲存帳號不支援 Microsoft Entra 認證,或是存取外部或第三方儲存時,請使用帳號金鑰。 帳號金鑰存到 Azure Key Vault 並用 notebookutils.credentials.getSecret API 取回。

# Retrieve account key from Azure Key Vault
accountKey = notebookutils.credentials.getSecret("<vaultURI>", "<secretName>")
notebookutils.fs.mount(
    "abfss://mycontainer@<accountname>.dfs.core.windows.net",
    "/test",
    {"accountKey": accountKey}
)

共享存取簽章(SAS)令牌

使用 共享存取簽章(SAS) 令牌,進行限時且權限範圍限制的存取。 當你需要暫時授權外部方存取時,這個選項非常有用。 將 SAS 代幣存放在 Azure Key Vault 中。

# Retrieve SAS token from Azure Key Vault
sasToken = notebookutils.credentials.getSecret("<vaultURI>", "<secretName>")
notebookutils.fs.mount(
    "abfss://mycontainer@<accountname>.dfs.core.windows.net",
    "/test",
    {"sasToken": sasToken}
)

這很重要

為了安全考量,避免直接將憑證嵌入程式碼中。 筆記本輸出中顯示的任何秘密都會自動被遮蔽。 如需詳細資訊,請參閱 秘密密文。

掛載一個 ADLS Gen2 帳號

下列範例說明如何裝載 Azure Data Lake Storage Gen2。 掛載 Blob 儲存體 和 Azure 檔案分享的運作方式類似。

此範例假設您有一個名為 storegen2 的 Data Lake Storage Gen2 帳戶,其中有一個名為 mycontainer 的容器,您想要在筆記本 Spark 工作階段中掛接至 /test 。

顯示選取要裝載的容器之位置的螢幕擷取畫面。

要掛載名為 mycontainer 的容器,NotebookUtils 首先需要確認你是否有權限存取該容器。 目前,Fabric 支援三種觸發掛載操作的認證方法: Microsoft Entra 憑證 (預設)、 accountKey 與 sasToken。

為了安全考量,請將帳號金鑰或 SAS 憑證存放在 Azure Key Vault(如下圖所示)。 接著,您可以使用 notebookutils.credentials.getSecret API 來擷取它們。 如需關於 Azure Key Vault 的詳細資訊,請參閱關於 Azure Key Vault 受控儲存體帳戶金鑰。

顯示祕密儲存在 Azure Key Vault 中的螢幕擷取畫面。

accountKey 方法的範例程式碼:

# get access token for keyvault resource
# You can also use the full audience, such as https://vault.azure.net.
accountKey = notebookutils.credentials.getSecret("<vaultURI>", "<secretName>")
notebookutils.fs.mount(  
    "abfss://mycontainer@<accountname>.dfs.core.windows.net",  
    "/test",  
    {"accountKey":accountKey}
)

sasToken 範例程式碼:

# get access token for keyvault resource
# You can also use the full audience, such as https://vault.azure.net.
sasToken = notebookutils.credentials.getSecret("<vaultURI>", "<secretName>")
notebookutils.fs.mount(  
    "abfss://mycontainer@<accountname>.dfs.core.windows.net",  
    "/test",  
    {"sasToken":sasToken}
)

安裝參數

你可以在映射 extraConfigs 中用以下可選參數調整掛載方式:

  • fileCacheTimeout:Blobs 預設會被快取在本地暫存資料夾中 120 秒。 在此期間,blobfuse 不會檢查檔案是否是最新的。 你可以設定這個參數來改變預設的逾時時間。 當多個用戶端同時修改檔案時,為避免本地與遠端檔案間的不一致,請縮短快取時間或將其設為 0,以始終從伺服器取得最新檔案。
  • 超時:掛載操作的超時預設為 30 秒。 你可以設定這個參數來改變預設的逾時時間。 當執行者數量過多或掛載超時時,則提高數值。

您可以使用這些參數,如下所示:

notebookutils.fs.mount(
   "abfss://mycontainer@<accountname>.dfs.core.windows.net",
   "/test",
   {"fileCacheTimeout": 120, "timeout": 30}
)

快取設定建議

根據你的存取模式選擇快取逾時值:

情境 推薦 fileCacheTimeout Notes
讀取密集,單一客戶端 120 (預設值) 性能與新鮮度的平衡良好。
調節多客戶端存取 30–60 降低過時資料的風險。
多個用戶端修改檔案 0 總是從伺服器取得最新資訊。
檔案很少會改變 300+ 優化讀取效能。

零緩存模式

當多個用戶端同時修改檔案時,請使用零快取設定,始終從伺服器擷取最新版本:

# For scenarios with multiple clients modifying files
# Use zero cache to always fetch the latest from the server
notebookutils.fs.mount(
    "abfss://shared@account.dfs.core.windows.net",
    "/shared_data",
    {"fileCacheTimeout": 0}
)

備註

當掛載多個執行器或遇到逾時錯誤時,請提高 timeout 參數。

掛載湖倉

Lakehouse 掛載只支援 Microsoft Entra 令牌認證。 將 lakehouse 掛載至 /<mount_name> 的範例程式代碼:

notebookutils.fs.mount( 
 "abfss://<workspace_name>@onelake.dfs.fabric.microsoft.com/<lakehouse_name>.Lakehouse", 
 "/<mount_name>"
)

使用 notebookutils fs API 存取掛載點下的檔案

當你想透過本地檔案系統 API 存取遠端儲存資料時,可以使用掛載操作。 你也可以用 notebookutils.fs API 存取已掛載的資料,但路徑格式不同。

假設您使用掛接 API 將 Data Lake Storage Gen2 容器 mycontainer 掛接至 /test 。 當您使用本機檔案系統 API 存取資料時,路徑格式如下所示:

/synfs/notebook/{sessionId}/test/{filename}

當你想透過 notebookutils fs API 存取資料時,請用 getMountPath() 來取得準確的路徑:

path = notebookutils.fs.getMountPath("/test")
  • 清單目錄。

    notebookutils.fs.ls(f"file://{notebookutils.fs.getMountPath('/test')}")
    
  • 閱讀檔案內容。

    notebookutils.fs.head(f"file://{notebookutils.fs.getMountPath('/test')}/myFile.txt")
    
  • 建立目錄。

    notebookutils.fs.mkdirs(f"file://{notebookutils.fs.getMountPath('/test')}/newdir")
    

透過本機路徑存取裝載點下的檔案

你可以透過標準檔案系統在掛載點讀取和寫入檔案。 以下 Python 範例展示了此模式:

#File read
with open(notebookutils.fs.getMountPath('/test2') + "/myFile.txt", "r") as f:
    print(f.read())
#File write
with open(notebookutils.fs.getMountPath('/test2') + "/myFile.txt", "w") as f:
    print(f.write("dummy data"))

檢查現有的安裝點

使用 notebookutils.fs.mounts() API 檢查所有現有的掛載點資訊:

notebookutils.fs.mounts()

小提示

在建立新的掛載點之前,務必要使用 mounts() 檢查現有的掛載點,以避免衝突。

安裝前請確認有沒有安裝架

existing_mounts = notebookutils.fs.mounts()
mount_point = "/mydata"

if any(m.mountPoint == mount_point for m in existing_mounts):
    print(f"Mount point {mount_point} already exists")
else:
    notebookutils.fs.mount(
        "abfss://container@account.dfs.core.windows.net",
        mount_point
    )
    print("Mount created successfully")

卸載掛載點

請使用以下程式碼解除掛載點(此例中為 /test ):

notebookutils.fs.unmount("/test")

這很重要

卸載機制不會自動套用。 當應用程式執行完成時,若要卸載裝入點並釋放磁碟空間,您必須在程式碼中明確呼叫卸載 API。 否則,掛載點在應用程式執行結束後仍存在於節點中。

掛載-過程-卸載工作流程

為了可靠的資源管理,請將掛載操作封裝在 try/finally 區塊中,確保即使發生錯誤也可以執行清理。

def process_with_mount(source_uri, mount_point):
    """Complete workflow: mount, process, unmount."""
    
    try:
        # Step 1: Check if already mounted
        existing = notebookutils.fs.mounts()
        if any(m.mountPoint == mount_point for m in existing):
            print(f"Already mounted at {mount_point}")
        else:
            notebookutils.fs.mount(source_uri, mount_point)
            print(f"Mounted {source_uri} at {mount_point}")
        
        # Step 2: Process data using local file system
        mount_path = notebookutils.fs.getMountPath(mount_point)
        
        with open(f"{mount_path}/data/input.txt", "r") as f:
            data = f.read()
        
        processed = data.upper()
        
        with open(f"{mount_path}/output/result.txt", "w") as f:
            f.write(processed)
        
        print("Processing complete")
        
    finally:
        # Step 3: Always unmount to release resources
        notebookutils.fs.unmount(mount_point)
        print(f"Unmounted {mount_point}")

process_with_mount(
    "abfss://mycontainer@mystorage.dfs.core.windows.net",
    "/temp_mount"
)

已知的限制

  • 掛口是工作層級的配置。 使用 mounts API 來檢查是否有已存在或可用的掛載點。
  • 卸載不會自動發生。 應用程式執行結束後,呼叫程式碼中的卸載 API,釋放磁碟空間。 否則,掛載點會在應用程式執行結束後仍留在節點上。
  • 不支援裝載 ADLS Gen1 儲存體帳戶。