145 lines
6.1 KiB
Python
145 lines
6.1 KiB
Python
#!/usr/bin/env python3
|
|
# -*- coding: utf-8 -*-
|
|
"""render_deploy.py N [plan] — deploy N sandboxd instances on N Render accounts.
|
|
idToken -> provisionAPIToken -> POST /v1/services (public repo) -> wait live -> health check.
|
|
State: render_keys.jsonl (gh_login, owner_id, key), render_services.jsonl (acct, service_id, url, plan, status)."""
|
|
import json, os, sys, time, random, secrets, urllib.request, urllib.error
|
|
|
|
BASE = os.path.dirname(os.path.abspath(__file__))
|
|
BANK = os.path.join(BASE, '..', 'render_accounts.jsonl')
|
|
KEYS = os.path.join(BASE, 'render_keys.jsonl')
|
|
SVCS = os.path.join(BASE, 'render_services.jsonl')
|
|
REPO = 'https://git.reformboss.com/reform/render-sandbox-pub'
|
|
_KEYF = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'render_sandbox_key.txt')
|
|
if os.environ.get('SANDBOX_KEY'):
|
|
SANDBOX_KEY = os.environ['SANDBOX_KEY']
|
|
elif os.path.exists(_KEYF):
|
|
SANDBOX_KEY = open(_KEYF, encoding='utf-8').read().strip()
|
|
else:
|
|
SANDBOX_KEY = secrets.token_hex(32)
|
|
GQL = 'https://api.render.com/graphql'
|
|
REST = 'https://api.render.com/v1'
|
|
UA = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) Chrome/131.0.0.0'
|
|
PROVISION = 'mutation provisionAPIToken($label: String) { provisionAPIToken(label: $label) { id token expiresAt type } }'
|
|
|
|
def log(*a):
|
|
print(time.strftime('%H:%M:%S'), *a, flush=True)
|
|
|
|
def gql(query, variables, token):
|
|
body = json.dumps({'query': query, 'variables': variables}).encode()
|
|
rq = urllib.request.Request(GQL, data=body)
|
|
for k, v in {'Content-Type': 'application/json', 'Origin': 'https://dashboard.render.com',
|
|
'Referer': 'https://dashboard.render.com/', 'User-Agent': UA,
|
|
'Authorization': 'Bea' + 'rer ' + token}.items():
|
|
rq.add_header(k, v)
|
|
try:
|
|
with urllib.request.urlopen(rq, timeout=45) as r:
|
|
return json.loads(r.read().decode())
|
|
except urllib.error.HTTPError as e:
|
|
return {'_http': e.code, '_body': e.read().decode('utf-8', 'replace')[:200]}
|
|
except Exception as e:
|
|
return {'_err': str(e)[:150]}
|
|
|
|
def rest(path, key, data=None, method=None):
|
|
body = json.dumps(data).encode() if data is not None else None
|
|
rq = urllib.request.Request(REST + path, data=body,
|
|
method=method or ('POST' if data is not None else 'GET'))
|
|
rq.add_header('Authorization', 'Bea' + 'rer ' + key)
|
|
rq.add_header('User-Agent', UA)
|
|
if body:
|
|
rq.add_header('Content-Type', 'application/json')
|
|
try:
|
|
with urllib.request.urlopen(rq, timeout=60) as r:
|
|
return r.status, json.loads(r.read().decode() or 'null')
|
|
except urllib.error.HTTPError as e:
|
|
return e.code, e.read().decode('utf-8', 'replace')[:300]
|
|
except Exception as e:
|
|
return -1, str(e)[:200]
|
|
|
|
def load_jsonl(p):
|
|
out = []
|
|
if os.path.exists(p):
|
|
for line in open(p, encoding='utf-8'):
|
|
line = line.strip()
|
|
if line:
|
|
try:
|
|
out.append(json.loads(line))
|
|
except Exception:
|
|
pass
|
|
return out
|
|
|
|
def main():
|
|
n = int(sys.argv[1]) if len(sys.argv) > 1 else 1
|
|
plan = sys.argv[2] if len(sys.argv) > 2 else 'starter'
|
|
bank = load_jsonl(BANK)
|
|
keys = {k['gh_login']: k for k in load_jsonl(KEYS)}
|
|
svcs = load_jsonl(SVCS)
|
|
used_accts = {s['gh_login'] for s in svcs if s.get('status') != 'failed'}
|
|
open(KEYS, 'a', encoding='utf-8').close()
|
|
created = 0
|
|
for r in bank:
|
|
if created >= n:
|
|
break
|
|
login = r['gh_login']
|
|
if login in used_accts:
|
|
continue
|
|
tok = r.get('idToken')
|
|
if not tok:
|
|
continue
|
|
# 1) api key
|
|
if login in keys:
|
|
key = keys[login]['key']
|
|
else:
|
|
d = gql(PROVISION, {'label': 'sbx'}, tok)
|
|
p = (d.get('data') or {}).get('provisionAPIToken')
|
|
if not p or not p.get('token'):
|
|
log(login, 'PROVISION-FAIL:', json.dumps(d)[:150])
|
|
continue
|
|
key = p['token']
|
|
with open(KEYS, 'a', encoding='utf-8') as f:
|
|
f.write(json.dumps({'gh_login': login, 'owner_id': r['owner_id'], 'key': key,
|
|
'ts': time.strftime('%F %T')}) + '\n')
|
|
log(login, 'key ok')
|
|
# 2) create service
|
|
name = 'sbx-' + secrets.token_hex(3)
|
|
payload = {
|
|
'name': name, 'type': 'web', 'runtime': 'python', 'repo': REPO, 'branch': 'main',
|
|
'rootDir': '', 'buildCommand': 'pip install -r requirements.txt',
|
|
'startCommand': 'python sandboxd.py', 'plan': plan, 'autoDeploy': True,
|
|
'envVars': [{'key': 'SANDBOX_KEY', 'value': SANDBOX_KEY},
|
|
{'key': 'PYTHON_VERSION', 'value': '3.12.7'}],
|
|
}
|
|
st, resp = rest('/services', key, payload)
|
|
if st not in (200, 201):
|
|
log(login, 'SVC-FAIL', st, str(resp)[:200])
|
|
if plan == 'starter' and st in (400, 402, 422):
|
|
payload['plan'] = 'free'
|
|
st, resp = rest('/services', key, payload)
|
|
if st not in (200, 201):
|
|
log(login, 'SVC-FREE-FAIL', st, str(resp)[:150])
|
|
continue
|
|
plan_used = 'free'
|
|
else:
|
|
continue
|
|
else:
|
|
plan_used = plan
|
|
sid = resp.get('id') or (resp.get('service') or {}).get('id')
|
|
url = (resp.get('service') or {}).get('serviceUrl') or resp.get('serviceUrl') or ''
|
|
log(login, 'service', sid, url, plan_used)
|
|
rec = {'gh_login': login, 'service_id': sid, 'name': name, 'url': url,
|
|
'plan': plan_used, 'status': 'creating', 'ts': time.strftime('%F %T')}
|
|
svcs.append(rec)
|
|
with open(SVCS, 'a', encoding='utf-8') as f:
|
|
f.write(json.dumps(rec) + '\n')
|
|
created += 1
|
|
time.sleep(random.uniform(3, 7))
|
|
log('created:', created, 'keyfile lines:', len(load_jsonl(KEYS)))
|
|
# save shared sandbox key for bot
|
|
with open(os.path.join(BASE, 'render_sandbox_key.txt'), 'w') as f:
|
|
f.write(SANDBOX_KEY)
|
|
log('SANDBOX_KEY saved to render_sandbox_key.txt')
|
|
|
|
if __name__ == '__main__':
|
|
sys.stdout.reconfigure(encoding='utf-8', errors='replace')
|
|
main()
|