> 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-advanced-operations.md).

# 虚拟机高级操作 API

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

* 克隆虚拟机并完整复制配置和磁盘
* 创建并恢复虚拟机快照以用于备份和恢复
* 通过自动资源清理安全删除虚拟机
* 全面的错误处理和故障排除指南
  {% endhint %}

本指南介绍 VergeOS 中的高级虚拟机操作，包括克隆、快照管理、删除和故障排除。这些操作为虚拟机生命周期管理和灾难恢复提供了强大的能力。

**阶段**: 虚拟机高级操作（4/4） **输入**: VM 键（42）、操作类型、参数 **输出**: 已克隆的虚拟机、快照、清理确认 **上一页**: 虚拟机已配置 → [`VM 配置`](/knowledge-base/zh/automation-api/vm-configuration.md) **常见操作**:

* 用于模板的克隆 → 新建虚拟机创建周期
* 用于备份的快照 → 恢复工作流
* 用于清理的删除 → 生命周期结束

## 本文档适用于

* "如何通过 API 克隆虚拟机"
* "创建虚拟机快照和备份"
* "从快照恢复虚拟机"
* "安全删除虚拟机和清理"
* "虚拟机故障排除和诊断"
* "模板创建工作流"
* "灾难恢复操作"
* "批量虚拟机管理"
* "资源清理自动化"

## 快速参考

### 主要端点

* **VM 操作**: `POST /api/v4/vm_actions`
* **虚拟机删除**: `DELETE /api/v4/vms/{vm_key}`
* **虚拟机列表**: `GET /api/v4/vms`

### 关键操作

* `克隆`: 创建虚拟机完整副本
* `快照`: 创建虚拟机快照
* `恢复`: 从快照恢复

### 身份验证

```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 键      | 时间点备份  |
| 恢复快照  | POST   | `/api/v4/vm_actions`          | VM 键      | 恢复操作   |
| 列出快照  | GET    | `/api/v4/vms`                 | 筛选查询      | 查找快照   |
| 删除 VM | DELETE | `/api/v4/vms/{id}`            | VM 键      | 完整移除   |
| VM 状态 | GET    | `/api/v4/vms/{id}`            | VM 键      | 配置检查   |
| 操作状态  | GET    | `/api/v4/machine_status/{id}` | Machine 键 | 运行时监控  |

## 故障排查索引

* **409 冲突**: 克隆名称已存在，虚拟机已在运行，操作正在进行
* **507 存储空间不足**: 克隆空间不足，快照存储已满
* **403 禁止访问**: API 密钥权限、虚拟机访问被拒、集群限制
* **404 未找到**: 未找到虚拟机、未找到快照、虚拟机键无效
* **408 请求超时**: 克隆操作超时，快照创建超时
* **422 无法处理的实体**: 克隆参数无效，快照恢复冲突
* **500 内部服务器错误**: 存储系统问题、虚拟机监控器问题、集群故障

## 虚拟机克隆

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

**说明**: 创建虚拟机的完整副本，包括所有磁盘和配置。

### 基础克隆

```json
{
  "params": {
    "name": "测试克隆",
    "quiesce": "true"
  },
  "action": "clone",
  "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 '{
    "params": {
      "name": "测试克隆",
      "quiesce": "true"
    },
    "action": "clone",
    "vm": "42"
  }'
```

**响应示例**:

```json
{
  "response": {
    "vmkey": "43",
    "machinekey": "55",
    "machinestatuskey": "55",
    "clusterkey": "1"
  }
}
```

### 高级克隆选项

```json
{
  "params": {
    "name": "production-clone",
    "description": "用于测试的生产服务器克隆",
    "preserve_macs": "true",
    "preserve_device_uuids": "true",
    "quiesce": "true",
    "cluster": "2"
  },
  "action": "clone",
  "vm": "42"
}
```

### 克隆参数

| 参数                      | 类型  | 必需 | 说明                                 |
| ----------------------- | --- | -- | ---------------------------------- |
| name                    | 字符串 | 是  | 克隆后的虚拟机名称                          |
| description             | 字符串 | 否  | 克隆描述                               |
| 静默                      | 字符串 | 否  | 克隆前使虚拟机静默（"true"/"false"），以确保数据一致性 |
| preserve\_macs          | 字符串 | 否  | 保留 MAC 地址（"true"/"false"）          |
| preserve\_device\_uuids | 字符串 | 否  | 保留设备 UUID（"true"/"false"）          |
| cluster                 | 字符串 | 否  | 目标集群 ID                            |

{% hint style="success" %}
**克隆选项**

* **静默**: 使用 `"quiesce": "true"` 通过短暂暂停虚拟机来确保数据一致性
* **保留 MAC**: 使用 `"preserve_macs": "true"` 以保持相同的 MAC 地址（可能导致网络冲突）
* **保留设备 UUID**: 使用 `"preserve_device_uuids": "true"` 以保持设备标识符
* **跨集群**: 指定不同的集群 ID 以克隆到另一个集群
  {% endhint %}

### 克隆工作流示例

```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 '{
    "params": {
      "name": "backup-clone-$(date +%Y%m%d)",
      "description": "自动备份克隆",
      "quiesce": "true"
    },
    "action": "clone",
    "vm": "42"
  }'

