Upload a build with Python

A ready Python script that uploads your build and waits for its stream test. Copy it, set your API key, run it. Part of Automated upload.

Before you start

The script

Python 3.8 or newer, nothing to install. Save as e3ds_upload.py, then:

# macOS / Linux
export E3DS_API_KEY="your API key"
python3 e3ds_upload.py MyGame.zip MyGame

# Windows (Command Prompt)
set E3DS_API_KEY=your API key
python e3ds_upload.py MyGame.zip MyGame
#!/usr/bin/env python3
"""Upload an Unreal / Unity build (.zip) to Eagle 3D Streaming and wait for its stream test.

    python e3ds_upload.py <build.zip> <app name> [options]          (Python 3.8+, nothing to install)

Options:
  --part-size MB   size of each part (default: our server picks - 10 MB under 1 GB, 50 MB under 10 GB).
                   5 MB .. 5000 MB, at most 10,000 parts. As big as the file = the whole file in one part.
  --parallel N     how many parts are sent at the same time (default 4)
  --timeout MIN    how long to wait for the stream-test result (default 45)
  --no-wait        upload only; the result comes by email and in the Control Panel

Your API key is read from the environment variable E3DS_API_KEY (Control Panel -> Developer Section -> API key).
If the upload stops (network, closed window), run the same command again: it continues where it stopped.

Exit codes: 0 passed (also "passed, but a newer version is live") or uploaded with --no-wait;
            1 the stream test failed;  2 not tested - a newer upload of the same app is tested instead;
            3 no result within --timeout;  4 the upload itself failed (API key, file, network).

Steps (the same as the REST API guide on docs.eagle3dstreaming.com):
  1. POST /v1/uploads/app-builds               start: the uploadId, the new version, the first part addresses
  2. PUT each part to its address              (POST .../app-builds/<uploadId>/parts gives more addresses)
  3. POST .../app-builds/<uploadId>/complete   our server finishes the file and starts the stream test itself
  4. GET  .../app-builds/<uploadId>            (optional) the result - it also comes by email
"""
import json
import os
import sys
import time
import urllib.error
import urllib.request
from concurrent.futures import ThreadPoolExecutor
from datetime import datetime, timezone

API = os.environ.get("E3DS_API_BASE", "https://agw.eagle3dstreaming.com").rstrip("/")
TRIES = 6                # tries per request before giving up
METHOD = "python"        # tells Eagle 3D Streaming how this upload was made
MB = 1048576


class UploadError(Exception):
    pass


def call(method, url, body=None, headers=None, data=None):
    """One HTTP request with retries on network errors and 5xx. Returns (status, response headers, body bytes)."""
    h = dict(headers or {})
    if body is not None:
        data = json.dumps(body).encode()
        h["Content-Type"] = "application/json"
    last = None
    for attempt in range(1, TRIES + 1):
        try:
            req = urllib.request.Request(url, data=data, method=method, headers=h)
            with urllib.request.urlopen(req, timeout=900) as r:
                return r.status, r.headers, r.read()
        except urllib.error.HTTPError as e:
            if e.code < 500:
                return e.code, e.headers, e.read()
            last = f"HTTP {e.code}"
        except Exception as e:  # network trouble: wait and try again
            last = str(e)
        print(f"   try {attempt}/{TRIES} failed ({last})" + (" - trying again" if attempt < TRIES else ""), flush=True)
        if attempt < TRIES:  # no wait after the last try
            time.sleep(min(30, 2 ** attempt))
    raise UploadError(f"giving up after {TRIES} tries: {last}")


def js(body):
    try:
        return json.loads(body or b"{}")
    except ValueError as e:
        print(f"   (answer is not JSON: {e})")
        return {}


def error_text(st, body):
    e = js(body).get("error")
    return f"HTTP {st}: " + (e.get("message", "") if isinstance(e, dict) else str(e or body[:300]))


def read_part(path, n, part_size):
    with open(path, "rb") as f:
        f.seek((n - 1) * part_size)
        return f.read(part_size)


