Skip to content

refactor: remove PowerManager dependency from session manager#166

Merged
fly602 merged 1 commit intolinuxdeepin:masterfrom
fly602:master
Oct 30, 2025
Merged

refactor: remove PowerManager dependency from session manager#166
fly602 merged 1 commit intolinuxdeepin:masterfrom
fly602:master

Conversation

@fly602
Copy link
Copy Markdown
Contributor

@fly602 fly602 commented Oct 30, 2025

  1. Removed PowerManager D-Bus interface XML definition and generated adaptor files
  2. Replaced PowerManager dependency with direct system checks for power operations
  3. Added virtual machine detection using systemd-detect-virt
  4. Modified CanHibernate() and CanSuspend() to check /sys/power/ mem_sleep directly
  5. Removed m_powerInter member variable and related initialization

The PowerManager service dependency was unnecessary for basic power state checks. The session manager can directly query system files and detect VM environments to determine available power operations, reducing service dependencies and improving reliability.

Influence:

  1. Test hibernation functionality on physical machines with hibernation support
  2. Test suspend functionality on systems with different sleep states
  3. Verify VM detection works correctly in virtualized environments
  4. Test power operations are properly disabled in VMs
  5. Check /sys/power/mem_sleep file access permissions
  6. Verify no regression in shutdown and reboot functionality

重构:从会话管理器中移除 PowerManager 依赖

  1. 删除了 PowerManager D-Bus 接口 XML 定义和生成的适配器文件
  2. 使用直接的系统检查替换 PowerManager 依赖来获取电源操作状态
  3. 添加了使用 systemd-detect-virt 的虚拟机检测功能
  4. 修改 CanHibernate() 和 CanSuspend() 直接检查 /sys/power/mem_sleep 文件
  5. 移除了 m_powerInter 成员变量和相关初始化

PowerManager 服务依赖对于基本的电源状态检查是不必要的。会话管理器可以直
接查询系统文件和检测 VM 环境来确定可用的电源操作,从而减少服务依赖并提高
可靠性。

Influence:

  1. 在支持休眠的物理机器上测试休眠功能
  2. 在不同睡眠状态的系统上测试挂起功能
  3. 验证虚拟化环境中的 VM 检测功能正常工作
  4. 测试 VM 中电源操作是否正确禁用
  5. 检查 /sys/power/mem_sleep 文件访问权限
  6. 验证关机和重启功能没有回归问题

Summary by Sourcery

Refactor session manager to remove dependency on the PowerManager D-Bus interface and replace it with direct system checks and virtual machine detection

New Features:

  • Add detectVirtualMachine() function leveraging systemd-detect-virt to identify VM environments

Enhancements:

  • Remove PowerManager XML definitions, generated adaptor files, and m_powerInter member
  • Update CanHibernate() and CanSuspend() to use POWER_CAN_SLEEP environment variable, VM status, and direct /sys/power/mem_sleep checks
  • Clean up CMakeLists by dropping PowerManager D-Bus interface generation

1. Removed PowerManager D-Bus interface XML definition and generated
adaptor files
2. Replaced PowerManager dependency with direct system checks for power
operations
3. Added virtual machine detection using systemd-detect-virt
4. Modified CanHibernate() and CanSuspend() to check /sys/power/
mem_sleep directly
5. Removed m_powerInter member variable and related initialization

The PowerManager service dependency was unnecessary for basic power
state checks. The session manager can directly query system files and
detect VM environments to determine available power operations, reducing
service dependencies and improving reliability.

Influence:
1. Test hibernation functionality on physical machines with hibernation
support
2. Test suspend functionality on systems with different sleep states
3. Verify VM detection works correctly in virtualized environments
4. Test power operations are properly disabled in VMs
5. Check /sys/power/mem_sleep file access permissions
6. Verify no regression in shutdown and reboot functionality

重构:从会话管理器中移除 PowerManager 依赖

