文章目录
团队博客: 汽车电子社区
1. 项目概述
Systemd 是一个 Linux 系统和服务管理器,作为 init 系统替代传统的 SysV init。它提供了系统启动、服务管理、日志记录、设备管理、网络配置等全方位的系统管理功能。
2. 软件架构设计
2.1 分层架构设计
┌─────────────────────────────────────────────────────────────┐
│ 应用层 (用户工具) │
│ systemctl, journalctl, networkctl, timedatectl, etc... │
├─────────────────────────────────────────────────────────────┤
│ 服务层 (核心守护进程) │
│ PID 1 (systemd), journald, networkd, udevd, timedated... │
├─────────────────────────────────────────────────────────────┤
│ 共享库层 (libsystemd) │
│ sd-bus, sd-journal, sd-login, sd-event, sd-id128 │
├─────────────────────────────────────────────────────────────┤
│ 工具库层 (shared + basic) │
│ 配置解析、DBus工具、单元管理、基础工具库 │
├─────────────────────────────────────────────────────────────┤
│ 基础层 (fundamental) │
│ 内存管理、字符串处理、基础宏定义 │
└─────────────────────────────────────────────────────────────┘
2.2 核心组件架构
PID 1 (系统核心管理器)
PID 1 (systemd)
├── 单元管理器 (Unit Manager)
│ ├── Service 管理
│ ├── Socket 管理
│ ├── Target 管理
│ ├── Device 管理
│ └── Mount/Timer 管理
├── 任务调度器 (Job Scheduler)
├── 依赖解析器 (Dependency Resolver)
├── 进程执行器 (Executor)
├── D-Bus 接口管理
└── 事件循环管理
主要守护进程
- journald: 日志管理守护进程
- networkd: 网络配置管理守护进程
- udevd: 设备管理守护进程
- timedated: 时间日期管理守护进程
- logind: 用户会话管理守护进程
- resolved: 网络解析管理守护进程
3. 接口调用流程
3.1 系统启动流程
3.2 服务管理流程
3.3 D-Bus 通信架构
4. 源码分析
4.1 核心源码结构
fundamental 层 (最基础代码)
src/fundamental/
├── macro.h // 基础宏定义
├── memory-util.c // 内存管理工具
├── string-util.c // 字符串处理工具
├── random-util.c // 随机数生成工具
└── efi/ // EFI 特定代码
└── efi-loader.c // EFI 启动加载器
basic 层 (基础工具库)
src/basic/
├── fileio.c // 文件 I/O 操作
├── filesystem.c // 文件系统工具
├── process-util.c // 进程管理工具
├── cgroup-util.c // cgroup 工具
├── sd-event.c // 事件循环库
└── missing.h // 兼容性头文件
core 层 (PID 1 核心实现)
src/core/
├── main.c // 主程序入口 (1000+ 行)
├── manager.c // 管理器核心逻辑
├── unit.c // 单元抽象和操作
├── job.c // 任务调度管理
├── execute.c // 进程执行管理
├── load-fragment.c // 单元文件解析
├── dbus-unit.c // D-Bus 单元接口
├── dbus-manager.c // D-Bus 管理器接口
└── cgroup.c // cgroup 集成
4.2 关键数据结构
Unit 结构 (单元抽象)
struct Unit {
Manager *manager;
char *id; // 单元名称
UnitType type; // 单元类型
UnitState state; // 当前状态
Job *job; // 当前任务
UnitRef *refs_by_target; // 依赖引用
UnitRef *refs_by_dependency; // 被依赖引用
Hashmap *dependencies[UNIT_DEPENDENCY_MAX]; // 依赖表
UnitRef *refs; // 引用计数
Watchdog watchdog; // 看门狗
CGroupContext *cgroup_context; // cgroup 上下文
ExecContext *exec_context; // 执行上下文
// ...
};
Manager 结构 (系统管理器)
struct Manager {
Unit **units; // 单元数组
size_t n_units; // 单元数量
Hashmap *units_hash; // 单元哈希表
Job **jobs; // 任务数组
size_t n_jobs; // 任务数量
sd_event *event; // 事件循环
sd_bus *bus; // D-Bus 连接
CGroupControllerMask cgroup_supported; // cgroup 支持掩码
bool first_boot; // 首次启动标志
// ...
};
4.3 核心算法分析
依赖解析算法
// 单元依赖关系解析 (src/core/manager.c)
static int unit_add_dependency(
Unit *u,
UnitDependency d,
Unit *other,
UnitDependencyMask mask,
bool add_reference) {
// 1. 检查循环依赖
if (detect_circular_dependency(u, other, d))
return -EINVAL;
// 2. 添加依赖关系
if (!unit_has_dependency(u, d, other)) {
// 创建依赖引用
UnitRef *ref = unit_ref_new(other, u, d);
hashmap_put(u->dependencies[d], other->id, ref);
// 更新状态
if (add_reference)
unit_ref_add(ref);
}
return 0;
}
任务调度算法
// 任务调度器 (src/core/job.c)
static int job_run_and_invalidate(Job *j) {
Unit *u = j->unit;
switch (j->type) {
case JOB_START:
return unit_start(u);
case JOB_STOP:
return unit_stop(u);
case JOB_RESTART:
return unit_restart(u);
case JOB_RELOAD:
return unit_reload(u);
default:
return -EINVAL;
}
}
5. 模块间通信机制
5.1 D-Bus 接口设计
// D-Bus 方法注册 (src/core/dbus-manager.c)
static const sd_bus_vtable manager_vtable[] = {
SD_BUS_VTABLE_START(0),
// 系统控制方法
SD_BUS_METHOD("StartUnit", "ss", "o", method_start_unit, SD_BUS_VTABLE_UNPRIVILEGED),
SD_BUS_METHOD("StopUnit", "ss", "o", method_stop_unit, SD_BUS_VTABLE_UNPRIVILEGED),
SD_BUS_METHOD("ReloadUnit", "ss", "o", method_reload_unit, SD_BUS_VTABLE_UNPRIVILEGED),
SD_BUS_METHOD("RestartUnit", "ss", "o", method_restart_unit, SD_BUS_VTABLE_UNPRIVILEGED),
// 属性访问
SD_BUS_PROPERTY("Version", "s", property_get_version, 0, SD_BUS_VTABLE_PROPERTY_CONST),
SD_BUS_PROPERTY("SystemState", "s", property_get_system_state, 0, SD_BUS_VTABLE_PROPERTY_EMITS_CHANGE),
SD_BUS_VTABLE_END
};
5.2 事件循环机制
// 基于 sd-event 的事件循环 (src/basic/sd-event.c)
int sd_event_run(sd_event *e, uint64_t timeout) {
// 1. 处理定时器事件
process_timer_events(e);
// 2. 处理 I/O 事件
process_io_events(e);
// 3. 处理信号事件
process_signal_events(e);
// 4. 处理挂起事件
process_defer_events(e);
return 1; // 返回处理的事件数
}
6. 构建系统分析
6.1 Meson 构建配置
# 主 meson.build 文件结构
project('systemd', 'c',
version : meson.project_version(),
default_options : [
'warning_level=2',
'c_std=c17',
'buildtype=debugoptimized'
],
license : 'LGPLv2+'
)
# 核心依赖
glib_dep = dependency('glib-2.0', version : '>= 2.42')
dbus_dep = dependency('dbus-1')
libcap_dep = dependency('libcap')
libmount_dep = dependency('mount')
6.2 模块化编译
# 可选功能编译
conf = configuration_data()
conf.set('ENABLE_NETWORKD', get_option('networkd'))
conf.set('ENABLE_RESOLVED', get_option('resolved'))
conf.set('ENABLE_TIMEDATED', get_option('timedated'))
conf.set('ENABLE_LOCALED', get_option('localed'))
7. 安全机制
7.1 权限管理
// 进程权限设置 (src/core/execute.c)
static int setup_privileges(ExecContext *c) {
// 1. 设置用户和组
if (c->user) {
if (setgroups(0, NULL) < 0)
return -errno;
if (initgroups(c->user, c->group) < 0)
return -errno;
if (setregid(c->group, c->group) < 0)
return -errno;
if (setreuid(c->user, c->user) < 0)
return -errno;
}
// 2. 设置 capability
if (c->capability_set) {
if (prctl(PR_CAPBSET_DROP, cap_to_name(c->capability_set)) < 0)
return -errno;
}
return 0;
}
7.2 安全沙箱
// cgroup 限制设置
static int apply_cgroup_restrictions(Unit *u) {
CGroupContext *c = u->cgroup_context;
// CPU 限制
if (c->cpu_quota_per_sec_usec)
cg_set_attribute("cpu", "cpu.cfs_quota_us",
c->cpu_quota_per_sec_usec);
// 内存限制
if (c->memory_limit)
cg_set_attribute("memory", "memory.limit_in_bytes",
c->memory_limit);
return 0;
}
8. 性能优化策略
8.1 并行启动
// 并行任务调度 (src/core/manager.c)
static void manager_dispatch_run_queue(Manager *m) {
Job *j;
while ((j = hashmap_first(m->run_queue))) {
// 检查是否可以并行执行
if (job_is_ready(j)) {
job_run_and_invalidate(j);
hashmap_remove(m->run_queue, j);
} else {
break; // 等待依赖完成
}
}
}
8.2 缓存机制
// 单元配置缓存 (src/core/load-fragment.c)
static int unit_load_fragment(Unit *u) {
// 检查缓存
if (u->fragment_cached)
return 0;
// 解析配置文件
int r = config_parse(u->fragment_path, u->id,
unit_fragment_table, u);
if (r < 0)
return r;
u->fragment_cached = true;
return 0;
}
9. 测试体系
9.1 单元测试
// 测试用例示例 (src/test/test-unit.c)
static void test_unit_type(void) {
assert_se(unit_type_from_string("service") == UNIT_SERVICE);
assert_se(unit_type_from_string("socket") == UNIT_SOCKET);
assert_se(unit_type_from_string("target") == UNIT_TARGET);
}
9.2 集成测试
# test/TEST-01-BASIC-SYSTEM
#!/usr/bin/env bash
set -euxo pipefail
# 启动基本测试环境
systemd-nspawn \
--directory=/var/tmp/systemd-test \
--boot \
--machine=systemd-test \
--tmpfs=/tmp \
--bind-ro=/usr/lib/systemd
10. 总结
Systemd 作为现代 Linux 系统的核心组件,展现了以下架构特点:
10.1 设计优势
- 高度模块化: 清晰的分层架构,便于维护和扩展
- 并行执行: 充分利用系统资源,提升启动速度
- 统一接口: 通过 D-Bus 提供统一的系统管理接口
- 安全性: 多层安全机制,保障系统稳定运行
10.2 技术特色
- 事件驱动: 基于 sd-event 的高效事件循环
- 依赖管理: 智能的依赖解析和任务调度
- 资源控制: 深度集成 cgroup 实现资源隔离
- 向后兼容: 保持与传统 SysV init 的兼容性
10.3 代码质量
- 规范编码: 严格的代码规范和安全检查
- 全面测试: 覆盖单元测试、集成测试、模糊测试
- 文档完善: 详细的代码注释和开发文档
- 持续集成: 自动化测试和代码质量检查
这种架构设计使得 systemd 在功能强大、性能优越的同时,保持了良好的可维护性和扩展性,是现代系统软件工程的优秀典范。

221

被折叠的 条评论
为什么被折叠?