# 步骤 2：验证克隆创建（使用返回的 vmkey）
curl "https://your-vergeos.example.com/api/v4/vms/43?fields=name,description,created" \\
  -H "Authorization: Bearer YOUR_API_KEY"

# 步骤 3：检查克隆电源状态
curl "https://your-vergeos.example.com/api/v4/machine_status/55?fields=powerstate,status" \\
  -H "Authorization: Bearer YOUR_API_KEY"
```

## 虚拟机快照

### 创建快照

```json
{
  "vm": "42",
  "action": "snapshot",
  "params": {
    "name": "pre-update-snapshot",
    "description": "系统更新前"
  }
}
```

**完整 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 '{
    "vm": "42",
    "action": "snapshot",
    "params": {
      "name": "pre-update-snapshot",
      "description": "系统更新前 - $(date)"
    }
  }'
```

### 从快照恢复

```json
{
  "vm": "42",
  "action": "restore",
  "params": {
    "snapshot_id": "snapshot-67890"
  }
}
```

**完整 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 '{
    "vm": "42",
    "action": "restore",
    "params": {
      "snapshot_id": "snapshot-67890"
    }
  }'
```

### 列出虚拟机快照

#### GET /api/v4/vms

使用筛选条件查找快照：

```bash
curl "https://your-vergeos.example.com/api/v4/vms?filter=is_snapshot%20eq%20true%20and%20name%20contains%20'web-server'" \\
  -H "Authorization: Bearer YOUR_API_KEY"
```

**查找某虚拟机的所有快照**:

```bash
curl "https://your-vergeos.example.com/api/v4/vms?filter=is_snapshot%20eq%20true%20and%20parent_vm%20eq%2042" \\
  -H "Authorization: Bearer YOUR_API_KEY"
```

### 快照管理工作流

```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 '{
    "vm": "42",
    "action": "snapshot",
    "params": {
      "name": "maintenance-snapshot-$(date +%Y%m%d-%H%M)",
      "description": "维护前快照"
    }
  }'

# 步骤 2：列出快照以查找快照 ID
curl "https://your-vergeos.example.com/api/v4/vms?filter=is_snapshot%20eq%20true%20and%20parent_vm%20eq%2042&fields=name,description,created" \\
  -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 '{
    "vm": "42",
    "action": "restore",
    "params": {
      "snapshot_id": "found-snapshot-id"
    }
  }'
```

## 虚拟机删除与清理

### 完整删除虚拟机

#### DELETE /api/v4/vms/{vm\_key}

**说明**: 删除虚拟机并自动移除所有关联资源，包括磁盘、NIC、设备和配置。

```bash
curl -X DELETE "https://your-vergeos.example.com/api/v4/vms/42" \\
  -H "Authorization: Bearer YOUR_API_KEY"
```

**响应**: `200 OK` 在删除成功时。

{% hint style="success" %}
**自动清理**

当你使用 `DELETE /api/v4/vms/{vm_key}`删除虚拟机时，VergeOS 会自动移除：

* **所有磁盘** 挂载到虚拟机上的
* **所有网络接口** （NIC）
* **所有设备** （GPU、PCI 直通、USB、TPM 等）
* **虚拟机配置** 及元数据
* **Cloud-init 文件** 及配置
* **虚拟机备注** 及文档
* **关联的机器资源**
  {% endhint %}

### 删除前注意事项

删除虚拟机前，请考虑：

1. **数据备份**: 确保重要数据已备份
2. **快照**: 虚拟机快照可能会随虚拟机一起删除
3. **依赖项**: 检查其他系统是否依赖该虚拟机
4. **网络配置**: 记录任何特殊网络配置
5. **许可**: 考虑软件许可影响

### 安全删除流程

#### 步骤 1：关闭虚拟机（推荐）

```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"
  }'
```

#### 步骤 2：验证电源状态

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

#### 步骤 3：创建最终备份（可选）

```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 '{
    "params": {
      "name": "final-backup-before-deletion",
      "description": "删除虚拟机前的最终备份"
    },
    "action": "clone",
    "vm": "42"
  }'
```

#### 步骤 4：删除虚拟机及所有资源

```bash
curl -X DELETE "https://your-vergeos.example.com/api/v4/vms/42" \\
  -H "Authorization: Bearer YOUR_API_KEY"