def show_sent(sent, size):
    print(f"2. sent {sent / MB:.1f} / {size / MB:.1f} MB ({100 * sent // size}%)", flush=True)


def wait_for(get_state, app, version, opts):
    """Asks get_state() every 30 s; it answers ("passed"|"not-live"|"failed"|"replaced"|None, text)."""
    if opts["no_wait"]:
        print("   not waiting: the result comes by email and in the Control Panel")
        return 0
    print(f"   waiting for the stream test (up to {opts['timeout']:g} minutes)")
    deadline = time.time() + opts["timeout"] * 60
    while time.time() < deadline:
        time.sleep(30)
        state, text = get_state()
        if state == "passed":
            print(f"4. PASSED - app '{app}', version {version} is live")
            return 0
        if state == "not-live":
            print(f"4. PASSED, but a newer version is live ({text}) - app '{app}', version {version} is kept as a version")
            return 0
        if state == "failed":
            print(f"4. FAILED - app '{app}', version {version}: {text}")
            return 1
        if state == "replaced":
            print(f"4. REPLACED by a newer upload {text} - app '{app}', version {version} was not tested")
            return 2
        print(f"   {datetime.now().strftime('%H:%M:%S')} {text or 'testing'}...", flush=True)
    print(f"4. NO RESULT after {opts['timeout']:g} minutes - it will come by email and in the Control Panel")
    return 3


def upload(path, app, key, size, opts):
    """The upload API: start, send the parts, finish - our server starts the stream test."""
    auth = {"Authorization": f"Bearer {key}"}
    base = f"{API}/v1/uploads/app-builds"
    start = {"app": app, "fileName": os.path.basename(path), "fileSize": size, "method": METHOD}
    if opts["part_mb"]:
        start["partSize"] = int(opts["part_mb"] * MB)
    st, _, b = call("POST", base, start, auth)
    if st >= 300:
        raise UploadError(f"could not start the upload ({error_text(st, b)})")
    up = js(b)
    up_id, version, part_size, total = up["uploadId"], up["version"], int(up["partSize"]), int(up["totalParts"])
    done = {p["partNumber"] if isinstance(p, dict) else int(p) for p in up.get("doneParts") or []}
    urls = {p["partNumber"]: p["url"] for p in up.get("parts") or []}
    todo = [n for n in range(1, total + 1) if n not in done]
    print(f"1. upload started: app '{app}', version {version}, {total} part(s) of {part_size / MB:.4g} MB,"
          f" {opts['parallel']} at a time" + (f" - resuming, {len(done)} part(s) already sent" if done else ""))

    def put(n):
        st, _, _ = call("PUT", urls[n], data=read_part(path, n, part_size), headers={"Content-Type": "application/octet-stream"})
        if st >= 300:
            raise UploadError(f"part {n} was not accepted (HTTP {st})")

    sent = min(size, len(done) * part_size)
    with ThreadPoolExecutor(opts["parallel"]) as pool:
        for i in range(0, len(todo), opts["parallel"]):
            batch = todo[i:i + opts["parallel"]]
            missing = [n for n in batch if n not in urls]
            if missing:  # more part addresses
                st, _, b = call("POST", f"{base}/{up_id}/parts", {"partNumbers": missing}, auth)
                if st >= 300:
                    raise UploadError(f"could not get part addresses ({error_text(st, b)})")
                urls.update({p["partNumber"]: p["url"] for p in js(b)["parts"]})
            list(pool.map(put, batch))
            sent = min(size, sent + len(batch) * part_size)
            show_sent(sent, size)

    st, _, b = call("POST", f"{base}/{up_id}/complete", None, auth, data=b"")
    if st >= 300:
        raise UploadError(f"could not complete the upload ({error_text(st, b)})")
    print(f"3. upload complete - our server starts the stream test by itself (upload {up_id})")

    def get_state():
        st, _, b = call("GET", f"{base}/{up_id}", headers=auth)
        s = js(b)
        if s.get("state") == "passed":
            return ("passed", "") if s.get("live") is not False else ("not-live", s.get("liveVersion"))
        if s.get("state") == "failed":
            return "failed", f"{s.get('reason')}  {s.get('report') or ''}"
        if s.get("state") == "replaced":
            return "replaced", s.get("replacedBy") or ""
        return None, s.get("state") or f"HTTP {st}"
    return wait_for(get_state, app, version, opts)


