深入揭秘OpenHarmony核心:SAMGR掌控系统服务全生命周期

内容分享2天前发布
0 0 0

模块概述

SAMGR(System Ability Manager)是OpenHarmony系统服务管理的核心组件,负责系统服务的注册、查询、启动、停止等生命周期管理。该模块位于
foundation/systemabilitymgr/samgr
目录下,是系统服务框架的基础支撑模块。

核心特性

统一服务管理: 集中管理所有系统服务(SystemAbility)动态加载: 支持按需启动系统服务进程分布式支持: 支持跨设备服务发现和调用权限控制: 基于能力模型的权限验证机制故障恢复: 服务死亡通知和自动重启机制性能监控: 内置DFX(Design for X)监控能力

系统定位

在OpenHarmony架构中,SAMGR作为系统服务的中枢神经,连接着:

上层应用: 通过SystemAbilityManagerClient访问系统服务系统服务: 各类SystemAbility的宿主进程内核服务: 通过IPC与底层驱动交互分布式能力: 通过dBinder实现跨设备服务调用

架构设计

核心组件架构


/foundation/systemabilitymgr/samgr/
├── interfaces/                    # 接口定义层
│   └── innerkits/samgr_proxy/include/
│       ├── if_system_ability_manager.h    # 系统能力管理器接口定义
│       └── iservice_registry.h            # 服务注册接口定义
├── services/                      # 服务实现层
│   └── samgr/native/
│       ├── source/
│       │   ├── system_ability_manager.cpp  # 系统能力管理器核心实现
│       │   ├── service_registry.cpp        # 服务注册实现
│       │   ├── main.cpp                    # 服务启动入口
│       │   └── ability_death_recipient.cpp # 能力死亡通知处理
│       └── include/              # 头文件
├── test/                        # 测试代码
├── utils/                       # 工具类
└── README_zh.md                 # 中文说明文档

核心类关系图


┌─────────────────────┐    ┌─────────────────────┐
│ SystemAbilityManager │    │ SystemAbilityManagerClient │
│  (服务端实现)        │    │  (客户端代理)        │
├─────────────────────┤    ├─────────────────────┤
│ - AddSystemAbility() │    │ - GetInstance()      │
│ - CheckSystemAbility()│    │ - GetSystemAbilityManager()│
│ - RemoveSystemAbility()│   │ - DestroySystemAbilityManagerObject()│
│ - SubscribeSystemAbility()│ └─────────────────────┘
│ - LoadSystemAbility()   │
└─────────────────────┘
            │
            │ IPC通信
            │
┌─────────────────────┐
│ ISystemAbilityManager │
│  (接口定义)          │
└─────────────────────┘

进程间通信架构

SAMGR通过Binder机制实现进程间通信,架构如下:


┌─────────────────┐    ┌─────────────────┐    ┌─────────────────┐
│   客户端进程     │    │   SAMGR进程     │    │   服务进程      │
│                 │    │                 │    │                 │
│ ┌─────────────┐ │    │ ┌─────────────┐ │    │ ┌─────────────┐ │
│ │SystemAbility│ │    │ │SystemAbility│ │    │ │SystemAbility│ │
│ │ManagerClient│ │◄──►│ │   Manager   │ │◄──►│ │ 实现类       │ │
│ └─────────────┘ │    │ └─────────────┘ │    │ └─────────────┘ │
│                 │    │                 │    │                 │
│    BinderProxy   │    │   BinderStub    │    │   BinderNative  │
└─────────────────┘    └─────────────────┘    └─────────────────┘

分层架构详解

1. 应用层(Application Layer)

SystemAbilityManagerClient: 单例模式,提供静态访问接口API接口: 封装底层IPC调用,提供简洁的API

2. 框架层(Framework Layer)

SystemAbilityManager: 核心服务管理器实现ServiceRegistry: 服务注册中心OnDemandPolicy: 按需加载策略管理

3. IPC层(IPC Layer)

IServiceRegistry: 服务注册接口ISystemAbilityManager: 系统能力管理接口Binder机制: 跨进程通信实现

4. 系统服务层(System Service Layer)

各类SystemAbility: 具体系统服务实现死亡通知机制: 服务状态监控权限验证: 基于能力模型的安全检查

核心功能实现

1. 系统服务注册机制

源码位置

实现文件:
foundation/systemabilitymgr/samgr/services/samgr/native/source/system_ability_manager.cpp
接口定义:
foundation/systemabilitymgr/interfaces/innerkits/samgr_proxy/include/if_system_ability_manager.h