```

{% hint style="success" %}
**VM 键用法**

使用 VM 键（例如， `42`）来自 VM 创建响应或 VM 列表，而不是 machine key。删除过程会自动处理所有关联的机器资源。
{% endhint %}

### 无需手动清理

与某些虚拟化平台不同，VergeOS 会自动完成完整的资源清理。你不 **未** 需要手动：

* 删除单个磁盘
* 移除网络接口
* 分离设备
* 清理配置文件
* 移除机器状态条目

单个 `DELETE /api/v4/vms/{vm_key}` 操作会自动处理所有清理。

### 查找孤立资源

```bash
# 查找没有关联机器的磁盘
curl "https://your-vergeos.example.com/api/v4/machine_drives?filter=machine%20eq%20null" \\
  -H "Authorization: Bearer YOUR_API_KEY"

# 查找没有关联机器的 NIC
curl "https://your-vergeos.example.com/api/v4/machine_nics?filter=machine%20eq%20null" \\
  -H "Authorization: Bearer YOUR_API_KEY"
```

## 错误处理与故障排除

### 常见错误场景

#### 虚拟机创建失败

**错误**: `400 错误请求 - 无效的机器类型`

```json
{
  "error": "无效的 machine_type 'invalid-type'。有效选项：pc, q35, pc-i440fx-*, pc-q35-*"
}
```

**解决方案**: 使用受支持列表中的有效机器类型。

#### 电源状态冲突

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

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

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

#### 资源限制

**错误**: `507 存储空间不足`

```json
{
  "error": "第 3 层可用存储空间不足，无法满足请求的磁盘大小"
}
```

**解决方案**: 选择不同的存储层或减小磁盘大小。

#### 克隆失败

**错误**: `409 冲突 - 克隆名称已存在`

```json
{
  "error": "名为 'test clone' 的虚拟机已存在"
}
```

**解决方案**: 为克隆的虚拟机使用唯一名称。

### 监控虚拟机操作

#### 检查操作状态

许多虚拟机操作是异步的。使用以下方式监控进度：

```bash
# 检查虚拟机状态
curl "https://your-vergeos.example.com/api/v4/vms/42?fields=machine%23status" \\
  -H "Authorization: Bearer YOUR_API_KEY"

# 检查机器状态以获取运行时信息
curl "https://your-vergeos.example.com/api/v4/machine_status/54?fields=status,powerstate" \\
  -H "Authorization: Bearer YOUR_API_KEY"
```

#### 操作超时

为长时间运行的操作设置合适的超时：

* **VM 创建**: 5-10 分钟
* **克隆操作**: 10-30 分钟（取决于大小）
* **快照创建**: 2-5 分钟
* **快照恢复**: 5-15 分钟
* **电源状态更改**: 30-60 秒
* **虚拟机删除**: 2-5 分钟

### 重试逻辑

为瞬时故障实现重试逻辑：

```python
import time
import requests

def wait_for_operation_completion(vm_id, max_retries=20):
    """等待虚拟机操作完成"""
    for attempt in range(max_retries):
        response = requests.get(
            f"https://your-vergeos.example.com/api/v4/vms/{vm_id}",
            params={"fields": "machine#status#status as operation_status"},
            headers={"Authorization": "Bearer YOUR_API_KEY"}
        )
        
        status = response.json().get("operation_status", "")
        if status not in ["cloning", "snapshotting", "restoring"]:
            return True
            
        time.sleep(10)  # 每次检查之间等待 10 秒
    
    return False

# 示例用法
if wait_for_operation_completion("42"):
    print("操作成功完成")
else:
    print("操作超时")
```

### 调试虚拟机问题

#### 检查虚拟机配置

```bash
# 获取完整虚拟机配置
curl "https://your-vergeos.example.com/api/v4/vms/42?fields=most" \\
  -H "Authorization: Bearer YOUR_API_KEY"
```

#### 检查机器状态

```bash
# 获取运行时状态和错误
curl "https://your-vergeos.example.com/api/v4/machine_status/54?fields=most" \\
  -H "Authorization: Bearer YOUR_API_KEY"
```

#### 检查系统资源

```bash
# 检查集群资源
curl "https://your-vergeos.example.com/api/v4/clusters/1?fields=resources" \\
  -H "Authorization: Bearer YOUR_API_KEY"

# 检查存储层
curl "https://your-vergeos.example.com/api/v4/storage_tiers" \\
  -H "Authorization: Bearer YOUR_API_KEY"
```

### 最佳实践

1. **始终先测试操作** 在开发环境中进行
2. **创建快照** 在重大更改前
3. **监控资源使用情况** 在操作期间
4. **实施适当的错误处理** 在自动化脚本中
5. **使用描述性名称** 用于克隆和快照
6. **清理未使用的资源** 定期
7. **记录操作流程** 供你的团队使用

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

* **VM 创建**：参见 [`VM 创建`](/knowledge-base/zh/automation-api/vm-creation-api.md) 用于初始虚拟机设置
* **电源管理**：参见 [`VM 电源管理`](/knowledge-base/zh/automation-api/vm-power-management.md) 用于启动/停止操作
* **配置**：参见 [`VM 配置`](/knowledge-base/zh/automation-api/vm-configuration.md) 用于 CPU/RAM 更改
  {% 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-advanced-operations.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.
