feat(multicloud): 补齐上线前的多云管理缺口(适配器/动作层/DNS/定时同步)
评估发现项目只有台账能力,缺失真正的多云管理链路。本次按缺口逐项补齐: 适配层 - 新增 aws / linode / namesilo 适配器,registry 登记;阿里云、腾讯云补 list_domains 与 get_account 余额 - NormalizedVPS 补 expiry_date + charge_type:此前云端同步进来的 VPS 拿不到 到期日,永远进不了续费提醒——而续费提醒正是这套台账存在的理由 - base.py 统一云端错误可读化(http_error_message / cloud_error_text):各厂商 把原因放的位置都不同(Linode errors[].reason、Cloudflare errors[].message、 腾讯 Response.Error.Message、AWS XML),此前直接 str(e) 会把 httpx 的多行文本 连同 MDN 链接弹给用户 动作层与 DNS - 新增 /api/actions:实例启停/重启/续费,写操作全部二次确认 + 审计 - 新增 Cloudflare DNS 记录的增删改查 定时同步 - scripts/sync_all_assets.py + /api/sync/assets + vps-sync-assets.timer(08:30) - 08:30 而非随机时刻:必须早于 09:00 的续费检查,否则提醒读到上一天的旧到期日 - sync_all_assets 修正计数:每一项子同步都失败时不再计为「成功」,否则凭证过期 会显示「成功 1」,用户以为数据拉到了、实际一条没有 数据一致性 - AssetRead 输出 external_id(只出不进):前端「云操作」「DNS」按钮靠它渲染, 缺了则所有按钮永远出不来 - import_assets 落库 external_id:导出带了去重键而导入丢弃,会让迁移后首次同步 把所有云端资产当新增再建一份 - _align_preset_providers 取代 _backfill_provider_services:库里声明但注册表未 实现的 sdk_type 清空(声明支持却不支持,比明说不支持更糟),services 只增量 补标签不覆盖,用户自建平台不动 前端如实展示 - cost 为 0 统一显示「未填」而非「0 USD」:0 既可能是没填、也可能是云端不返回 价格,而汇总处又把 0 当「无费用」排除,两处口径不一致 - 总览「本年支出」增加 year_cost_missing,把合计的覆盖缺口说出来 - DNS 弹窗补 MX/SRV 优先级与备注;列表请求失败时 provider 用资产自带 slug 兜底, 否则 Cloudflare 代理勾选框永远不出现 测试:257 -> 309 passed
This commit is contained in:
@@ -0,0 +1,213 @@
|
||||
"""Linode(Akamai)适配器(REST API v4,Bearer Token)
|
||||
|
||||
API 文档:https://www.linode.com/docs/api/
|
||||
所需配置:{"api_key": "..."}(Personal Access Token)
|
||||
|
||||
覆盖:实例清单与启停/重启、账户余额、托管域名清单、DNS 记录增删改查。
|
||||
Linode 为按小时计费,无「续费」概念,故不实现 renew_instance。
|
||||
DNS 的 zone_id 是数字域名 ID(/domains 返回的 id),不是域名字符串。
|
||||
"""
|
||||
|
||||
import httpx
|
||||
|
||||
from app.adapters.base import (
|
||||
AccountInfo,
|
||||
BaseAdapter,
|
||||
NormalizedDNSRecord,
|
||||
NormalizedDomain,
|
||||
NormalizedVPS,
|
||||
parse_iso_date,
|
||||
)
|
||||
from app.adapters.registry import register
|
||||
|
||||
_STATUS_MAP = {"running": "active", "offline": "stopped", "booting": "active", "shutting_down": "stopped"}
|
||||
|
||||
|
||||
@register("linode-api")
|
||||
class LinodeAdapter(BaseAdapter):
|
||||
required_config = ["api_key"]
|
||||
BASE = "https://api.linode.com/v4"
|
||||
|
||||
def _headers(self) -> dict:
|
||||
return {"Authorization": f"Bearer {self.config.get('api_key', '')}"}
|
||||
|
||||
def _request(self, method: str, path: str, json_body: dict = None) -> dict:
|
||||
with httpx.Client(timeout=30) as client:
|
||||
resp = client.request(method, self.BASE + path, headers=self._headers(), json=json_body)
|
||||
resp.raise_for_status()
|
||||
return resp.json() if resp.content else {}
|
||||
|
||||
def _get(self, path: str) -> dict:
|
||||
return self._request("GET", path)
|
||||
|
||||
@staticmethod
|
||||
def _error_message(e: httpx.HTTPStatusError) -> str:
|
||||
"""Linode 把原因放在 body.errors[0].reason,比裸状态码有用得多"""
|
||||
try:
|
||||
errors = e.response.json().get("errors", [])
|
||||
if errors:
|
||||
return f"HTTP {e.response.status_code}:{errors[0].get('reason')}"
|
||||
except Exception: # noqa: BLE001
|
||||
pass
|
||||
return f"HTTP {e.response.status_code}"
|
||||
|
||||
def test_connection(self) -> dict:
|
||||
try:
|
||||
data = self._get("/account")
|
||||
return {"ok": True, "message": f"连接成功,账户 {data.get('email') or data.get('company') or 'OK'}"}
|
||||
except httpx.HTTPStatusError as e:
|
||||
return {"ok": False, "message": f"{self._error_message(e)}:Token 无效或权限不足"}
|
||||
except Exception as e: # noqa: BLE001
|
||||
return {"ok": False, "message": str(e)}
|
||||
|
||||
# ---------------- 只读清单 ----------------
|
||||
|
||||
def get_account(self) -> AccountInfo:
|
||||
acc = self._get("/account")
|
||||
# Linode 的 balance 为负数表示账户有余额(预付信用),正数表示欠款
|
||||
return AccountInfo(
|
||||
balance=acc.get("balance"),
|
||||
currency="USD",
|
||||
raw=acc,
|
||||
)
|
||||
|
||||
def list_vps(self) -> list:
|
||||
result = []
|
||||
page = 1
|
||||
while True:
|
||||
data = self._get(f"/linode/instances?page={page}&page_size=100")
|
||||
for inst in data.get("data", []):
|
||||
specs = inst.get("specs", {}) or {}
|
||||
mem_mb = specs.get("memory") or 0
|
||||
ipv4 = inst.get("ipv4") or []
|
||||
result.append(
|
||||
NormalizedVPS(
|
||||
external_id=str(inst.get("id")),
|
||||
name=inst.get("label") or str(inst.get("id")),
|
||||
ip_address=ipv4[0] if ipv4 else None,
|
||||
region=inst.get("region"),
|
||||
os=inst.get("image"),
|
||||
cpu_cores=specs.get("vcpus"),
|
||||
memory_gb=round(mem_mb / 1024, 1) if mem_mb else None,
|
||||
disk_gb=specs.get("disk"),
|
||||
status=_STATUS_MAP.get(inst.get("status"), inst.get("status") or "unknown"),
|
||||
currency="USD",
|
||||
charge_type="postpaid",
|
||||
raw=inst,
|
||||
)
|
||||
)
|
||||
if page >= (data.get("pages") or 1):
|
||||
break
|
||||
page += 1
|
||||
return result
|
||||
|
||||
def list_domains(self) -> list:
|
||||
result = []
|
||||
page = 1
|
||||
while True:
|
||||
data = self._get(f"/domains?page={page}&page_size=100")
|
||||
for d in data.get("data", []):
|
||||
result.append(
|
||||
NormalizedDomain(
|
||||
external_id=str(d.get("id")),
|
||||
domain_name=d.get("domain"),
|
||||
registrar="linode",
|
||||
# 仅 Linode 注册的域名有 expiry;纯 DNS 托管的为 null
|
||||
expiry_date=parse_iso_date(d.get("expiry")),
|
||||
status="active" if d.get("status") == "active" else (d.get("status") or "unknown"),
|
||||
raw=d,
|
||||
)
|
||||
)
|
||||
if page >= (data.get("pages") or 1):
|
||||
break
|
||||
page += 1
|
||||
return result
|
||||
|
||||
# ---------------- 实例管理动作 ----------------
|
||||
|
||||
def _instance_action(self, external_id: str, verb: str, label: str) -> dict:
|
||||
try:
|
||||
self._request("POST", f"/linode/instances/{external_id}/{verb}")
|
||||
return {"ok": True, "message": f"{label}指令已下发"}
|
||||
except httpx.HTTPStatusError as e:
|
||||
return {"ok": False, "message": f"{self._error_message(e)}:{label}失败"}
|
||||
except Exception as e: # noqa: BLE001
|
||||
return {"ok": False, "message": f"{label}失败:{e}"}
|
||||
|
||||
def start_instance(self, external_id: str) -> dict:
|
||||
return self._instance_action(external_id, "boot", "开机")
|
||||
|
||||
def stop_instance(self, external_id: str) -> dict:
|
||||
return self._instance_action(external_id, "shutdown", "关机")
|
||||
|
||||
def reboot_instance(self, external_id: str) -> dict:
|
||||
return self._instance_action(external_id, "reboot", "重启")
|
||||
|
||||
# ---------------- DNS 记录管理 ----------------
|
||||
|
||||
def list_dns_records(self, zone_id: str) -> list:
|
||||
result = []
|
||||
page = 1
|
||||
while True:
|
||||
data = self._get(f"/domains/{zone_id}/records?page={page}&page_size=100")
|
||||
for r in data.get("data", []):
|
||||
result.append(
|
||||
NormalizedDNSRecord(
|
||||
record_id=str(r.get("id")),
|
||||
zone_id=zone_id,
|
||||
name=r.get("name") or "",
|
||||
type=r.get("type"),
|
||||
content=r.get("target"),
|
||||
ttl=r.get("ttl_sec"),
|
||||
priority=r.get("priority"),
|
||||
raw=r,
|
||||
)
|
||||
)
|
||||
if page >= (data.get("pages") or 1):
|
||||
break
|
||||
page += 1
|
||||
return result
|
||||
|
||||
@staticmethod
|
||||
def _record_body(record: dict) -> dict:
|
||||
body = {
|
||||
"type": record.get("type", "A"),
|
||||
"name": record.get("name", ""),
|
||||
"target": record.get("content", ""),
|
||||
"ttl_sec": record.get("ttl") or 300,
|
||||
}
|
||||
if record.get("priority") is not None:
|
||||
body["priority"] = record["priority"]
|
||||
return body
|
||||
|
||||
def create_dns_record(self, zone_id: str, record: dict) -> dict:
|
||||
try:
|
||||
data = self._request("POST", f"/domains/{zone_id}/records", self._record_body(record))
|
||||
return {
|
||||
"ok": True,
|
||||
"message": "记录已创建",
|
||||
"record_id": str(data.get("id", "")),
|
||||
"raw": data,
|
||||
}
|
||||
except httpx.HTTPStatusError as e:
|
||||
return {"ok": False, "message": f"{self._error_message(e)}:创建失败"}
|
||||
except Exception as e: # noqa: BLE001
|
||||
return {"ok": False, "message": f"创建失败:{e}"}
|
||||
|
||||
def update_dns_record(self, zone_id: str, record_id: str, record: dict) -> dict:
|
||||
try:
|
||||
self._request("PUT", f"/domains/{zone_id}/records/{record_id}", self._record_body(record))
|
||||
return {"ok": True, "message": "记录已更新"}
|
||||
except httpx.HTTPStatusError as e:
|
||||
return {"ok": False, "message": f"{self._error_message(e)}:更新失败"}
|
||||
except Exception as e: # noqa: BLE001
|
||||
return {"ok": False, "message": f"更新失败:{e}"}
|
||||
|
||||
def delete_dns_record(self, zone_id: str, record_id: str) -> dict:
|
||||
try:
|
||||
self._request("DELETE", f"/domains/{zone_id}/records/{record_id}")
|
||||
return {"ok": True, "message": "记录已删除"}
|
||||
except httpx.HTTPStatusError as e:
|
||||
return {"ok": False, "message": f"{self._error_message(e)}:删除失败"}
|
||||
except Exception as e: # noqa: BLE001
|
||||
return {"ok": False, "message": f"删除失败:{e}"}
|
||||
Reference in New Issue
Block a user