1. 删除了 PowerManager D-Bus 接口 XML 定义和生成的适配器文件
2. 使用直接的系统检查替换 PowerManager 依赖来获取电源操作状态
3. 添加了使用 systemd-detect-virt 的虚拟机检测功能
4. 修改 CanHibernate() 和 CanSuspend() 直接检查 /sys/power/mem_sleep
文件
5. 移除了 m_powerInter 成员变量和相关初始化

PowerManager 服务依赖对于基本的电源状态检查是不必要的。会话管理器可以直
接查询系统文件和检测 VM 环境来确定可用的电源操作,从而减少服务依赖并提高
可靠性。

Influence:
1. 在支持休眠的物理机器上测试休眠功能
2. 在不同睡眠状态的系统上测试挂起功能
3. 验证虚拟化环境中的 VM 检测功能正常工作
4. 测试 VM 中电源操作是否正确禁用
5. 检查 /sys/power/mem_sleep 文件访问权限
6. 验证关机和重启功能没有回归问题
@deepin-ci-robot
Copy link
Copy Markdown

deepin pr auto review

我来分析一下这个代码变更:

  1. 主要变更内容:
  • 移除了 PowerManager1 相关的 D-Bus 接口和实现
  • 添加了虚拟机检测功能
  • 修改了休眠和挂起的判断逻辑
  1. 代码质量分析:

优点:

  • 简化了代码结构,移除了不必要的 D-Bus 依赖
  • 使用系统级工具(systemd-detect-virt)进行虚拟机检测,更可靠
  • 直接检查 /sys/power/mem_sleep 文件来判断挂起支持,更直接

需要改进的地方:

  1. 虚拟机检测函数:
bool SessionManager::detectVirtualMachine() {
    QProcess process;
    process.start("/usr/bin/systemd-detect-virt", QStringList());
    process.waitForFinished(-1);
    
    if (process.exitCode() != 0) {
        qWarning() << "Failed to detect virtual machine, error:" << process.errorString();
        return false;
    }
    
    QString name = QString::fromUtf8(process.readAllStandardOutput()).trimmed();
    return name != "none" && !name.isEmpty();
}

建议改进:

  • 添加超时限制,避免无限等待
  • 增加错误处理的详细程度
  • 考虑缓存检测结果,避免重复检测

改进版本:

bool SessionManager::detectVirtualMachine() {
    static bool isVM = false;
    static bool detected = false;
    
    if (detected) {
        return isVM;
    }

    QProcess process;
    process.start("/usr/bin/systemd-detect-virt", QStringList());
    
    if (!process.waitForFinished(3000)) { // 3秒超时
        qWarning() << "Virtual machine detection timeout";
        process.kill();
        return false;
    }
    
    if (process.exitCode() != 0) {
        qWarning() << "Failed to detect virtual machine. Exit code:" << process.exitCode()
                   << "Error:" << process.errorString();
        return false;
    }
    
    QString name = QString::fromUtf8(process.readAllStandardOutput()).trimmed();
    isVM = (name != "none" && !name.isEmpty());
    detected = true;
    
    qDebug() << "Virtual machine detection result:" << (isVM ? name : "physical machine");
    return isVM;
}
  1. 挂起检测逻辑:
if (!QFile::exists("/sys/power/mem_sleep")) {
    return false;
}

建议改进:

  • 不仅检查文件存在性,还应检查文件内容
  • 添加错误处理

改进版本:

bool SessionManager::CanSuspend()
{
    if (QString(getenv("POWER_CAN_SLEEP")) == "0" || m_isVM) {
        return false;
    }

    QFile file("/sys/power/mem_sleep");
    if (!file.exists()) {
        qWarning() << "Suspend not supported: mem_sleep interface not available";
        return false;
    }

    if (!file.open(QIODevice::ReadOnly | QIODevice::Text)) {
        qWarning() << "Failed to read mem_sleep interface:" << file.errorString();
        return false;
    }

    QString content = file.readAll().trimmed();
    file.close();

    // 检查是否支持 s2idle (suspend-to-idle)
    if (!content.contains("s2idle")) {
        qWarning() << "Suspend not supported: s2idle not available in mem_sleep states";
        return false;
    }

    return true;
}
  1. 安全性考虑:
  • 虚拟机检测使用的是系统命令,应该验证命令的完整性
  • 文件操作应该有适当的权限检查
  • 环境变量的读取应该有合法性验证
  1. 性能优化:
  • 虚拟机检测结果应该缓存
  • 文件检查应该减少重复操作
  • 考虑使用异步方式进行检测
  1. 代码组织:
  • 建议将虚拟机检测相关代码抽取为单独的工具类
  • 电源管理相关的功能应该集中管理
  • 添加更多的日志记录,便于问题追踪