注册流程详解

// 系统服务注册核心方法
int32_t SystemAbilityManager::AddSystemAbility(
    int32_t systemAbilityId, 
    const sptr<IRemoteObject>& ability,
    const SAExtraProp& extraProp)
{
    // 1. 参数校验
    if (!CheckInputSysAbilityId(systemAbilityId) || ability == nullptr) {
        HILOGW("AddSystemAbility saId %{public}d failed, invalid input", systemAbilityId);
        return ERR_INVALID_VALUE;
    }

    // 2. 容量检查
    {
        unique_lock<shared_mutex> writeLock(abilityMapLock_);
        if (abilityMap_.size() >= MAX_SERVICES) {
            HILOGE("AddSystemAbility failed, reach max capacity");
            return ERR_INVALID_VALUE;
        }
        
        // 3. 构建SA信息
        SAInfo saInfo;
        saInfo.remoteObj = ability;
        saInfo.isDistributed = extraProp.isDistributed;
        saInfo.capability = Str16ToStr8(extraProp.capability);
        saInfo.permission = Str16ToStr8(extraProp.permission);
        
        // 4. 添加到能力映射表
        abilityMap_[systemAbilityId] = std::move(saInfo);
    }

    // 5. 死亡通知注册
    if (abilityDeath_ != nullptr) {
        ability->AddDeathRecipient(abilityDeath_);
    }

    // 6. 分布式注册
    if (extraProp.isDistributed && dBinderService_ != nullptr) {
        std::string strName = std::to_string(systemAbilityId);
        dBinderService_->RegisterRemoteProxy(strName, systemAbilityId);
    }

    // 7. 发送添加通知
    SendSystemAbilityAddedMsg(systemAbilityId, ability);
    
    // 8. 触发DFX监控
    DfxAddSystemAbility(systemAbilityId);
    
    return ERR_OK;
}
参数验证机制

bool SystemAbilityManager::CheckInputSysAbilityId(int32_t systemAbilityId)
{
    // 有效SAID范围检查
    if (systemAbilityId < FIRST_SYS_ABILITY_ID || 
        systemAbilityId >= MAX_SYS_ABILITY_ID) {
        return false;
    }
    
    // 保留SAID检查
    if (IsReservedSystemAbilityId(systemAbilityId)) {
        return false;
    }
    
    return true;
}
注册流程时序图

2. 系统服务查询机制

查询接口实现

// 检查系统能力是否存在
sptr<IRemoteObject> SystemAbilityManager::CheckSystemAbility(int32_t systemAbilityId)
{
    if (!CheckInputSysAbilityId(systemAbilityId)) {
        HILOGW("CheckSystemAbility invalid saId: %{public}d", systemAbilityId);
        return nullptr;
    }

    shared_lock<shared_mutex> readLock(abilityMapLock_);
    auto iter = abilityMap_.find(systemAbilityId);
    if (iter != abilityMap_.end()) {
        // 检查对象是否有效
        if (iter->second.remoteObj != nullptr && iter->second.remoteObj->IsObjectDead()) {
            HILOGW("CheckSystemAbility saId %{public}d is dead", systemAbilityId);
            return nullptr;
        }
        return iter->second.remoteObj;
    }
    return nullptr;
}

// 获取系统能力(支持按需加载)
sptr<IRemoteObject> SystemAbilityManager::GetSystemAbility(int32_t systemAbilityId)
{
    auto ability = CheckSystemAbility(systemAbilityId);
    if (ability != nullptr) {
        return ability;
    }
    
    // 尝试按需加载
    if (LoadSystemAbility(systemAbilityId)) {
        return CheckSystemAbility(systemAbilityId);
    }
    
    return nullptr;
}
缓存机制

// 系统能力缓存实现
class SystemAbilityCache {
private:
    mutable shared_mutex cacheLock_;
    unordered_map<int32_t, weak_ptr<IRemoteObject>> cache_;
    
public:
    sptr<IRemoteObject> Get(int32_t saId) {
        shared_lock<shared_mutex> lock(cacheLock_);
        auto iter = cache_.find(saId);
        if (iter != cache_.end()) {
            return iter->second.lock();
        }
        return nullptr;
    }
    
    void Put(int32_t saId, const sptr<IRemoteObject>& obj) {
        unique_lock<shared_mutex> lock(cacheLock_);
        cache_[saId] = obj;
    }
    
    void Invalidate(int32_t saId) {
        unique_lock<shared_mutex> lock(cacheLock_);
        cache_.erase(saId);
    }
};

