Mycroft 文件系统沙箱 FileSystemAccess 深入解析:技能数据隔离与 XDG 规范实践
Mycroft 文件系统沙箱 FileSystemAccess 深入解析:技能数据隔离与 XDG 规范实践
mycroft.filesystem 是 Mycroft Core 为技能(Skill)与系统组件提供的文件系统沙箱模块,其核心类是 FileSystemAccess。它通过 XDG Base Directory 规范为每个技能划出独立的命名空间目录,并内置从旧版 ~/.mycroft 目录的自动迁移逻辑。本文基于 doc/source/mycroft.filesystem.rst 展开,结合仓库源码与真实调用方,讲解该模块的 API、路径解析机制、在 MycroftSkill 与 IdentityManager 中的挂载方式,帮助你理解并正确使用 Mycroft 的持久化数据隔离方案。
一、从文档到实现:mycroft.filesystem 模块是什么
doc/source/mycroft.filesystem.rst 是 Sphinx 自动文档(autodoc)的声明文件,全文通过一个指令将类成员全部渲染到文档中:
mycroft.filesystem
==================
.. autoclass:: mycroft.filesystem.FileSystemAccess
:members:
这意味着该模块的“文档即源码 docstring”:FileSystemAccess 类的全部公开成员(path 属性、open()、exists() 方法)均由其 docstring 驱动生成。该页面被 doc/source/mycroft.rst 中的 toctree 引用,属于 Mycroft API 文档体系的一部分。
FileSystemAccess 的实际实现位于 mycroft/filesystem/init.py,类注释明确说明了它的定位:
A class for providing access to the mycroft FS sandbox. Intended to be attached to skills at initialization time to provide a skill-specific namespace.
即:为 Mycroft 提供受控的文件系统沙箱访问,设计初衷是在技能初始化时挂载,为每个技能提供独立的命名空间。它依赖 pyxdg(声明于 requirements/requirements.txt,版本 pyxdg==0.27)来落实 XDG Base Directory 规范。
二、核心类 FileSystemAccess 的 API 全景
FileSystemAccess 的公开接口非常精简,全部集中在三个成员上,但其内部逻辑覆盖了参数校验、旧路径迁移、目录自动创建三个关键环节。
2.1 path 成员:命名空间根路径
在 __init__ 中通过 self.path = self.__init_path(path) 初始化,注释明确标注为“Member value containing the root path of the namespace”。它是沙箱的根目录,后续所有文件操作都在该目录内展开。
2.2 open(filename, mode):在命名空间内打开文件
def open(self, filename, mode):
"""Open a file in the provided namespace.
...
Parameters:
filename (str): a path relative to the namespace.
subdirs not currently supported.
mode (str): a file handle mode
Returns:
an open file handle.
"""
file_path = join(self.path, filename)
return open(file_path, mode)
要点:
filename必须是相对于命名空间根路径的相对路径,且源码 docstring 明确说明“subdirs not currently supported”(暂不支持子目录),实际实现即简单的join(self.path, filename);mode与 Python 内置open()的模式字符串一致('r'、'w'、'a'等),返回值是一个打开的文件句柄,调用方需自行负责关闭或使用上下文管理器;- 由于返回的是原生文件句柄,调用方可以继续使用
json.dump、f.flush()、os.fsync()等标准文件操作。
2.3 exists(filename):判断命名空间内文件是否存在
def exists(self, filename):
"""Check if file exists in the namespace.
Args:
filename (str): a path relative to the namespace.
subdirs not currently supported.
Returns:
bool: True if file exists, else False.
"""
return os.path.exists(join(self.path, filename))
同样要求相对路径,底层委托给 os.path.exists。典型的调用模式是“先 exists 判断、再 open 读取”,在 IdentityManager 中可以看到完整用例。
三、沙箱路径的解析与初始化:__init_path 内部机制
路径初始化是 FileSystemAccess 最核心的私有逻辑,源码如下:
@staticmethod
def __init_path(path):
if not isinstance(path, str) or len(path) == 0:
raise ValueError("path must be initialized as a non empty string")
old_path = join(expanduser('~'), '.mycroft', path)
path = join(xdg.BaseDirectory.save_config_path('mycroft'), path)
# Migrate from the old location if it still exists
# TODO: remove in 22.02
if isdir(old_path):
if isdir(path):
shutil.rmtree(path)
shutil.move(old_path, path)
if not isdir(path):
os.makedirs(path)
return path
它依次完成四件事:
- 入参校验:
path必须是非空字符串,否则抛出ValueError。这保证了命名空间名(如'identity'、'skills/<skill_name>')的合法性,从源头杜绝空路径落到磁盘; - 计算新旧路径:
- 旧路径:
~/.mycroft/<path>(expanduser('~')展开用户主目录); - 新路径:
xdg.BaseDirectory.save_config_path('mycroft')/<path>。save_config_path是 pyxdg 提供的方法,遵循 XDG 规范——默认返回$XDG_CONFIG_HOME/mycroft(未设置XDG_CONFIG_HOME时即~/.config/mycroft),并自动创建该目录;
- 旧路径:
- 自动迁移:若旧路径
~/.mycroft/<path>仍存在,则先删除同名新目录(shutil.rmtree),再整体移动(shutil.move),将用户旧版数据无缝搬到新位置。源码中# TODO: remove in 22.02表明这是过渡性兼容代码; - 确保目录存在:若目标目录尚不存在,则
os.makedirs递归创建,返回新路径。
从源码结构可以推断:最终的沙箱根目录形如 ~/.config/mycroft/<namespace>(Linux 默认),命名空间名即构造时传入的 path。迁移逻辑的存在说明 Mycroft 曾经使用 ~/.mycroft 作为数据目录,后全面转向 XDG 规范,FileSystemAccess 承担了平滑升级的职责。
四、Skills 中的挂载方式:file_system 属性
FileSystemAccess 最主要的使用者是技能系统。在 mycroft/skills/mycroft_skill/mycroft_skill.py 的 MycroftSkill.__init__ 中,每个技能实例都会挂载一个专属的文件系统沙箱:
#: Filesystem access to skill specific folder.
#: See mycroft.filesystem for details.
self.file_system = FileSystemAccess(join('skills', self.name))
由此可知:
- 所有技能的沙箱统一收纳在
skills/命名空间下; self.name是技能名(如my-skill),因此每个技能的沙箱根路径为~/.config/mycroft/skills/<技能名>;- 技能之间天然隔离,互不可见对方的沙箱内容,实现了“技能专属命名空间”的设计目标。
技能作者可以在技能代码中直接使用:
def handle_save_score(self, message):
# 保存一个计分文件到本技能专属目录
with self.file_system.open('score.txt', 'w') as f:
f.write('100')
def handle_load_score(self, message):
if self.file_system.exists('score.txt'):
with self.file_system.open('score.txt', 'r') as f:
score = f.read()
这与 settings.json 的持久化策略相辅相成——技能设置也遵循“优先技能目录、否则写入 XDG 配置目录”的原则(见 mycroft_skill.py 中基于 BaseDirectory.save_config_path('mycroft', 'skills', basename(self.root_dir)) 的 settings_write_path 计算),共同构成技能的持久化数据体系。
五、系统级使用实例:IdentityManager 的设备身份持久化
除技能外,系统组件同样通过 FileSystemAccess 落盘关键数据。最典型的例子是 mycroft/identity/init.py 中的 IdentityManager——它负责设备身份(OAuth token 等)的读写:
@staticmethod
def _load():
LOG.debug('Loading identity')
try:
identity_dir = FileSystemAccess('identity')
if identity_dir.exists('identity2.json'):
with identity_dir.open('identity2.json', 'r') as f:
IdentityManager.__identity = DeviceIdentity(**json.load(f))
else:
IdentityManager.__identity = DeviceIdentity()
except Exception as e:
LOG.exception(f'Failed to load identity file: {repr(e)}')
IdentityManager.__identity = DeviceIdentity()
保存时同样经由 FileSystemAccess('identity').open('identity2.json', 'w'),并追加了 f.flush() 与 os.fsync(f.fileno()),确保身份数据真正落盘而非停留在系统缓冲区:
with FileSystemAccess('identity').open('identity2.json', 'w') as f:
json.dump(IdentityManager.__identity.__dict__, f)
f.flush()
os.fsync(f.fileno())
这个例子展示了 open() 返回原生文件句柄带来的灵活性:FileSystemAccess 只负责“把文件放进正确且隔离的目录”,至于 JSON 序列化、持久化强度(fsync)等由调用方自由掌控。设备身份文件最终位于 ~/.config/mycroft/identity/identity2.json(Linux 默认),读取前用 exists() 探测文件是否存在,与文档中 exists 的用法一一对应。
六、遵循 XDG Base Directory:Mycroft 配置文件体系的一体化视角
FileSystemAccess 采用 xdg.BaseDirectory.save_config_path('mycroft') 并非孤例,Mycroft 的配置系统整体建立在 XDG 规范之上,可在 mycroft/configuration/locations.py 中看到统一布局:
SYSTEM_CONFIG = os.environ.get('MYCROFT_SYSTEM_CONFIG',
'/etc/mycroft/mycroft.conf')
# TODO: remove in 22.02
# Deprecated and will be removed eventually
OLD_USER_CONFIG = join(expanduser('~'), '.mycroft/mycroft.conf')
USER_CONFIG = join(xdg.BaseDirectory.xdg_config_home,
'mycroft',
'mycroft.conf'
)
同一套 XDG 逻辑还用于:
- mycroft/configuration/config.py:通过
load_config_paths('mycroft')按优先级聚合系统、用户等多级配置; - mycroft/client/speech/hotword_factory.py:在
xdg_config_home/mycroft/mycroft.conf与load_config_paths('mycroft')中查找唤醒词配置; - mycroft/client/text/text_client.py:同样基于
xdg_config_home与load_config_paths定位配置。
对照可见:FileSystemAccess 把“配置目录选择 + 旧目录迁移 + 目录自动创建”封装成统一入口,让上层模块只需关心命名空间名,无需重复实现 XDG 逻辑。默认路径汇总如下(Linux 下未设置 XDG_CONFIG_HOME 时):
| 命名空间 | 实际目录(默认) | 主要使用者 |
|---|---|---|
identity |
~/.config/mycroft/identity/ |
IdentityManager(identity2.json) |
skills/<技能名> |
~/.config/mycroft/skills/<技能名>/ |
MycroftSkill.file_system |
| (配置) | ~/.config/mycroft/mycroft.conf |
配置系统(非沙箱,见 locations.py) |
若设置了 XDG_CONFIG_HOME,则根目录随之变为 $XDG_CONFIG_HOME/mycroft;这是 XDG 规范带来的标准可移植性。
七、实战要点与使用建议
综合文档、源码与调用方,使用 FileSystemAccess 时有以下几点值得注意:
- 命名空间名必须是非空字符串:传入空串或非字符串会触发
ValueError,这既是保护也是约束; - 路径参数是相对路径:
open()与exists()的filename相对于命名空间根目录;当前实现不支持子目录,需要嵌套目录时应考虑自行扩展或在命名空间中组织扁平文件名; - 返回原生文件句柄:可以无缝配合
json、os.fsync等标准库,但句柄的生命周期(关闭/刷新)由调用方负责,推荐使用with语句; - 旧数据自动迁移:如果设备上还残留
~/.mycroft/目录,首次初始化沙箱时会自动迁移到 XDG 位置,无需人工干预;源码注释表明该迁移代码计划在 22.02 版本后移除; - 技能数据天然隔离:每个技能通过
self.file_system拥有专属目录,适合存放用户偏好、缓存、进度等不便于放进settings.json的私有数据。
八、总结
mycroft.filesystem.FileSystemAccess 虽只暴露了 path、open()、exists() 三个成员,却是 Mycroft 平台持久化架构的基石:它为每个技能提供隔离的数据沙箱(skills/<技能名>),为系统组件(如 IdentityManager)提供标准化的配置目录落盘能力,并通过 XDG Base Directory 规范与自动迁移逻辑,让 Mycroft 的数据目录从 ~/.mycroft 平滑过渡到 ~/.config/mycroft。理解这个模块,是编写具备可靠本地状态持久化能力的 Mycroft 技能的第一步——其完整实现与文档均可直接在 mycroft/filesystem/init.py 与其 Sphinx 文档页 doc/source/mycroft.filesystem.rst 中进一步研读。