> ## Documentation Index
> Fetch the complete documentation index at: https://docs.siflow.cn/llms.txt
> Use this file to discover all available pages before exploring further.

# 使用 Python SDK 管理实例资源

> 使用人工智能平台 Python SDK 查询资源池、购买实例资源、管理用户配额、扩缩容资源池和查看独占池节点。

Python SDK 可用于自动化查询和管理实例资源。使用本文示例前，请先完成 [Python SDK 快速开始](./python-sdk-quickstart)，并确认当前账号具备资源池、订单或管理员相关权限。

## 查询资源池

通过 `client.pools` 可以查询当前账号可见的资源池。

```python theme={null}
from siflow import SiFlow

client = SiFlow(region="cn-beijing", cluster="auriga")

pools = client.pools.list()

for row in pools.rows:
    pool_type = row.get("poolType")
    pool_name = row.get("resourcePoolName", row.get("poolName"))
    print(pool_type, pool_name)
```

按资源池类型筛选：

```python theme={null}
shared_pools = client.pools.list(pool_type="shared")
dedicated_pools = client.pools.list(pool_type="dedicated")
exclusive_pools = client.pools.list(pool_type="exclusive")
```

获取专属或独占资源池详情：

```python theme={null}
detail = client.pools.get(pool_id=10, pool_type="exclusive")
print(detail.data)
```

`pool_type` 用于区分资源池类型，可选择 `shared`、`dedicated` 或 `exclusive`。独占池节点、碎片整理等操作通常只适用于独占资源池。

查询当前账号可见的实例规格：

```python theme={null}
instances = client.pools.list_visible_instances()

for instance in instances.rows:
    print(instance)
```

如需限定资源池范围，可以传入资源池 ID：

```python theme={null}
instances = client.pools.list_visible_instances(resource_pool_id=10)
```

查询闲时资源池和可用配额：

```python theme={null}
idle_quotas = client.pools.list_idle_quotas()

for item in idle_quotas.data:
    print(
        item["resourcePoolName"],
        item["instanceName"],
        item["quota"],
        item["used"],
        item["avail"],
    )
```

## 购买实例资源

通过 `client.orders` 可以查询可购买实例规格并创建计算实例订单。

```python theme={null}
available = client.orders.list_available_instances(region="cn-beijing")

for instance in available.rows:
    print(instance["instanceName"], instance.get("gpuType"), instance.get("gpuCount"))
```

购买实例资源：

```python theme={null}
resp = client.orders.buy_instances(
    instances=[
        {
            "instance": "sci.g22-1",
            "quantity": 2,
            "duration_days": 30,
            "auto_renew": False,
        }
    ],
    idempotency_key="buy-instances-20260916-001",
)

print(resp.data)
```

购买完成后，可查询订单状态和到期时间：

```python theme={null}
orders = client.orders.list_instance_orders(status="active", page=1)

for order in orders.rows:
    print(order["id"], order["instanceName"], order.get("expiredAt"))

detail = client.orders.get_instance_order(order_id=100)
print(detail.data)
```

购买会产生费用和资源配额变化。提交前请确认实例规格、数量、购买时长和自动续费设置。

## 续费和自动续费

手动续费：

```python theme={null}
client.orders.renew_instance_order(order_id=100, duration_days=30)
```

按需开启或关闭自动续费：

```python theme={null}
client.orders.set_instance_auto_renew(order_id=100, enabled=True)
# 或者：client.orders.set_instance_auto_renew(order_id=100, enabled=False)
```

如需修改订单过期时间，需要具备相应管理权限：

```python theme={null}
client.orders.set_instance_expiry(
    order_id=100,
    expired_at="2026-12-31T23:59:59Z",
)
```

## 创建资源池

购买实例资源后，可以按需创建专属或独占资源池。共享资源池配额通常由订单和平台策略管理，不通过 `client.pools.create()` 创建。

创建专属资源池：