3. 动态加载机制

按需加载策略

bool SystemAbilityManager::LoadSystemAbility(int32_t systemAbilityId)
{
    // 1. 检查是否支持按需加载
    if (!IsOnDemandEnable(systemAbilityId)) {
        return false;
    }
    
    // 2. 获取加载策略
    OnDemandPolicy policy;
    if (!GetOnDemandPolicy(systemAbilityId, policy)) {
        return false;
    }
    
    // 3. 执行加载动作
    switch (policy.loadType) {
        case LOAD_BY_CMD:
            return LoadByCommand(policy.loadCmd);
        case LOAD_BY_SERVICE:
            return LoadByService(policy.serviceName);
        case LOAD_BY_CLASS:
            return LoadByClass(policy.className);
        default:
            return false;
    }
}
比如这里以av——

// 加载策略配置示例
struct OnDemandPolicy {
    LoadType loadType;      // 加载类型
    string loadCmd;         // 加载命令
    string serviceName;     // 服务名称
    string className;       // 类名
    int timeoutMs;           // 超时时间
    int retryCount;         // 重试次数
};

比如这里以av_code的服务配置文件为例
{
    "services" : [{
        "name" : "av_codec_service",
        "path" : ["/system/bin/sa_main", "/system/profile/av_codec_service.json"],
        "uid" : "media",
        "gid" : ["media_rw", "system", "vcodec", "dev_dma_heap", "netsys_socket", "vendor_mpp_driver"],
        "secon" : "u:r:av_codec_service:s0",
        "ondemand" : true
        }
    ]
}
首先根据ondemand字段判断是否是动态加载,ondemand:true表示开机加载,ondemand:false表示动态加载

加载策略:

当某个服务把 “ondemand”: true 写进配置后,init 进程不会在系统启动阶段就把该服务拉起,而是等到真正需要它时才启动。

常见的触发条件有两类:

socket 消息:如果该服务同时配置了 socket 节点,init 会提前创建并监听对应的 socket;当 socket
上产生数据读写事件时,init 立即拉起服务。 SAMGR 请求:对于 SA(System Ability)服务,当客户端通过 samgr
首次请求对应的 SA 句柄时,samgr 会检查 sa_profile.xml 中的 ondemand 标记并动态拉起进程。 使用场景
减少冷启动耗时:把不常用或重量级服务做成 ondemand,缩短开机时间。
降低资源占用:服务在空闲时可以自动退出,待再次触发时再拉起,节省内存和 CPU。 小型系统(Linux
内核)和标准系统均支持,但小型系统只能在 Linux 内核上使用。

动态加载流程

4. 服务订阅机制

订阅接口实现

int32_t SystemAbilityManager::SubscribeSystemAbility(
    int32_t systemAbilityId,
    const sptr<ISystemAbilityStatusChange>& listener)
{
    if (listener == nullptr) {
        return ERR_NULL_OBJECT;
    }
    
    if (!CheckInputSysAbilityId(systemAbilityId)) {
        return ERR_INVALID_VALUE;
    }
    
    unique_lock<shared_mutex> lock(listenerMapLock_);
    auto& listeners = listenerMap_[systemAbilityId];
    
    // 避免重复订阅
    for (const auto& item : listeners) {
        if (item->AsObject() == listener->AsObject()) {
            return ERR_OK;
        }
    }
    
    listeners.emplace_back(listener);
    return ERR_OK;
}

// 状态变更通知
void SystemAbilityManager::NotifySystemAbilityChanged(
    int32_t systemAbilityId, SystemAbilityChangedAction action)
{
    shared_lock<shared_mutex> lock(listenerMapLock_);
    auto iter = listenerMap_.find(systemAbilityId);
    if (iter != listenerMap_.end()) {
        for (const auto& listener : iter->second) {
            if (listener != nullptr) {
                listener->OnSystemAbilityChanged(systemAbilityId, action);
            }
        }
    }
}

服务启动流程

启动入口分析

main.cpp实现