def main():
    try:  # each line at once, also in a CI log (stdout is a pipe there, so Python would hold the lines back)
        sys.stdout.reconfigure(line_buffering=True)
    except AttributeError as e:
        print(f"   (could not switch to line-by-line output: {e})")
    args, opts = [], {"part_mb": 0.0, "parallel": 4, "timeout": 45.0, "no_wait": False}
    argv = sys.argv[1:]
    try:
        while argv:
            a = argv.pop(0)
            if a == "--part-size":
                opts["part_mb"] = float(argv.pop(0))
            elif a == "--parallel":
                opts["parallel"] = max(1, int(argv.pop(0)))
            elif a == "--timeout":
                opts["timeout"] = float(argv.pop(0))
            elif a == "--no-wait":
                opts["no_wait"] = True
            else:
                args.append(a)
    except (IndexError, ValueError) as e:
        print(f"wrong option value ({e})")
        args = []
    if len(args) != 2:
        print(__doc__)
        return 4
    path, app = args
    key = os.environ.get("E3DS_API_KEY")
    if not key:
        print("Set E3DS_API_KEY to your API key first.")
        return 4
    try:
        size = os.path.getsize(path)
        print(f"Uploading {os.path.basename(path)} ({size / MB:.1f} MB) as app '{app}' to {API}")
        return upload(path, app, key, size, opts)
    except (UploadError, OSError) as e:
        print(f"UPLOAD FAILED: {e}")
        return 4


if __name__ == "__main__":
    sys.exit(main())

Running it, step by step

  1. Check Python: python --version (3.8 or newer).
  2. Save the script above as e3ds_upload.py in the same folder as your zip.
  3. Set your API key in the terminal (Windows PowerShell: $env:E3DS_API_KEY = "your API key"; Command Prompt and macOS / Linux: above).
  4. Run python e3ds_upload.py MyGame.zip MyGame — the zip, then the app name.

What it prints, from a real upload of a 218 MB build with --part-size 50:

Uploading MyGame.zip (217.8 MB) as app 'MyGame' to https://agw.eagle3dstreaming.com
1. upload started: app 'MyGame', version v1795149047748, 5 part(s) of 50 MB, 4 at a time
2. sent 200.0 / 217.8 MB (91%)
2. sent 217.8 / 217.8 MB (100%)
3. upload complete (queued) - our server starts the stream test by itself
   22:31:24 queued...
   22:31:54 queued...
   22:32:25 testing...
...
   22:45:34 testing...
4. PASSED - app 'MyGame', version v1795149047748 is live

The exit code is 0 when the build passed, 1 when it failed, 2 when it was not tested because a newer upload of the same app was tested instead, 3 when there was no result within --timeout and 4 when the upload itself failed - run the same command again and it continues where it stopped (in PowerShell: $LASTEXITCODE; in bash: $?), so a pipeline step that runs it stops on a failed build.

Watch it in 1:41

Upload with PythonVideo · 1:41

If the upload stops: run the same command again

Nothing extra is needed to resume. If the upload stops - the network drops, the computer sleeps, the window is closed, Ctrl+C - just run the same command again, with the same zip and the same app name, within 24 hours:

python e3ds_upload.py MyGame.zip MyGame

The script finds the unfinished upload by itself and sends only the parts that are still missing. Its first line then says resuming, N part(s) already sent, and the version number stays the same. A part that fails on its own is sent again automatically (up to six tries), so a short network hiccup needs nothing from you at all. Video of a real run: youtu.be/c0x8wsBRiCs. How it works: Resumable uploads.

When it fails, and keeping the key safe

Every message the script can print, and what it means: when it fails. How to store the key in a pipeline: keep your API key safe. The other ways to upload automatically: Automated upload.

Related

Last updated