```python theme={null}
resp = client.pools.create(
    pool_type="dedicated",
    resource_pool_name="team-a-dedicated",
    instance_name="sci.g22-1",
    quota=16,
    authorized_users=["alice", "bob"],
    resource_admins=["admin1"],
    workload_types=["task", "jupyter", "inference"],
    default_quota=4,
)

print(resp.data["id"])
```

创建独占资源池：

```python theme={null}
resp = client.pools.create(
    pool_type="exclusive",
    resource_pool_name="team-a-exclusive",
    instance_name="sci.g22-1",
    quota=8,
    authorized_users=["alice", "bob"],
    resource_admins=["admin1"],
    workload_types=["task", "jupyter"],
)

print(resp.data["id"])
```

创建前请确认可分配配额、资源池名称、授权用户、资源管理员和支持的负载类型。创建后，资源池可被训练任务、开发环境或推理服务引用。

## 扩缩容资源池

扩容资源池：

```python theme={null}
result = client.pools.expand(
    pool_id=10,
    pool_type="exclusive",
    add_count=4,
)

print(result.before, result.after)
```

缩容资源池：

```python theme={null}
result = client.pools.shrink(
    pool_id=10,
    pool_type="exclusive",
    reduce_count=2,
)
```

缩容后配额不能低于已使用量。执行前请确认当前资源占用、待运行任务和服务副本，避免影响正在运行的工作负载。

共享资源池扩缩容时，`pool_id` 通常对应配额 ID。按配额类型调整时，可以传入 `quota_type`：

```python theme={null}
result = client.pools.expand(
    pool_id=42,
    pool_type="shared",
    add_count=4,
    quota_type="ondemand",
)

result = client.pools.shrink(
    pool_id=42,
    pool_type="shared",
    reduce_count=2,
    quota_type="spot",
)
```

## 管理资源池访问控制

更新授权用户、资源管理员或负载类型：

```python theme={null}
client.pools.update_access(
    pool_id=10,
    pool_type="exclusive",
    authorized_users=["alice", "bob", "carol"],
    resource_admins=["admin1"],
    workload_types=["task", "jupyter", "inference"],
)
```

设置资源池管理员：

```python theme={null}
client.pools.set_admins(
    pool_id=10,
    pool_type="exclusive",
    admin_ids=["admin1", "admin2"],
)
```

权限变更会影响用户能否在创建训练任务、开发环境或推理服务时选择该资源池。

检查当前账号可访问的资源池：

```python theme={null}
access = client.admin.check_pool_access()

for pool in access.data:
    print(pool)
```

## 管理用户配额

通过 `client.user_quotas` 可以管理资源池内的用户级配额。

```python theme={null}
quotas = client.user_quotas.list(instance_quota_id=42)

for quota in quotas.data:
    print(quota["userName"], quota["total"], quota["used"])
```

分配用户配额：

```python theme={null}
client.user_quotas.assign(
    instance_quota_id=42,
    allocations=[
        {"userName": "alice", "total": 4},
        {"userName": "bob", "total": 2},
    ],
)
```

更新已有用户配额：

```python theme={null}
client.user_quotas.update(
    instance_quota_id=42,
    allocations=[{"userName": "alice", "total": 8}],
)
```

确认不再需要用户配额后再撤销：

```python theme={null}
client.user_quotas.revoke(ids=[101, 102])
```

调整用户配额前，请确认资源池总配额、当前已用量和用户实际任务需求。

## 管理独占池节点

独占资源池支持查看节点详情：

```python theme={null}
nodes = client.pools.list_nodes(pool_id=10, page=1, page_size=50)

for node in nodes.rows:
    print(node["nodeName"], node["status"], node.get("quotaUsed"), node.get("quotaTotal"))
```

如需整理资源碎片，可先预览方案，再执行整理：

```python theme={null}
preview = client.pools.defrag_preview(pool_id=10)
print(preview.data)

result = client.pools.defrag_execute(
    pool_id=10,
    pods=[
        {"pod_name": "<POD_NAME>", "namespace": "<NAMESPACE>"},
    ],
)
print(result.data)
```