int main(int argc, char* argv[])
{
    // 1. 初始化系统能力管理器
    auto samgr = SystemAbilityManager::GetInstance();
    if (samgr == nullptr) {
        HILOGE("Failed to get SystemAbilityManager instance");
        return -1;
    }
    
    // 2. 初始化
    int32_t ret = samgr->Init();
    if (ret != ERR_OK) {
        HILOGE("SystemAbilityManager init failed: %{public}d", ret);
        return ret;
    }
    
    // 3. 设置上下文对象
    sptr<IRemoteObject> samgrObject = samgr->AsObject();
    if (samgrObject != nullptr) {
        SetContextObject(samgrObject);
    }
    
    // 4. 注册到系统能力映射表
    ret = AddSamgrToAbilityMap();
    if (ret != ERR_OK) {
        HILOGE("AddSamgrToAbilityMap failed: %{public}d", ret);
        return ret;
    }
    
    // 5. 设置启动就绪参数
    SetParameter("bootevent.samgr.ready", "true");
    
    // 6. 启动DFX定时器
    samgr->StartDfxTimer();
    
    // 7. 进入工作循环
    return samgr->JoinWorkThread();
}
初始化流程

int32_t SystemAbilityManager::Init()
{
    // 1. 初始化DFX模块
    DfxInit();
    
    // 2. 初始化死亡通知处理
    abilityDeath_ = new SystemAbilityDeathRecipient();
    
    // 3. 初始化分布式服务
    dBinderService_ = DBinderService::GetInstance();
    
    // 4. 加载配置文件
    LoadConfig();
    
    // 5. 初始化线程池
    workHandler_ = std::make_shared<WorkHandler>("SAMGR_WORK");
    
    return ERR_OK;
}

关键数据结构

1. SAInfo结构体


struct SAInfo {
    sptr<IRemoteObject> remoteObj;  // 远程对象
    bool isDistributed;              // 是否分布式
    std::string capability;          // 能力描述
    std::string permission;          // 权限要求
    
    SAInfo() : isDistributed(false) {}
    
    // 拷贝构造函数
    SAInfo(const SAInfo& other) = default;
    SAInfo(SAInfo&& other) noexcept = default;
    
    // 赋值运算符
    SAInfo& operator=(const SAInfo& other) = default;
    SAInfo& operator=(SAInfo&& other) noexcept = default;
};

2. SAExtraProp结构体


struct SAExtraProp {
    bool isDistributed;      // 是否分布式
    bool dumpFlag;          // 是否支持dump
    std::u16string capability;  // 能力描述
    std::u16string permission;    // 权限要求
    
    SAExtraProp() : isDistributed(false), dumpFlag(false) {}
};

3. 能力映射表


// 系统能力映射表定义
using SystemAbilityMap = std::unordered_map<int32_t, SAInfo>;

class SystemAbilityManager {
private:
    SystemAbilityMap abilityMap_;           // 能力映射表
    mutable shared_mutex abilityMapLock_;   // 读写锁
    
    // 监听器映射表
    using ListenerMap = std::unordered_map<int32_t, std::vector<sptr<ISystemAbilityStatusChange>>>;
    ListenerMap listenerMap_;
    mutable shared_mutex listenerMapLock_;
    
    // 死亡通知处理
    sptr<SystemAbilityDeathRecipient> abilityDeath_;
    
    // 分布式服务
    sptr<DBinderService> dBinderService_;
};

线程安全机制

1. 读写锁设计


class SystemAbilityManager {
private:
    // 能力映射表锁
    mutable shared_mutex abilityMapLock_;
    
    // 监听器映射表锁
    mutable shared_mutex listenerMapLock_;
    
    // 进程映射表锁
    mutable shared_mutex processMapLock_;
    
public:
    // 读操作使用共享锁
    sptr<IRemoteObject> CheckSystemAbility(int32_t saId) {
        shared_lock<shared_mutex> lock(abilityMapLock_);
        // 读取操作
    }
    
    // 写操作使用独占锁
    int32_t AddSystemAbility(int32_t saId, const sptr<IRemoteObject>& ability) {
        unique_lock<shared_mutex> lock(abilityMapLock_);
        // 写入操作
    }
};

2. 无锁队列设计


// 消息队列实现
class WorkHandler {
private:
    std::queue<WorkMessage> messageQueue_;
    std::mutex queueMutex_;
    std::condition_variable queueCondition_;
    
public:
    void PostTask(const WorkMessage& msg) {
        std::lock_guard<std::mutex> lock(queueMutex_);
        messageQueue_.push(msg);
        queueCondition_.notify_one();
    }
    
    WorkMessage GetTask() {
        std::unique_lock<std::mutex> lock(queueMutex_);
        queueCondition_.wait(lock, [this] { return !messageQueue_.empty(); });
        
        WorkMessage msg = std::move(messageQueue_.front());
        messageQueue_.pop();
        return msg;
    }
};

开发指导

1. 系统服务ID分配规范

