Microsoft Spark Utilities(MSSparkUtils)是一个内置的软件包,帮助你轻松完成常见任务。 使用 MSSparkUtils 处理文件系统、获取环境变量、将笔记本链接在一起以及处理机密。 MSSparkUtils 包可用于 PySpark(Python)、Scala 和 SparkR 笔记本,以及 Fabric 管道。
注意
- MsSparkUtils 正式更名为 NotebookUtils。 现有代码将保持向后兼容,不会造成任何重大变更。 我们 强烈建议 升级到 notebookutils,以确保持续支持并能使用新功能。 mssparkutils 命名空间将来会停用。
- NotebookUtils 旨在与 Spark 3.4 (Runtime v1.2) 及更高版本配合使用。 所有新功能和更新从今往后都仅受 notebookutils 命名空间支持。
文件系统实用工具
mssparkutils.fs 提供用于处理各种文件系统的工具,包括 Azure Data Lake Storage Gen2 和 Azure Blob 存储。 请确保正确配置对 Azure Data Lake Storage Gen2 和 Azure Blob 存储的访问。
运行以下命令以概要了解可用的方法:
from notebookutils import mssparkutils
mssparkutils.fs.help()
输出
mssparkutils.fs provides utilities for working with various FileSystems.
Below is overview about the available methods:
cp(from: String, to: String, recurse: Boolean = false): Boolean -> Copies a file or directory, possibly across FileSystems
mv(from: String, to: String, recurse: Boolean = false): Boolean -> Moves a file or directory, possibly across FileSystems
ls(dir: String): Array -> Lists the contents of a directory
mkdirs(dir: String): Boolean -> Creates the given directory if it does not exist, also creating any necessary parent directories
put(file: String, contents: String, overwrite: Boolean = false): Boolean -> Writes the given String out to a file, encoded in UTF-8
head(file: String, maxBytes: int = 1024 * 100): String -> Returns up to the first 'maxBytes' bytes of the given file as a String encoded in UTF-8
append(file: String, content: String, createFileIfNotExists: Boolean): Boolean -> Append the content to a file
rm(dir: String, recurse: Boolean = false): Boolean -> Removes a file or directory
exists(file: String): Boolean -> Check if a file or directory exists
mount(source: String, mountPoint: String, extraConfigs: Map[String, Any]): Boolean -> Mounts the given remote storage directory at the given mount point
unmount(mountPoint: String): Boolean -> Deletes a mount point
mounts(): Array[MountPointInfo] -> Show information about what is mounted
getMountPath(mountPoint: String, scope: String = ""): String -> Gets the local path of the mount point
Use mssparkutils.fs.help("methodName") for more info about a method.
MSSparkUtils 以与 Spark API 相同的方式处理文件系统。 以 mssparkuitls.fs.mkdirs() 和 Lakehouse 使用为例:
| 使用情况 | HDFS 根目录的相对路径 | ABFS 文件系统的绝对路径 | 驱动程序节点中本地文件系统的绝对路径 |
|---|---|---|---|
| 非默认湖屋 | 不支持 | mssparkutils.fs.mkdirs(“abfss://< container_name>@<storage_account_name.dfs.core.windows.net/>< new_dir>”) | mssparkutils.fs.mkdirs(“file:/<new_dir>”) |
| 默认湖屋 | “Files”或“Tables”下的目录:mssparkutils.fs.mkdirs("Files/<new_dir>") | mssparkutils.fs.mkdirs(“abfss://< container_name>@<storage_account_name.dfs.core.windows.net/>< new_dir>”) | mssparkutils.fs.mkdirs(“file:/<new_dir>”) |
列出文件
若要列出目录的内容,使用 mssparkutils.fs.ls (“你的目录路径”) 。 例如:
mssparkutils.fs.ls("Files/tmp") # works with the default lakehouse files using relative path
mssparkutils.fs.ls("abfss://<container_name>@<storage_account_name>.dfs.core.windows.net/<path>") # based on ABFS file system
mssparkutils.fs.ls("file:/tmp") # based on local file system of driver node
查看文件属性
该方法返回文件属性,包括文件名、文件路径、文件大小,以及它是目录还是文件。
files = mssparkutils.fs.ls('Your directory path')
for file in files:
print(file.name, file.isDir, file.isFile, file.path, file.size)
创建新目录
如果指定的目录不存在,该方法会创建该目录,并创建必要的父目录。
mssparkutils.fs.mkdirs('new directory name')
mssparkutils.fs. mkdirs("Files/<new_dir>") # works with the default lakehouse files using relative path
mssparkutils.fs.ls("abfss://<container_name>@<storage_account_name>.dfs.core.windows.net/<new_dir>") # based on ABFS file system
mssparkutils.fs.ls("file:/<new_dir>") # based on local file system of driver node
复制文件
此方法会复制文件或目录,并支持跨文件系统复制活动。
mssparkutils.fs.cp('source file or directory', 'destination file or directory', True)# Set the third parameter as True to copy all files and directories recursively
高性能复制文件
此方法会提供更快的方式来复制或移动文件,尤其是面对大量数据时。
mssparkutils.fs.fastcp('source file or directory', 'destination file or directory', True)# Set the third parameter as True to copy all files and directories recursively
预览文件内容
该方法返回指定文件的前几个 maxBytes 字节,以 UTF-8 编码的字符串形式返回。
# Set the second parameter as an integer for the maxBytes to read
mssparkutils.fs.head('file path', <maxBytes>)
移动文件
此方法会移动文件或目录,并支持跨文件系统移动。
mssparkutils.fs.mv('source file or directory', 'destination directory', True) # Set the last parameter as True to firstly create the parent directory if it does not exist
mssparkutils.fs.mv('source file or directory', 'destination directory', True, True) # Set the third parameter to True to firstly create the parent directory if it does not exist. Set the last parameter to True to overwrite the updates.
写入文件
此方法将以 UTF-8 编码的给定字符串写入文件。
mssparkutils.fs.put("file path", "content to write", True) # Set the last parameter as True to overwrite the file if it existed already
将内容追加到文件
此方法将以 UTF-8 编码的给定字符串追加到文件中。
mssparkutils.fs.append("file path", "content to append", True) # Set the last parameter as True to create the file if it does not exist
注意
如果你在 mssparkutils.fs.append 循环中使用 for API 向同一文件写入,我们建议你在两次重复写入之间添加一条约 0.5 到 1 秒的 sleep 语句。
mssparkutils.fs.append API内部flush操作是异步的,因此短暂的延迟有助于确保数据完整性。
删除文件或目录
此方法会删除文件或目录。
mssparkutils.fs.rm('file path', True) # Set the last parameter as True to remove all files and directories recursively
挂载/卸载目录
有关详细使用情况的更多信息,请参见 文件挂载和卸载。
笔记本实用工具
使用 MSSparkUtils 笔记本实用工具来运行笔记本或通过返回值退出笔记本。 运行以下命令以概要了解可用的方法:
mssparkutils.notebook.help()
输出:
exit(value: String): Raises NotebookExit Exception -> This method lets you exit a notebook with a value.
run(path: String, timeoutSeconds: int, arguments: Map): String -> This method runs a notebook and returns its exit value.
注意
笔记本工具不适用于Apache Spark作业定义(SJD)。
引用笔记本
此方法会引用笔记本并返回其退出值。 可以在笔记本中以交互方式或在管道中运行嵌套函数调用。 被引用的笔记本将在调用此函数的笔记本的 Spark 池上运行。
mssparkutils.notebook.run("notebook name", <timeoutSeconds>, <parameterMap>, <workspaceId>)
例如:
mssparkutils.notebook.run("Sample1", 90, {"input": 20 })
Fabric 笔记本还支持通过指定工作区 ID 跨多个工作区引用笔记本。
mssparkutils.notebook.run("Sample1", 90, {"input": 20 }, "fe0a6e2a-a909-4aa3-a698-0a651de790aa")
可以在单元格输出中打开参考运行的快照链接。 快照可以捕捉代码的运行结果,并允许你轻松调试参考运行。
注意
- 跨工作区引用笔记本由运行时版本 1.2 及更高版本支持。
- 如果你在 笔记本资源下使用文件,请在引用的笔记本中使用
mssparkutils.nbResPath,确保它指向与交互运行相同的文件夹。
并行运行多个笔记本
重要
此功能目前为预览版。
mssparkutils.notebook.runMultiple() 方法让你可以并行运行多个笔记本,或使用预定义的拓扑结构。 该 API 采用多线程实现,用于提交、排入队列并监控在现有 Spark 会话中的隔离 REPL 实例(读取-求值-输出循环)内执行的子笔记本。 引用的子笔记本共享会话的计算资源。
通过 mssparkutils.notebook.runMultiple(),您可以:
同时执行多个笔记本,而无需等待每个笔记本完成。
使用简单的 JSON 格式为笔记本指定依赖项和执行顺序。
优化 Spark 计算资源的使用,并降低 Fabric 项目的成本。
在输出中查看每个笔记本运行记录的快照,方便调试和监控笔记本任务。
获取每个执行活动的退出值,并在下游任务中使用它们。
还可以尝试运行 mssparkutils.notebook.help("runMultiple") 来查找示例和详细用法。
下面是使用此方法并行运行一组笔记本的简单示例:
mssparkutils.notebook.runMultiple(["NotebookSimple", "NotebookSimple2"])
根笔记本中的执行结果如下所示:
以下示例展示了如何使用 mssparkutils.notebook.runMultiple() 运行具有拓扑结构的笔记本。 使用此方法通过代码体验轻松编排笔记本。
# run multiple notebooks with parameters
DAG = {
"activities": [
{
"name": "NotebookSimple", # activity name, must be unique
"path": "NotebookSimple", # notebook path
"timeoutPerCellInSeconds": 90, # max timeout for each cell, default to 90 seconds
"args": {"p1": "changed value", "p2": 100}, # notebook parameters
},
{
"name": "NotebookSimple2",
"path": "NotebookSimple2",
"timeoutPerCellInSeconds": 120,
"args": {"p1": "changed value 2", "p2": 200}
},
{
"name": "NotebookSimple2.2",
"path": "NotebookSimple2",
"timeoutPerCellInSeconds": 120,
"args": {"p1": "changed value 3", "p2": 300},
"retry": 1,
"retryIntervalInSeconds": 10,
"dependencies": ["NotebookSimple"] # list of activity names that this activity depends on
}
],
"timeoutInSeconds": 43200, # max timeout for the entire DAG, default to 12 hours
"concurrency": 50 # max number of notebooks to run concurrently, defaults to 50 but ultimately constrained by the number of driver cores
}
mssparkutils.notebook.runMultiple(DAG, {"displayDAGViaGraphviz": False})
根笔记本中的执行结果如下所示:
注意
- 笔记本活动或并发笔记本的上限受驱动程序核心数的限制。 例如,一个拥有八核的中等节点驱动可以同时运行最多八个笔记本。 这个限制存在是因为每个提交的笔记本都运行在自己的REPL(读取-评估-打印循环)实例上,每个实例消耗一个驱动核心。
- 默认并发参数设置为 50,以支持自动缩放最大并发数,因为用户使用更大的节点和更多的驱动器核心配置 Spark 池。 虽然在使用较大的驱动节点时可以将该参数设置得更高,但增加单个驱动节点上运行的并发进程数量通常不会线性扩展。 由于驱动程序和执行程序资源争用,并发性增加可能会导致效率降低。 每台运行笔记本运行在专用的 REPL 实例上,该实例占用驱动的 CPU 和内存。 在高并发情况下,这种消耗会增加驱动程序不稳定或内存外错误的风险,尤其是在长时间运行的工作负载中。
- 由于初始化 REPL 实例以及编排多个笔记本会带来额外开销,每个作业的执行时间可能会更长。 如果出现问题,可以考虑将笔记本拆分为多个
runMultiple调用,或者通过调整 DAG 参数中的 concurrency 字段来降低并发度。 - 当你运行生命周期较短的笔记本时(例如,代码执行时间只有 5 秒),初始化开销就会占主导地位。 准备时间的波动性可能会降低笔记本运行时间重叠的概率,从而导致实际并发度降低。 在这种情况下,将小操作合并到一个或多个笔记本中可能更为优。
- 虽然多线程用于提交、排队和监控,但请注意,每个笔记本中运行的代码并非在每个执行程序上都采用多线程。 笔记本之间没有资源共享。 每个笔记本进程都会被分配总执行器资源的一部分。 这种分配可能导致较短的作业效率低下,而较长的作业则会争夺资源。
- 整个 DAG 的默认超时时间为 12 小时,子笔记本中每个单元格的默认超时时间为 90 秒。 可通过在 DAG 参数中设置“timeoutInSeconds”和“timeoutPerCellInSeconds”字段更改超时。 随着并发度的提高,您可能需要增加 timeoutPerCellInSeconds,以防止可能的资源争用导致不必要的超时。
退出笔记本
此方法会退出具有值的笔记本。 可以在笔记本中以交互方式或在管道中运行嵌套函数调用。
在笔记本中以交互方式调用 exit() 函数时,Fabric 笔记本会引发异常,跳过运行后续单元格,并使 Spark 会话保持活动状态。
在管道中协调调用 exit() 函数的笔记本时,笔记本活动将返回退出值,完成管道运行,并停止 Spark 会话。 不要将 exit() 函数放在 try/catch 语句中,因为该 NotebookExit 异常必须继续传播,管道才能获取返回值。
当你调用被引用笔记本中的 exit() 函数时,Fabric Spark 会停止对该笔记本的进一步执行,并继续运行主笔记本中调用 run() 函数的下一个单元格。 例如:Notebook1 有三个单元格,调用第二个单元格中的 exit() 函数。 Notebook2 有五个单元格,调用第三个单元格中的 run(notebook1) 函数。 运行 Notebook2 时,如果命中 exit() 函数,Notebook1 将在第二个单元格停止。 Notebook2 继续运行其第四个和第五个单元。
mssparkutils.notebook.exit("value string")
例如:
示例1 笔记本有以下两个单元格:
单元格 1 定义 input 参数,默认值设为 10。
单元 2 以input作为退出值退出笔记本。
可以使用默认值在其他笔记本中运行Sample1:
exitVal = mssparkutils.notebook.run("Sample1")
print (exitVal)
输出:
Notebook executed successfully with exit value 10
可以在另一笔记本中运行 Sample1,并将 input 值设为 20 :
exitVal = mssparkutils.notebook.run("Sample1", 90, {"input": 20 })
print (exitVal)
输出:
Notebook executed successfully with exit value 20
凭据管理工具
你可以使用 MSSparkUtils 凭证工具来获取访问令牌,并在 Azure 密钥保管库 中管理密钥。
运行以下命令以概要了解可用的方法:
mssparkutils.credentials.help()
输出:
getToken(audience, name): returns AAD token for a given audience, name (optional)
getSecret(keyvault_endpoint, secret_name): returns secret for a given Key Vault and secret name
获取令牌
getToken 返回针对给定受众和名称(可选)的 Microsoft Entra 令牌。 以下列表显示了当前可用的受众密钥:
-
存储受众资源:
storage -
Power BI 资源:
pbi -
Azure 密钥保管库 Resource:
keyvault -
Synapse RTA KQL DB 资源:
kusto
运行以下命令以获取这些令牌:
mssparkutils.credentials.getToken('audience Key')
通过使用用户凭证获取秘密
getSecret通过使用用户凭据返回给定Azure 密钥保管库端点的Azure 密钥保管库秘密和秘密名称。
mssparkutils.credentials.getSecret('https://<name>.vault.azure.net/', 'secret name')
文件装载和卸载
Fabric 支持以下 Microsoft Spark 实用工具包中的装载方案。 你可以使用 mount、unmount、getMountPath() 和 mounts() API 来将远程存储(Azure Data Lake Storage Gen2)附加到所有工作节点(驱动节点和工作节点)。 存储装入点就位后,使用本地文件 API 访问数据,如同数据存储在本地文件系统中一样。
如何挂载 Azure Data Lake Storage Gen2 账户
以下示例展示了如何挂载 Azure Data Lake Storage Gen2。 装载 Blob 存储的操作方式是类似的。
本示例假定你有一个名为 storegen2 的 Data Lake Storage Gen2 帐户,并且该帐户有一个名为 mycontainer 的容器,你希望将其装载到笔记本 Spark 会话中的 /test。
要挂载名为 mycontainer 的容器, mssparkutils 首先检查你是否有权限访问该容器。 Fabric 支持三种触发挂载操作的认证方法:Microsoft Entra 令牌(默认且推荐)、accountKey 和 sastoken。 有关 Microsoft Entra 令牌认证及当前 notebookutils API 的更多信息,请参见 NotebookUtils 在 Fabric 上挂载和卸载文件。
通过使用共享访问签名令牌或账户密钥进行挂载
MSSparkUtils 支持将账户密钥或 共享访问签名 (SAS) 令牌作为参数显式传递以挂载目标。
出于安全原因,建议将帐户密钥或 SAS 令牌存储在 Azure 密钥保管库 中(如以下屏幕截图所示)。 可以使用 mssparkutils.credentials.getSecret API 来检索它们。 有关 Azure 密钥保管库 的详细信息,请参阅关于 Azure 密钥保管库 托管存储帐户密钥。
accountKey 方法的示例代码:
from notebookutils import mssparkutils
# get access token for keyvault resource
# you can also use full audience here like https://vault.azure.net
accountKey = mssparkutils.credentials.getSecret("<vaultURI>", "<secretName>")
mssparkutils.fs.mount(
"abfss://mycontainer@<accountname>.dfs.core.windows.net",
"/test",
{"accountKey":accountKey}
)
sastoken 的示例代码:
from notebookutils import mssparkutils
# get access token for keyvault resource
# you can also use full audience here like https://vault.azure.net
sasToken = mssparkutils.credentials.getSecret("<vaultURI>", "<secretName>")
mssparkutils.fs.mount(
"abfss://mycontainer@<accountname>.dfs.core.windows.net",
"/test",
{"sasToken":sasToken}
)
注意
如果 mssparkutils 不可用,可能需要将它导入:
from notebookutils import mssparkutils
装载参数:
-
fileCacheTimeout: blobs 默认会在本地临时文件夹缓存 120 秒。 在此期间,blobfuse 不会检查文件是否是最新的。 设置此参数以更改默认超时。 当多个客户端同时修改文件时,为避免本地和远程文件之间的不一致,我们建议缩短缓存时间,甚至将其改为0,并且始终从服务器获取最新文件。 -
timeout:挂载操作默认超时为120秒。 设置此参数以更改默认超时。 当执行者数量过多或挂载超时时,我们建议提高该值。
可以使用如下所示的这些参数:
mssparkutils.fs.mount(
"abfss://mycontainer@<accountname>.dfs.core.windows.net",
"/test",
{"fileCacheTimeout": 120, "timeout": 120}
)
注意
出于安全原因,请勿在代码中存储凭据。 为了进一步保护您的凭据,机密内容会在笔记本输出中被隐藏。 有关详细信息,请查看机密编修。
如何装载湖屋
将湖仓挂载到 /test 的示例代码:
from notebookutils import mssparkutils
mssparkutils.fs.mount(
"abfss://<workspace_id>@onelake.dfs.fabric.microsoft.com/<lakehouse_id>",
"/test"
)
注意
不支持安装区域端点。 Fabric 仅支持装载全局端点 onelake.dfs.fabric.microsoft.com。
通过使用 mssparkutils fs API 访问挂载点下的文件
挂载操作的主要目的是通过本地文件系统 API 访问存储在远程存储账户中的数据。 你也可以使用 mssparkutils fs API 以装载路径作为参数来访问数据。 此路径格式稍有不同。
假设你使用挂载 API 将 Data Lake Storage Gen2 容器 mycontainer 挂载到 /test。 当你通过本地文件系统API访问数据时,路径格式如下:
/synfs/notebook/{sessionId}/test/{filename}
当你想通过 mssparkutils fs API 访问数据时,我们建议你使用 getMountPath() 来获取准确的路径:
path = mssparkutils.fs.getMountPath("/test")
列出目录:
mssparkutils.fs.ls(f"file://{mssparkutils.fs.getMountPath('/test')}")读取文件内容:
mssparkutils.fs.head(f"file://{mssparkutils.fs.getMountPath('/test')}/myFile.txt")创建目录:
mssparkutils.fs.mkdirs(f"file://{mssparkutils.fs.getMountPath('/test')}/newdir")
通过本地路径访问装载点下的文件
可以使用标准文件系统在装载点中轻松读取和写入文件。 下面是 Python 示例:
#File read
with open(mssparkutils.fs.getMountPath('/test2') + "/myFile.txt", "r") as f:
print(f.read())
#File write
with open(mssparkutils.fs.getMountPath('/test2') + "/myFile.txt", "w") as f:
print(f.write("dummy data"))
如何检查现有装入点
可以使用 mssparkutils.fs.mounts() API 来检查所有现有装入点信息:
mssparkutils.fs.mounts()
如何卸载挂载点
使用以下代码可卸载装入点(在此示例中为 /test):
mssparkutils.fs.unmount("/test")
已知的限制
目前的安装架是作业级配置。 我们建议您使用 mounts API 来检查挂载点是否存在或不可用。
卸载机制不是自动进行的。 应用程序运行完成后,若要卸载装入点并释放磁盘空间,需要在代码中显式调用卸载 API。 否则,应用程序运行完成后,装入点仍存在于节点中。
不支持挂载 Azure Data Lake Storage Gen1 存储账户。
Lakehouse 的实用工具
该 mssparkutils.lakehouse 模块提供了用于管理 Lakehouse 项目的实用工具。 这些工具让创建、检索、更新和删除 Lakehouse 项目变得简单。
注意
Lakehouse API 仅支持运行时版本 1.2 或更高版本。
方法概述
mssparkutils.lakehouse 模块中提供以下方法:
# Create a new Lakehouse artifact
create(name: String, description: String = "", workspaceId: String = ""): Artifact
# Retrieve a Lakehouse artifact
get(name: String, workspaceId: String = ""): Artifact
# Update an existing Lakehouse artifact
update(name: String, newName: String, description: String = "", workspaceId: String = ""): Artifact
# Delete a Lakehouse artifact
delete(name: String, workspaceId: String = ""): Boolean
# List all Lakehouse artifacts
list(workspaceId: String = ""): Array[Artifact]
用法示例
为了有效使用这些方法,请考虑以下使用示例:
创建 Lakehouse 项
artifact = mssparkutils.lakehouse.create("artifact_name", "Description of the artifact", "optional_workspace_id")
检索 Lakehouse 项
artifact = mssparkutils.lakehouse.get("artifact_name", "optional_workspace_id")
更新 Lakehouse 项
updated_artifact = mssparkutils.lakehouse.update("old_name", "new_name", "Updated description", "optional_workspace_id")
删除 Lakehouse 项目
is_deleted = mssparkutils.lakehouse.delete("artifact_name", "optional_workspace_id")
Lakehouse 项目列表
artifacts_list = mssparkutils.lakehouse.list("optional_workspace_id")
其他信息
如需更详细了解每种方法及其参数,请使用该 mssparkutils.lakehouse.help("methodName") 函数。
通过使用 MSSparkUtils 的 Lakehouse 工具,您可以更高效地管理您的 Lakehouse 项目,并将这些管理整合进 Fabric 管道,提升整体数据管理体验。
探索这些实用工具,并将其融入您的 Fabric 工作流程,实现无缝的 Lakehouse 项管理。
运行时实用工具
显示会话上下文信息
通过使用 mssparkutils.runtime.context,你可以获取当前实时会话的上下文信息,包括笔记本名称、默认湖屋、工作区信息、是否是流水线运行等。
mssparkutils.runtime.context
注意
mssparkutils.env 尚未在 Fabric 上获得官方支持。 使用 notebookutils.runtime.context 作为替代方法。
多进程限制
不支持在同一Spark驱动应用内,从多个独立Python进程并发导入或使用Spark支持的MSSparkUtils或NotebookUtils接口。 该限制包括从 pytest-xdist 工作进程同时导入。 导入包可以初始化Spark运行时依赖,即使你之后没有调用工具API。
对于需要实际工具API的测试,请在原始Spark驱动进程中运行测试,且禁用基于进程的并行处理。 对于业务逻辑单元测试,使用模拟或伪造来隔离这些依赖,避免在工作进程中导入实际包。
这一限制适用于访问Spark支持的工具,而不适用于Python子进程的普遍使用。
已知问题
当你使用1.2之前的运行时版本并运行 mssparkutils.help()时,上述的 fabricClient、 warehouse和 workspace API目前不被支持。