碎片整理可能迁移工作负载。执行前请先查看预览结果，并确认迁移影响。

查看最近一次碎片整理结果和历史记录：

```python theme={null}
latest = client.pools.defrag_latest(pool_id=10)
history = client.pools.defrag_history(pool_id=10, page=1, page_size=10)

print(latest.data)
print(history.rows)
```

独占池还支持自动故障恢复和隔离模式切换：

```python theme={null}
client.pools.enable_auto_recover(pool_id=10)
# 需要关闭时：client.pools.disable_auto_recover(pool_id=10)
```

根据目标隔离模式选择其中一种配置：

```python theme={null}
client.pools.switch_isolation(pool_id=10, mode="shared")
# 或者：client.pools.switch_isolation(pool_id=10, mode="exclusive")
```

这些操作会影响资源池调度策略或节点使用方式。执行前请确认当前运行负载、资源池权限和业务影响。

## 屏蔽和恢复节点

具备运维权限时，可以通过 `client.admin` 屏蔽故障或维护中的节点。

```python theme={null}
import time

client.admin.block_nodes(
    node_names=["gpu-node-01"],
    expire_at=int(time.time()) + 86400,
    scope="tenant",
    blacklist_type="NodeNotIn",
    workload_types=["task"],
    reason="hardware maintenance",
    source="manual",
)
```

查询当前生效的节点屏蔽记录：

```python theme={null}
blocked = client.admin.list_blocked_nodes(only_enabled=True, page=1)
print(blocked)
```

节点恢复后再解除屏蔽：

```python theme={null}
client.admin.unblock_all_for_node(node_name="gpu-node-01")
```

节点屏蔽会影响任务调度范围。操作前请确认影响范围和恢复时间。

查询实例配额总览：

```python theme={null}
info = client.admin.get_instance_quota_info()
print(info.data)
```

## 场景示例

### 购买实例并创建独占资源池

```python theme={null}
available = client.orders.list_available_instances(region="cn-beijing")
for instance in available.rows:
    print(instance["instanceName"], instance.get("gpuType"), instance.get("gpuCount"))

order = client.orders.buy_instances(
    instances=[
        {
            "instance": "sci.g22-1",
            "quantity": 8,
            "duration_days": 30,
            "auto_renew": True,
        }
    ],
    idempotency_key="buy-exclusive-20260916",
)
print(order.data)
```

订单提交后，通过 `list_instance_orders()` 或 `get_instance_order()` 查询状态。将下例中的 `100` 替换为本次订单 ID；仅在订单状态变为 `active`、实例配额已经可用后，再创建资源池。

```python theme={null}
order_detail = client.orders.get_instance_order(order_id=100)
print(order_detail.data)
```

确认订单已经生效后，创建独占资源池：

```python theme={null}
pool = client.pools.create(
    pool_type="exclusive",
    resource_pool_name="team-a-exclusive",
    instance_name="sci.g22-1",
    quota=8,
    authorized_users=["alice", "bob"],
    resource_admins=["admin1"],
    workload_types=["task", "jupyter"],
)

print(pool.data["id"])
```

### 扩容共享配额并分配用户配额

```python theme={null}
quota_id = 42

result = client.pools.expand(
    pool_id=quota_id,
    pool_type="shared",
    add_count=6,
)
print(result.before, result.after)

client.user_quotas.assign(
    instance_quota_id=quota_id,
    allocations=[
        {"userName": "alice", "total": 4},
        {"userName": "bob", "total": 2},
    ],
)

quotas = client.user_quotas.list(instance_quota_id=quota_id)
for quota in quotas.data:
    print(quota["userName"], quota["total"], quota["used"])
```

## 相关文档

* [Python SDK 快速开始](./python-sdk-quickstart)
* [准备实例资源](../resources/prepare-compute-resources)
* [管理资源池和配额](../resources/manage-resource-pools-and-quotas)