ID范围 用途 示例
0x0000-0x0FFF 保留
0x1000-0x1FFF 系统核心服务 AMS、BMS
0x2000-0x2FFF 硬件抽象层 Camera、Audio
0x3000-0x3FFF 分布式服务 DistributedSchedule
0x4000-0x4FFF 应用服务 Account、Notification
0x5000-0x5FFF 第三方服务 预留

2. 系统服务实现模板


// MySystemAbility.h
#include <system_ability.h>

class MySystemAbility : public SystemAbility {
    DECLARE_SYSTEM_ABILITY(MySystemAbility);
    
public:
    MySystemAbility(int32_t systemAbilityId, bool runOnCreate = true);
    ~MySystemAbility() override;
    
    // 系统能力接口
    void OnStart() override;
    void OnStop() override;
    void OnAddSystemAbility(int32_t systemAbilityId, const std::string& deviceId) override;
    void OnRemoveSystemAbility(int32_t systemAbilityId, const std::string& deviceId) override;
    
private:
    bool Init();
    bool Publish();
    
    bool registerToService_ = false;
};

// MySystemAbility.cpp
MySystemAbility::MySystemAbility(int32_t systemAbilityId, bool runOnCreate)
    : SystemAbility(systemAbilityId, runOnCreate)
{
}

void MySystemAbility::OnStart()
{
    if (!Init()) {
        HILOGE("MySystemAbility init failed");
        return;
    }
    
    if (!Publish()) {
        HILOGE("MySystemAbility publish failed");
        return;
    }
    
    registerToService_ = true;
    HILOGI("MySystemAbility started");
}

bool MySystemAbility::Publish()
{
    sptr<IRemoteObject> ability = this->AsObject();
    return SystemAbilityManagerClient::GetInstance().AddSystemAbility(saId_, ability);
}

3. 客户端调用示例


// 获取系统服务
sptr<IRemoteObject> GetMySystemAbility()
{
    auto samgr = SystemAbilityManagerClient::GetInstance();
    return samgr->GetSystemAbility(MY_SA_ID);
}

// 订阅系统服务状态
class MyStatusChange : public ISystemAbilityStatusChange {
public:
    void OnSystemAbilityChanged(int32_t systemAbilityId, SystemAbilityChangedAction action) override
    {
        switch (action) {
            case SystemAbilityChangedAction::ADD:
                HILOGI("MySystemAbility added");
                break;
            case SystemAbilityChangedAction::REMOVE:
                HILOGI("MySystemAbility removed");
                break;
        }
    }
};

// 使用示例
void SubscribeMySystemAbility()
{
    sptr<MyStatusChange> listener = new MyStatusChange();
    auto samgr = SystemAbilityManagerClient::GetInstance();
    samgr->SubscribeSystemAbility(MY_SA_ID, listener);
}
监控接口

class DfxManager {
public:
    // 记录服务注册时间
    void RecordRegisterTime(int32_t saId, int64_t timestamp);
    
    // 记录服务查询时间
    void RecordQueryTime(int32_t saId, int64_t timestamp);
    
    // 记录服务加载结果
    void RecordLoadResult(int32_t saId, bool success);
    
    // 记录服务死亡
    void RecordServiceDeath(int32_t saId, const std::string& reason);
};

4. 故障排查指南

常见问题及解决方案
问题现象 可能原因 解决方案
服务注册失败 权限不足 检查调用者UID和权限配置
服务查询返回null 服务未注册 确认服务是否已启动并注册
服务突然不可用 进程崩溃 检查死亡通知日志
按需加载失败 配置错误 检查on_demand配置
分布式调用失败 网络问题 检查dBinder配置和网络状态
调试工具

// 内存泄漏检查
class MemoryChecker {
public:
    static void CheckLeaks() {
        // 检查未释放的SAInfo对象
        // 检查未取消的监听器
        // 检查未处理的死亡通知
    }
};

// 死锁检测
class DeadlockDetector {
public:
    static void CheckLocks() {
        // 检查abilityMapLock_的持有时间
        // 检查listenerMapLock_的等待队列
        // 检查processMapLock_的争用情况
    }
};

总结

SAMGR作为OpenHarmony系统服务管理的核心组件,通过统一的服务注册、查询、管理和监控机制,为系统服务提供了完整生命周期管理。其分层架构设计、完善的权限控制、强大的分布式支持以及丰富的调试工具,使其成为OpenHarmony系统服务框架的基石。

© 版权声明

相关文章

暂无评论

none
暂无评论...