withruntime autoreg: email+code and Google OAuth channels, key issuance, pool API wrapper
This commit is contained in:
@@ -0,0 +1,117 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""wr_api.py — обёртка Runtime API: sandbox create/exec/delete, usage, пул ключей.
|
||||
|
||||
Примеры:
|
||||
python wr_api.py usage
|
||||
python wr_api.py sh "uname -a" # одноразовый сандбокс: создать -> exec -> удалить
|
||||
python wr_api.py create farm02 [vcpu] [memMiB] [diskMiB]
|
||||
python wr_api.py exec <id> "cmd"
|
||||
python wr_api.py list
|
||||
python wr_api.py rm <id>
|
||||
"""
|
||||
import json, sys, time, urllib.request, urllib.error
|
||||
|
||||
BASE = "https://api.withruntime.com"
|
||||
REG = r"C:\Users\User\tmp\wr_accounts.jsonl"
|
||||
|
||||
|
||||
def keys():
|
||||
out = []
|
||||
for l in open(REG, encoding="utf-8"):
|
||||
d = json.loads(l)
|
||||
if d.get("key"):
|
||||
out.append((d.get("alias"), d["key"]))
|
||||
return out
|
||||
|
||||
|
||||
def call(key, method, path, data=None, timeout=120):
|
||||
req = urllib.request.Request(BASE + path, method=method)
|
||||
req.add_header("Authorization", "Bearer " + key)
|
||||
body = None
|
||||
if data is not None:
|
||||
body = json.dumps(data).encode()
|
||||
req.add_header("Content-Type", "application/json")
|
||||
try:
|
||||
with urllib.request.urlopen(req, body, timeout=timeout) as r:
|
||||
raw = r.read().decode()
|
||||
return r.status, (json.loads(raw) if raw.strip() else {})
|
||||
except urllib.error.HTTPError as e:
|
||||
raw = e.read().decode()
|
||||
try:
|
||||
return e.code, json.loads(raw)
|
||||
except Exception:
|
||||
return e.code, {"raw": raw[:400]}
|
||||
|
||||
|
||||
def pick_key():
|
||||
for alias, k in keys():
|
||||
s, d = call(k, "GET", "/v1/usage", timeout=30)
|
||||
if s == 200:
|
||||
left = {a["pool"]: a["left"] for a in d.get("allowances", [])}
|
||||
if left.get("machine-cpu", 0) > 0.5:
|
||||
return alias, k, left
|
||||
return None, None, None
|
||||
|
||||
|
||||
def wait_running(key, sid, timeout=180):
|
||||
t0 = time.time()
|
||||
while time.time() - t0 < timeout:
|
||||
s, d = call(key, "GET", "/v1/sandboxes/%s" % sid, timeout=40)
|
||||
st = (d or {}).get("state") or (d or {}).get("status")
|
||||
if st in ("running", "ready"):
|
||||
return st
|
||||
if st in ("failed", "error"):
|
||||
return st
|
||||
time.sleep(4)
|
||||
return "timeout"
|
||||
|
||||
|
||||
def main():
|
||||
cmd = sys.argv[1] if len(sys.argv) > 1 else "usage"
|
||||
if cmd == "usage":
|
||||
for alias, k in keys():
|
||||
s, d = call(k, "GET", "/v1/usage", timeout=30)
|
||||
if s != 200:
|
||||
print(alias[:34].ljust(34), "ERR", s, str(d)[:80])
|
||||
continue
|
||||
left = {a["pool"]: round(a["left"], 2) for a in d.get("allowances", [])}
|
||||
print(alias[:34].ljust(34), json.dumps(left))
|
||||
return
|
||||
alias, k, left = pick_key()
|
||||
if not k:
|
||||
print("NO KEY with quota left")
|
||||
return
|
||||
print("key:", alias)
|
||||
if cmd == "sh":
|
||||
command = sys.argv[2]
|
||||
s, d = call(k, "POST", "/v1/sandboxes", {"name": "tmp%d" % int(time.time()) % 100000,
|
||||
"vcpu": 1, "memoryMiB": 1024, "diskMiB": 3072})
|
||||
if s not in (200, 201):
|
||||
print("create fail", s, d); return
|
||||
sid = d.get("id") or d.get("sandbox", {}).get("id")
|
||||
print("sandbox", sid, wait_running(k, sid))
|
||||
s, r = call(k, "POST", "/v1/sandboxes/%s:exec" % sid, {"command": command, "user": "root"}, timeout=180)
|
||||
print("exec", s, json.dumps(r)[:1500])
|
||||
call(k, "DELETE", "/v1/sandboxes/%s" % sid, timeout=60)
|
||||
print("deleted")
|
||||
elif cmd == "create":
|
||||
name = sys.argv[2] if len(sys.argv) > 2 else "sbx"
|
||||
vcpu = int(sys.argv[3]) if len(sys.argv) > 3 else 1
|
||||
mem = int(sys.argv[4]) if len(sys.argv) > 4 else 1024
|
||||
disk = int(sys.argv[5]) if len(sys.argv) > 5 else 3072
|
||||
s, d = call(k, "POST", "/v1/sandboxes", {"name": name, "vcpu": vcpu, "memoryMiB": mem, "diskMiB": disk})
|
||||
print(s, json.dumps(d)[:600])
|
||||
elif cmd == "exec":
|
||||
sid, command = sys.argv[2], sys.argv[3]
|
||||
s, r = call(k, "POST", "/v1/sandboxes/%s:exec" % sid, {"command": command, "user": "root"}, timeout=300)
|
||||
print(s, json.dumps(r)[:2000])
|
||||
elif cmd == "list":
|
||||
s, d = call(k, "GET", "/v1/sandboxes")
|
||||
print(s, json.dumps(d)[:1500])
|
||||
elif cmd == "rm":
|
||||
s, d = call(k, "DELETE", "/v1/sandboxes/%s" % sys.argv[2], timeout=60)
|
||||
print(s, json.dumps(d)[:300])
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
Reference in New Issue
Block a user