Initial commit: VMware vSphere API simulator scaffold.
Add the FastAPI app, PostgreSQL migrations, Docker/Helm packaging, API contracts, docs, client examples, and the unit/integration/compatibility test suite for local client and tooling labs without a real vCenter.
This commit is contained in:
@@ -0,0 +1,106 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Raw `requests` cookbook against the vSphere REST gateway (no vsphere-automation-sdk)."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
import sys
|
||||
import time
|
||||
from typing import Any
|
||||
|
||||
import requests
|
||||
import urllib3
|
||||
|
||||
urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)
|
||||
|
||||
BASE = os.environ.get("VSPHERE_BASE", "https://localhost").rstrip("/")
|
||||
USER = os.environ.get("VSPHERE_USER", "administrator@vsphere.local")
|
||||
PASSWORD = os.environ.get("VSPHERE_PASSWORD", "VMware1!")
|
||||
VM_NAME = os.environ.get("VSPHERE_VM_NAME", "req-lab-01")
|
||||
|
||||
|
||||
def api(
|
||||
method: str,
|
||||
path: str,
|
||||
*,
|
||||
headers: dict[str, str] | None = None,
|
||||
json_body: dict[str, Any] | None = None,
|
||||
) -> Any:
|
||||
response = requests.request(
|
||||
method,
|
||||
f"{BASE}{path}",
|
||||
headers=headers,
|
||||
json=json_body,
|
||||
verify=False, # local self-signed development certificate only
|
||||
timeout=60,
|
||||
)
|
||||
response.raise_for_status()
|
||||
if response.status_code == 204 or not response.content:
|
||||
return None
|
||||
return response.json()
|
||||
|
||||
|
||||
def wait_task(headers: dict[str, str], task: str, timeout: float = 120.0) -> None:
|
||||
deadline = time.time() + timeout
|
||||
while time.time() < deadline:
|
||||
status = api("GET", f"/api/cis/tasks/{task}", headers=headers)
|
||||
if status.get("status") in {"SUCCEEDED", "FAILED"}:
|
||||
return
|
||||
time.sleep(0.3)
|
||||
raise TimeoutError(task)
|
||||
|
||||
|
||||
def session_headers() -> dict[str, str]:
|
||||
response = requests.post(
|
||||
f"{BASE}/api/session",
|
||||
auth=(USER, PASSWORD),
|
||||
verify=False,
|
||||
timeout=60,
|
||||
)
|
||||
response.raise_for_status()
|
||||
return {"vmware-api-session-id": response.json()}
|
||||
|
||||
|
||||
def main() -> int:
|
||||
headers = session_headers()
|
||||
print("session:", headers["vmware-api-session-id"])
|
||||
|
||||
vms = api("GET", "/api/vcenter/vm", headers=headers)
|
||||
print("vms before:", len(vms))
|
||||
|
||||
moid = api(
|
||||
"POST",
|
||||
"/api/vcenter/vm",
|
||||
headers=headers,
|
||||
json_body={
|
||||
"name": VM_NAME,
|
||||
"guest_OS": "OTHER_GUEST_64",
|
||||
"placement": {
|
||||
"folder": "group-v23",
|
||||
"host": "host-11",
|
||||
"datastore": "datastore-31",
|
||||
"resource_pool": "resgroup-22",
|
||||
},
|
||||
"cpu": {"count": 1},
|
||||
"memory": {"size_MiB": 512},
|
||||
},
|
||||
)
|
||||
print("created:", moid)
|
||||
|
||||
power = api("POST", f"/api/vcenter/vm/{moid}/power?action=start", headers=headers)
|
||||
wait_task(headers, power["task"])
|
||||
|
||||
detail = api("GET", f"/api/vcenter/vm/{moid}", headers=headers)
|
||||
print("power_state:", detail["power_state"])
|
||||
|
||||
power = api("POST", f"/api/vcenter/vm/{moid}/power?action=stop", headers=headers)
|
||||
wait_task(headers, power["task"])
|
||||
|
||||
api("DELETE", f"/api/vcenter/vm/{moid}", headers=headers)
|
||||
api("DELETE", "/api/session", headers=headers)
|
||||
print("ok")
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
@@ -0,0 +1 @@
|
||||
requests>=2.31
|
||||
@@ -0,0 +1,128 @@
|
||||
#!/usr/bin/env python3
|
||||
"""End-to-end Python smoke: REST create/power/guest-file + SOAP CreateVM_Task."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
import sys
|
||||
import xml.etree.ElementTree as ET
|
||||
|
||||
import requests
|
||||
import urllib3
|
||||
|
||||
urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)
|
||||
|
||||
BASE = os.environ.get("VSPHERE_BASE", "https://localhost").rstrip("/")
|
||||
USER = os.environ.get("VSPHERE_USER", "administrator@vsphere.local")
|
||||
PASSWORD = os.environ.get("VSPHERE_PASSWORD", "VMware1!")
|
||||
|
||||
|
||||
def rest_session() -> dict[str, str]:
|
||||
response = requests.post(f"{BASE}/api/session", auth=(USER, PASSWORD), verify=False, timeout=60)
|
||||
response.raise_for_status()
|
||||
return {"vmware-api-session-id": response.json()}
|
||||
|
||||
|
||||
def rest_lifecycle(headers: dict[str, str]) -> str:
|
||||
created = requests.post(
|
||||
f"{BASE}/api/vcenter/vm",
|
||||
headers=headers,
|
||||
json={
|
||||
"name": "py-rest-lab-01",
|
||||
"guest_OS": "OTHER_GUEST_64",
|
||||
"placement": {
|
||||
"folder": "group-v23",
|
||||
"host": "host-11",
|
||||
"datastore": "datastore-31",
|
||||
"resource_pool": "resgroup-22",
|
||||
},
|
||||
"cpu": {"count": 1},
|
||||
"memory": {"size_MiB": 512},
|
||||
},
|
||||
verify=False,
|
||||
timeout=60,
|
||||
)
|
||||
created.raise_for_status()
|
||||
vm = created.json()
|
||||
power = requests.post(
|
||||
f"{BASE}/api/vcenter/vm/{vm}/power",
|
||||
params={"action": "start"},
|
||||
headers=headers,
|
||||
verify=False,
|
||||
timeout=60,
|
||||
)
|
||||
power.raise_for_status()
|
||||
assert "task" in power.json()
|
||||
put = requests.put(
|
||||
f"{BASE}/api/vcenter/vm/{vm}/guest/filesystem",
|
||||
params={"path": "/tmp/python-marker"},
|
||||
headers=headers,
|
||||
json={"content": "ok"},
|
||||
verify=False,
|
||||
timeout=60,
|
||||
)
|
||||
put.raise_for_status()
|
||||
requests.post(
|
||||
f"{BASE}/api/vcenter/vm/{vm}/power",
|
||||
params={"action": "stop"},
|
||||
headers=headers,
|
||||
verify=False,
|
||||
timeout=60,
|
||||
).raise_for_status()
|
||||
requests.delete(
|
||||
f"{BASE}/api/vcenter/vm/{vm}", headers=headers, verify=False, timeout=60
|
||||
).raise_for_status()
|
||||
return vm
|
||||
|
||||
|
||||
def soap_create_vm(session_id: str) -> str:
|
||||
envelope = """<?xml version="1.0"?>
|
||||
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/">
|
||||
<soapenv:Body>
|
||||
<CreateVM_Task xmlns="urn:vim25">
|
||||
<_this type="Folder">group-v23</_this>
|
||||
<config>
|
||||
<name>py-soap-lab-01</name>
|
||||
<guestId>otherGuest64</guestId>
|
||||
<numCPUs>1</numCPUs>
|
||||
<memoryMB>512</memoryMB>
|
||||
<files><vmPathName>[datastore1]</vmPathName></files>
|
||||
</config>
|
||||
<pool type="ResourcePool">resgroup-22</pool>
|
||||
<host type="HostSystem">host-11</host>
|
||||
</CreateVM_Task>
|
||||
</soapenv:Body>
|
||||
</soapenv:Envelope>"""
|
||||
response = requests.post(
|
||||
f"{BASE}/sdk",
|
||||
data=envelope,
|
||||
headers={
|
||||
"Content-Type": "text/xml",
|
||||
"vmware-api-session-id": session_id,
|
||||
"Cookie": f'vmware_soap_session="{session_id}"',
|
||||
},
|
||||
verify=False,
|
||||
timeout=60,
|
||||
)
|
||||
response.raise_for_status()
|
||||
root = ET.fromstring(response.text)
|
||||
task = None
|
||||
for node in root.iter():
|
||||
if node.tag.endswith("returnval") and (node.text or "").startswith("task-"):
|
||||
task = node.text
|
||||
break
|
||||
assert task, response.text
|
||||
return task
|
||||
|
||||
|
||||
def main() -> int:
|
||||
headers = rest_session()
|
||||
rest_vm = rest_lifecycle(headers)
|
||||
soap_task = soap_create_vm(headers["vmware-api-session-id"])
|
||||
print(f"REST VM lifecycle ok: {rest_vm}")
|
||||
print(f"SOAP CreateVM_Task ok: {soap_task}")
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
@@ -0,0 +1,58 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Smoke the native vSphere REST surface against a running simulator."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import sys
|
||||
import urllib.error
|
||||
import urllib.request
|
||||
from base64 import b64encode
|
||||
|
||||
BASE = sys.argv[1] if len(sys.argv) > 1 else "https://localhost"
|
||||
USER = "administrator@vsphere.local"
|
||||
PASSWORD = "VMware1!"
|
||||
|
||||
|
||||
def _req(
|
||||
method: str, path: str, *, headers: dict[str, str] | None = None, data: bytes | None = None
|
||||
):
|
||||
request = urllib.request.Request(
|
||||
f"{BASE}{path}",
|
||||
data=data,
|
||||
method=method,
|
||||
headers=headers or {},
|
||||
)
|
||||
ctx = None
|
||||
if BASE.startswith("https://"):
|
||||
import ssl
|
||||
|
||||
ctx = ssl._create_unverified_context() # noqa: S323 - lab self-signed
|
||||
with urllib.request.urlopen(request, context=ctx) as response: # noqa: S310
|
||||
body = response.read()
|
||||
return response.status, dict(response.headers), body
|
||||
|
||||
|
||||
def main() -> int:
|
||||
basic = b64encode(f"{USER}:{PASSWORD}".encode()).decode()
|
||||
status, headers, body = _req(
|
||||
"POST",
|
||||
"/api/session",
|
||||
headers={"Authorization": f"Basic {basic}"},
|
||||
)
|
||||
print("session", status, body.decode())
|
||||
session = json.loads(body.decode())
|
||||
sess_headers = {"vmware-api-session-id": session}
|
||||
status, _, vms = _req("GET", "/api/vcenter/vm", headers=sess_headers)
|
||||
print("vms", status, vms.decode())
|
||||
status, _, hosts = _req("GET", "/api/vcenter/host", headers=sess_headers)
|
||||
print("hosts", status, hosts.decode())
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
try:
|
||||
raise SystemExit(main())
|
||||
except urllib.error.URLError as error:
|
||||
print(f"failed: {error}", file=sys.stderr)
|
||||
raise SystemExit(1) from error
|
||||
@@ -0,0 +1,73 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Minimal SOAP /sdk smoke (RetrieveServiceContent + Login envelope)."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import ssl
|
||||
import sys
|
||||
import urllib.error
|
||||
import urllib.request
|
||||
|
||||
BASE = sys.argv[1] if len(sys.argv) > 1 else "https://localhost"
|
||||
|
||||
CONTENT = """<?xml version="1.0" encoding="UTF-8"?>
|
||||
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/"
|
||||
xmlns:urn="urn:vim25">
|
||||
<soapenv:Body>
|
||||
<urn:RetrieveServiceContent>
|
||||
<urn:_this type="ServiceInstance">ServiceInstance</urn:_this>
|
||||
</urn:RetrieveServiceContent>
|
||||
</soapenv:Body>
|
||||
</soapenv:Envelope>
|
||||
"""
|
||||
|
||||
LOGIN = """<?xml version="1.0" encoding="UTF-8"?>
|
||||
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/"
|
||||
xmlns:urn="urn:vim25">
|
||||
<soapenv:Body>
|
||||
<urn:Login>
|
||||
<urn:_this type="SessionManager">SessionManager</urn:_this>
|
||||
<urn:userName>administrator@vsphere.local</urn:userName>
|
||||
<urn:password>VMware1!</urn:password>
|
||||
</urn:Login>
|
||||
</soapenv:Body>
|
||||
</soapenv:Envelope>
|
||||
"""
|
||||
|
||||
|
||||
def _post(path: str, body: str) -> tuple[int, str]:
|
||||
req = urllib.request.Request(
|
||||
f"{BASE}{path}",
|
||||
data=body.encode(),
|
||||
method="POST",
|
||||
headers={"Content-Type": "text/xml; charset=utf-8", "SOAPAction": '""'},
|
||||
)
|
||||
ctx = ssl._create_unverified_context() if BASE.startswith("https://") else None # noqa: S323
|
||||
with urllib.request.urlopen(req, context=ctx) as resp: # noqa: S310
|
||||
return int(resp.status), resp.read().decode()
|
||||
|
||||
|
||||
def main() -> int:
|
||||
status, body = _post("/sdk", CONTENT)
|
||||
print("RetrieveServiceContent", status, "ServiceContent" in body)
|
||||
if "ServiceContent" not in body:
|
||||
return 1
|
||||
status, body = _post("/sdk", LOGIN)
|
||||
login_ok = "LoginResponse" in body or "UserSession" in body or "key>" in body
|
||||
print("Login", status, login_ok)
|
||||
if not login_ok:
|
||||
print(body[:400], file=sys.stderr)
|
||||
return 1
|
||||
wsdl = urllib.request.Request(f"{BASE}/sdk/vimService.wsdl")
|
||||
ctx = ssl._create_unverified_context() if BASE.startswith("https://") else None # noqa: S323
|
||||
with urllib.request.urlopen(wsdl, context=ctx) as resp: # noqa: S310
|
||||
print("wsdl", resp.status, len(resp.read()))
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
try:
|
||||
raise SystemExit(main())
|
||||
except urllib.error.URLError as error:
|
||||
print(f"failed: {error}", file=sys.stderr)
|
||||
raise SystemExit(1) from error
|
||||
Reference in New Issue
Block a user