这些改进建议可以提高代码的可靠性、性能和可维护性。

@sourcery-ai
Copy link
Copy Markdown

sourcery-ai Bot commented Oct 30, 2025

Reviewer's Guide

This PR removes the external PowerManager D-Bus dependency by deleting its XML/adaptor definitions, drops the m_powerInter member and related CMake entries, introduces in-process VM detection via systemd-detect-virt, and refactors CanHibernate/CanSuspend to rely on environment variables and direct sysfs checks.

Sequence diagram for CanHibernate/CanSuspend after PowerManager removal

sequenceDiagram
participant "SessionManager"
participant "Environment"
participant "System Files"
participant "systemd-detect-virt"

"SessionManager"->>"Environment": Read POWER_CAN_SLEEP
alt POWER_CAN_SLEEP == "0"
    "SessionManager"-->>"SessionManager": Return false
else
    "SessionManager"->>"systemd-detect-virt": Check VM status
    alt Is VM
        "SessionManager"-->>"SessionManager": Return false
    else
        "SessionManager"->>"System Files": Check /sys/power/mem_sleep
        alt File exists
            "SessionManager"-->>"SessionManager": Return true
        else
            "SessionManager"-->>"SessionManager": Return false
        end
    end
end
Loading

Entity relationship diagram for power state checks after PowerManager removal

erDiagram
SESSION_MANAGER {
    bool CanHibernate
    bool CanSuspend
    bool detectVirtualMachine
    bool m_isVM
}

SESSION_MANAGER ||--|| "sysfs:/sys/power/mem_sleep" : checks
SESSION_MANAGER ||--|| "env:POWER_CAN_SLEEP" : reads
SESSION_MANAGER ||--|| "systemd-detect-virt" : executes
Loading

Class diagram for refactored SessionManager (PowerManager dependency removed)

classDiagram
class SessionManager {
    -QString m_currentUid
    -QString m_soundTheme
    -int m_stage
    -QDBusObjectPath m_currentSessionPath
    -bool m_isVM
    -org::deepin::dde::Audio1 *m_audioInter
    -org::freedesktop::login1::Manager *m_login1ManagerInter
    -org::freedesktop::login1::User *m_login1UserInter
    -org::freedesktop::login1::Session *m_login1SessionInter
    -org::freedesktop::systemd1::Manager *m_systemd1ManagerInter
    -org::freedesktop::DBus *m_DBusInter
    +bool CanHibernate()
    +bool CanSuspend()
    +bool detectVirtualMachine()
}
Loading

Flow diagram for VM detection in SessionManager

flowchart TD
    A["SessionManager starts systemd-detect-virt"] --> B["systemd-detect-virt runs"]
    B --> C["Read output"]
    C --> D{Is output 'none'?}
    D -- Yes --> E["Not a VM"]
    D -- No --> F["Is a VM"]
    F --> G["Set m_isVM = true"]
    E --> H["Set m_isVM = false"]
Loading

File-Level Changes

Change Details Files
Removed PowerManager D-Bus integration and its generated artifacts
  • Deleted PowerManager D-Bus XML definition and adaptor files
  • Removed org_deepin_dde_PowerManager1 header include and m_powerInter member
  • Cleaned up CMakeLists to drop qt_add_dbus_interface for PowerManager
  • Removed m_powerInter initialization from constructor
src/dde-session/impl/sessionmanager.cpp
src/dde-session/impl/sessionmanager.h
src/dde-session/CMakeLists.txt
dbus/interface/org.deepin.dde.PowerManager1.xml
toolGenerate/qdbusxml2cpp/org.deepin.dde.PowerManager1Adaptor.cpp
toolGenerate/qdbusxml2cpp/org.deepin.dde.PowerManager1Adaptor.h
Added virtual machine detection flag via systemd-detect-virt
  • Implemented detectVirtualMachine() function using QProcess
  • Introduced m_isVM member and initialized it in the constructor
  • Included QProcess and QFile headers
