> For the complete documentation index, see [llms.txt](https://docs.verge.io/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.verge.io/knowledge-base/zh/automation-api/vm-power-management.md).

# 虚拟机电源管理 API

{% hint style="info" %}
**要点**

* 通过 REST API 端点控制虚拟机电源状态
* 支持优雅关机和强制电源操作
* 监控虚拟机电源状态和运行时状态
* 了解虚拟机键与机器键在不同状态检查中的区别
  {% endhint %}

本指南介绍在 VergeOS 中管理虚拟机电源状态，包括启动、停止、重启和监控虚拟机。VergeOS API 提供了全面的电源管理功能，支持优雅操作和强制操作。

**阶段**：虚拟机电源管理（4 之 2） **输入**：从创建开始的虚拟机键（42）、电源操作类型 **输出**：电源状态变化、运行时状态 **上一页**：虚拟机已创建 → [`VM 创建`](/knowledge-base/zh/automation-api/vm-creation-api.md) **常见下一步**:

* 配置虚拟机设置 → [`VM 配置`](/knowledge-base/zh/automation-api/vm-configuration.md)
* 高级操作 → [`VM 高级操作`](/knowledge-base/zh/automation-api/vm-advanced-operations.md)

## 本文档适用于

* “如何通过 API 启动/停止虚拟机”
* “检查虚拟机电源状态”
* “优雅关机与强制关机”
* “虚拟机重启和重置操作”
* “监控虚拟机电源状态”
* “电源管理自动化”
* “虚拟机启动故障排查”
* “计划的电源操作”
* “通过电源控制实现资源优化”

## 快速参考

### 主要端点

* **电源操作**: `POST /api/v4/vm_actions`
* **VM 状态**: `GET /api/v4/vms/{id}`
* **电源状态**: `GET /api/v4/machine_status/{machine_id}`

### 关键操作

* `poweron`：启动虚拟机
* `poweroff`：优雅关机（ACPI）
* `kill`：强制断电
* `reset`：重启虚拟机

### 身份验证

```bash
-H "Authorization: Bearer YOUR_API_KEY"
-H "Content-Type: application/json"
```

### 前提条件

必须先创建虚拟机 → 参见 [`VM 创建`](/knowledge-base/zh/automation-api/vm-creation-api.md)

## API 快速参考

| 操作    | 方法   | 端点                            | 键类型       | 用途         |
| ----- | ---- | ----------------------------- | --------- | ---------- |
| 开机    | POST | `/api/v4/vm_actions`          | VM 键      | 启动虚拟机      |
| 关闭电源  | POST | `/api/v4/vm_actions`          | VM 键      | 优雅关机（ACPI） |
| 强制关闭  | POST | `/api/v4/vm_actions`          | VM 键      | 立即终止       |
| 重新启动  | POST | `/api/v4/vm_actions`          | VM 键      | 重启虚拟机      |
| 虚拟机信息 | GET  | `/api/v4/vms/{id}`            | VM 键      | 配置数据       |
| 电源状态  | GET  | `/api/v4/machine_status/{id}` | Machine 键 | 运行时状态      |

## 故障排查索引

* **409 冲突**：虚拟机已在运行、虚拟机未运行、电源状态不匹配
* **507 资源不足**：集群资源不足，内存/CPU 不可用
* **403 禁止访问**：API 密钥权限不足、集群访问被拒绝、虚拟机访问受限
* **404 未找到**：虚拟机键无效、虚拟机已删除、未找到机器键
* **408 请求超时**：电源操作超时、虚拟机无响应、集群通信失败
* **500 内部服务器错误**：虚拟机管理程序问题、节点问题、存储故障

## 启动虚拟机

### POST /api/v4/vm\_actions

**说明**：为虚拟机通电并等待其进入运行状态。

**通电请求**:

```json
{
  "action": "poweron",
  "params": {},
  "vm": "42"
}
```

**完整 API 调用**:

```bash
curl -X POST "https://your-vergeos.example.com/api/v4/vm_actions" \\
  -H "Authorization: Bearer YOUR_API_KEY" \\
  -H "Content-Type: application/json" \\
  -d '{
    "action": "poweron",
    "params": {},
    "vm": "42"
  }'
```

**响应**: `201 已创建` 当操作被发起时。

{% hint style="success" %}
**最佳实践**

* 通电前始终验证虚拟机配置
* 确保所有必需的磁盘和网络接口都已连接
* 检查集群资源可用性
* 确认虚拟机尚未运行，以避免冲突
  {% endhint %}

## 停止虚拟机

### 优雅断电（ACPI）

**说明**：向来宾操作系统发送 ACPI 关机信号，使其可以正常关闭。

```json
{
  "action": "poweroff",
  "vm": "42"
}
```

**完整 API 调用**:

```bash
curl -X POST "https://your-vergeos.example.com/api/v4/vm_actions" \\
  -H "Authorization: Bearer YOUR_API_KEY" \\
  -H "Content-Type: application/json" \\
  -d '{
    "action": "poweroff",
    "vm": "42"
  }'
```

### 强制断电（Kill）

**说明**：立即终止虚拟机，不允许来宾操作系统正常关闭。仅在优雅关机失败时使用。

```json
{
  "action": "kill",
  "vm": "42"
}
```

**完整 API 调用**:

```bash
curl -X POST "https://your-vergeos.example.com/api/v4/vm_actions" \\
  -H "Authorization: Bearer YOUR_API_KEY" \\
  -H "Content-Type: application/json" \\
  -d '{
    "action": "kill",
    "vm": "42"
  }'
```

{% hint style="warning" %}
**强制断电**

使用 `kill` 操作可能导致数据丢失或损坏。始终先尝试优雅 `poweroff` ，只有在必要时才使用 `kill` 。
{% endhint %}

## 重启虚拟机

### 优雅重启（ACPI）

**说明**：向来宾操作系统发送 ACPI 重置信号，以便干净地重新启动。

```json
{
  "action": "reset",
  "params": {
    "graceful": true
  },
  "vm": "42"
}
```

**完整 API 调用**:

```bash
curl -X POST "https://your-vergeos.example.com/api/v4/vm_actions" \\
  -H "Authorization: Bearer YOUR_API_KEY" \\
  -H "Content-Type: application/json" \\
  -d '{
    "action": "reset",
    "params": {
      "graceful": true
    },
    "vm": "42"
  }'
```

### 硬重置（电源循环）

**说明**：立即重启虚拟机，不允许来宾操作系统正常关闭。

```json
{
  "action": "reset",
  "vm": "42"
}
```

**完整 API 调用**:

```bash
curl -X POST "https://your-vergeos.example.com/api/v4/vm_actions" \\
  -H "Authorization: Bearer YOUR_API_KEY" \\
  -H "Content-Type: application/json" \\
  -d '{
    "action": "reset",
    "vm": "42"
  }'
```

## 虚拟机状态和信息

### GET /api/v4/vms/{id}

**说明**：使用各种字段过滤器检索虚拟机配置和元数据。

**获取完整虚拟机信息**:

```bash
curl "https://your-vergeos.example.com/api/v4/vms/42?fields=most" \\
  -H "Authorization: Bearer YOUR_API_KEY"
```

**响应示例**:

```json
{
  "$key": 42,
  "name": "test",
  "machine": 54,
  "description": "测试虚拟机",
  "enabled": true,
  "created": 1755991665,
  "modified": 1755993248,
  "is_snapshot": false,
  "machine_type": "pc-q35-9.0",
  "allow_hotplug": true,
  "guest_agent": true,
  "cpu_cores": 3,
  "cpu_type": "host",
  "ram": 16384,
  "console": "spice",
  "video": "qxl",
  "sound": "none",
  "os_family": "linux",
  "rtc_base": "utc",
  "boot_order": "cd",
  "console_pass_enabled": false,
  "usb_tablet": true,
  "uefi": true,
  "secure_boot": false,
  "serial_port": false,
  "boot_delay": 5,
  "uuid": "821e96ec-2479-7cc4-7c14-c623557bdd2b",
  "need_restart": false,
  "console_status": 42,
  "cloudinit_datasource": "none",
  "imported": false,
  "created_from": "custom",
  "migration_method": "auto",
  "note": "这是一台测试虚拟机",
  "power_cycle_timeout": 0,
  "allow_export": true,
  "creator": "admin",
  "nested_virtualization": true,
  "disable_hypervisor": true,
  "usb_legacy": false
}
```

## 虚拟机电源状态和运行时状态

### GET /api/v4/machine\_status/{machine\_id}

**说明**：使用机器键检索虚拟机的实际运行时状态和电源状态。

**检查虚拟机电源状态**:

```bash
curl "https://your-vergeos.example.com/api/v4/machine_status/54?fields=most" \\
  -H "Authorization: Bearer YOUR_API_KEY"
```

### 已停止虚拟机响应示例

```json
{
  "$key": 54,
  "machine": 54,
  "running": false,
  "migratable": true,
  "node": null,
  "migrated_node": null,
  "migration_destination": null,
  "started": 1755993338,
  "local_time": 0,
  "status": "stopped",
  "status_info": "",
  "state": "offline",
  "powerstate": false,
  "last_update": 1755993358,
  "running_cores": 3,
  "running_ram": 16384,
  "agent_version": "",
  "agent_features": [],
  "agent_guest_info": []
}
```

### 运行中虚拟机响应示例

```json
{
  "$key": 44,
  "machine": 44,
  "running": true,
  "migratable": true,
  "node": 3,
  "migrated_node": null,
  "migration_destination": null,
  "started": 1755460982,
  "local_time": 0,
  "status": "running",
  "status_info": "",
  "state": "online",
  "powerstate": true,
  "last_update": 1755993927,
  "running_cores": 6,
  "running_ram": 12288,
  "agent_version": "",
  "agent_features": [],
  "agent_guest_info": []
}
```

{% hint style="success" %}
**虚拟机与机器状态**

* **虚拟机信息** (`/api/v4/vms/{vm_key}`）：配置、设置和元数据
* **电源状态** (`/api/v4/machine_status/{machine_key}`）：运行时状态、电源状态和资源使用情况
* 始终使用机器键（而不是虚拟机键）来检查实际电源状态和运行时状态
  {% endhint %}

{% hint style="success" %}
**状态字段**

* `powerstate`：表示虚拟机是否已通电的布尔值
* `running`：表示虚拟机当前是否正在运行的布尔值
* `status`：文本状态（“running”、“stopped”等）
* `state`：整体状态（“online”、“offline”）
* `node`：虚拟机运行所在的物理节点（停止时为 null）
  {% endhint %}

## 电源状态监控

### 仅检查电源状态

对于快速检查电源状态，你可以请求特定字段：

```bash
# 仅检查电源状态
curl "https://your-vergeos.example.com/api/v4/machine_status/54?fields=powerstate,running,status" \
  -H "Authorization: Bearer YOUR_API_KEY"
```

**响应**:

```json
{
  "powerstate": true,
  "running": true,
  "status": "running"
}
```

### 监控电源状态变化

```python
import time
import requests

def wait_for_power_state(machine_id, desired_state, max_retries=10):
    """等待虚拟机达到期望的电源状态"""
    for attempt in range(max_retries):
        response = requests.get(
            f"https://your-vergeos.example.com/api/v4/machine_status/{machine_id}",
            params={"fields": "powerstate,running,status"},
            headers={"Authorization": "Bearer YOUR_API_KEY"}
        )
        
        data = response.json()
        if data.get("powerstate") == desired_state:
            return True
            
        time.sleep(5)  # 每次检查之间等待 5 秒
    
    return False

# 示例用法
if wait_for_power_state("54", True):
    print("虚拟机现在正在运行")
else:
    print("虚拟机未能在超时时间内启动")
```

## 常见电源管理工作流

### 安全关闭虚拟机工作流

```bash
# 第 1 步：尝试优雅关机
curl -X POST "https://your-vergeos.example.com/api/v4/vm_actions" \\
  -H "Authorization: Bearer YOUR_API_KEY" \\
  -H "Content-Type: application/json" \\
  -d '{"action": "poweroff", "vm": "42"}'

# 第 2 步：等待并检查状态（按需重复）
sleep 30
curl "https://your-vergeos.example.com/api/v4/machine_status/54?fields=powerstate,status" \
  -H "Authorization: Bearer YOUR_API_KEY"

# 第 3 步：如果优雅关机失败，则强制关机（在合理超时后）
curl -X POST "https://your-vergeos.example.com/api/v4/vm_actions" \\
  -H "Authorization: Bearer YOUR_API_KEY" \\
  -H "Content-Type: application/json" \\
  -d '{"action": "kill", "vm": "42"}'
```

### 虚拟机重启工作流

```bash
# 第 1 步：优雅重启
curl -X POST "https://your-vergeos.example.com/api/v4/vm_actions" \\
  -H "Authorization: Bearer YOUR_API_KEY" \\
  -H "Content-Type: application/json" \\
  -d '{
    "action": "reset",
    "params": {"graceful": true},
    "vm": "42"
  }'

# 第 2 步：监控重启进度
curl "https://your-vergeos.example.com/api/v4/machine_status/54?fields=powerstate,status,node" \
  -H "Authorization: Bearer YOUR_API_KEY"
```

## 错误处理

### 常见电源管理错误

**错误**: `409 冲突 - 虚拟机已在运行`

```json
{
  "error": "无法启动虚拟机：已处于运行状态"
}
```

**解决方案**: 在发出电源命令前检查当前电源状态。

**错误**: `409 冲突 - 虚拟机未运行`

```json
{
  "error": "无法关闭虚拟机：未处于运行状态"
}
```

**解决方案**：在尝试关机前，验证虚拟机是否确实正在运行。

**错误**: `507 资源不足`

```json
{
  "error": "启动虚拟机所需的集群资源不足"
}
```

**解决方案**：检查集群资源可用性，或降低虚拟机资源需求。

### 操作超时

为电源操作设置适当的超时时间：

* **开机**: 30-60 秒
* **优雅关机**：60-120 秒
* **强制关机**：10-30 秒
* **重新启动**：60-120 秒

{% hint style="info" %}
**相关操作**

* **VM 创建**：参见 [`VM 创建`](/knowledge-base/zh/automation-api/vm-creation-api.md) 用于创建虚拟机
* **配置**：参见 [`VM 配置`](/knowledge-base/zh/automation-api/vm-configuration.md) 用于 CPU/RAM 更改
* **高级操作**：参见 [`VM 高级操作`](/knowledge-base/zh/automation-api/vm-advanced-operations.md) 用于克隆和快照
  {% endhint %}

{% hint style="info" %}
**需要帮助吗？**

如需有关虚拟机电源管理的更多支持：

* 查看 VergeOS 文档门户
* 联系 VergeOS 支持并提供具体的错误信息
* 查看系统日志以获取详细的错误信息
* 查阅 VergeOS 社区论坛
  {% endhint %}


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter, and the optional `goal` query parameter:

```
GET https://docs.verge.io/knowledge-base/zh/automation-api/vm-power-management.md?ask=<question>&goal=<endgoal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