src/dde-session/impl/sessionmanager.cpp
src/dde-session/impl/sessionmanager.h
Refactored CanHibernate and CanSuspend to use direct system checks
  • Replaced CanHibernate D-Bus call with getenv check and m_isVM flag
  • Replaced CanSuspend D-Bus call with getenv check, m_isVM flag, and /sys/power/mem_sleep existence check
src/dde-session/impl/sessionmanager.cpp

Tips and commands

Interacting with Sourcery

  • Trigger a new review: Comment @sourcery-ai review on the pull request.
  • Continue discussions: Reply directly to Sourcery's review comments.
  • Generate a GitHub issue from a review comment: Ask Sourcery to create an
    issue from a review comment by replying to it. You can also reply to a
    review comment with @sourcery-ai issue to create an issue from it.
  • Generate a pull request title: Write @sourcery-ai anywhere in the pull
    request title to generate a title at any time. You can also comment
    @sourcery-ai title on the pull request to (re-)generate the title at any time.
  • Generate a pull request summary: Write @sourcery-ai summary anywhere in
    the pull request body to generate a PR summary at any time exactly where you
    want it. You can also comment @sourcery-ai summary on the pull request to
    (re-)generate the summary at any time.
  • Generate reviewer's guide: Comment @sourcery-ai guide on the pull
    request to (re-)generate the reviewer's guide at any time.
  • Resolve all Sourcery comments: Comment @sourcery-ai resolve on the
    pull request to resolve all Sourcery comments. Useful if you've already
    addressed all the comments and don't want to see them anymore.
  • Dismiss all Sourcery reviews: Comment @sourcery-ai dismiss on the pull
    request to dismiss all existing Sourcery reviews. Especially useful if you
    want to start fresh with a new review - don't forget to comment
    @sourcery-ai review to trigger a new review!

Customizing Your Experience

Access your dashboard to:

  • Enable or disable review features such as the Sourcery-generated pull request
    summary, the reviewer's guide, and others.
  • Change the review language.
  • Add, remove or edit custom review instructions.
  • Adjust other review settings.

Getting Help

Copy link
Copy Markdown

@sourcery-ai sourcery-ai Bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hey there - I've reviewed your changes - here's some feedback:

  • Add a timeout to QProcess.waitForFinished or explicitly check for the existence of systemd-detect-virt to prevent blocking if the tool is missing or hangs.
  • Instead of solely checking /sys/power/mem_sleep existence, parse its contents to ensure the required sleep modes (e.g., "deep") are actually supported.
  • Consider refactoring detectVirtualMachine into a standalone helper or service to improve reuse and make it easier to mock or test independently.
Prompt for AI Agents
Please address the comments from this code review:

## Overall Comments
- Add a timeout to QProcess.waitForFinished or explicitly check for the existence of systemd-detect-virt to prevent blocking if the tool is missing or hangs.
- Instead of solely checking /sys/power/mem_sleep existence, parse its contents to ensure the required sleep modes (e.g., "deep") are actually supported.
- Consider refactoring detectVirtualMachine into a standalone helper or service to improve reuse and make it easier to mock or test independently.

Sourcery is free for open source - if you like our reviews please consider sharing them ✨
Help me be more useful! Please click 👍 or 👎 on each comment and I'll use the feedback to improve your reviews.

@deepin-ci-robot
Copy link
Copy Markdown

[APPROVALNOTIFIER] This PR is NOT APPROVED

This pull-request has been approved by: fly602, mhduiy

The full list of commands accepted by this bot can be found here.

Details Needs approval from an approver in each of these files:

Approvers can indicate their approval by writing /approve in a comment
Approvers can cancel approval by writing /approve cancel in a comment

@fly602 fly602 merged commit eccd126 into linuxdeepin:master Oct 30, 2025
17 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants