Skip to content

launchd service (imagewright.service)

imagewright.service

Run an imagewright server under launchd, so it starts by itself (macOS).

A login service is a LaunchAgent in ~/Library/LaunchAgents: launchd starts it when the user logs in and needs no root. A boot service is a LaunchDaemon in /Library/LaunchDaemons: it starts at boot, before anyone logs in, runs as the user who installed it, and needs root to install. A boot service suits a headless Mac; MLX reaches the GPU from it.

The service runs imagewright serve from the environment the installing imagewright lives in, and launchd restarts it if it exits.

ServiceError

Bases: RuntimeError

The service could not be installed, started or removed.

ServiceSpec(backend, boot, user, home, executable, host, port, idle_unload_s=0) dataclass

One launchd service running imagewright serve.

Parameters:

Name Type Description Default
backend str

flux or sdxl.

required
boot bool

True for a LaunchDaemon that starts at boot, False for a LaunchAgent that starts at login.

required
user str

The account the server runs as.

required
home Path

That account's home folder.

required
executable Path

The imagewright script to run.

required
host str

Address the server binds.

required
port int

Port the server binds.

required
idle_unload_s int

Seconds idle before FLUX unloads its model; 0 keeps it.

0

domain property

The launchd domain: system for a daemon, gui/<uid> for an agent.

health_url property

The URL that answers once the server is up, as seen from this Mac.

label property

The launchd label, local.imagewright for FLUX.

log_path property

The server's log, under the user's ~/Library/Logs.

plist_path property

Where the property list goes: the system daemons or the user's agents.

build_plist(spec)

The launchd property list for spec.

A daemon gets no HOME, and the Hugging Face model cache lives under it, so the list sets HOME and PATH itself.

Parameters:

Name Type Description Default
spec ServiceSpec

The service.

required
Source code in src/imagewright/service.py
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
def build_plist(spec: ServiceSpec) -> dict:
    """The launchd property list for ``spec``.

    A daemon gets no ``HOME``, and the Hugging Face model cache lives under it,
    so the list sets ``HOME`` and ``PATH`` itself.

    :param spec: The service.
    """
    prefix = ENV_PREFIX[spec.backend]
    env = {
        "HOME": str(spec.home),
        "PATH": f"{spec.executable.parent}:/opt/homebrew/bin:/usr/bin:/bin",
        f"{prefix}_HOST": spec.host,
        f"{prefix}_PORT": str(spec.port),
    }
    if spec.backend == "flux":
        env["IMAGE_IDLE_UNLOAD_S"] = str(spec.idle_unload_s)
    plist = {
        "Label": spec.label,
        "ProgramArguments": [str(spec.executable), "serve", "--backend", spec.backend],
        "WorkingDirectory": str(spec.home),
        "EnvironmentVariables": env,
        "RunAtLoad": True,
        "KeepAlive": True,
        "ThrottleInterval": 10,
        "StandardOutPath": str(spec.log_path),
        "StandardErrorPath": str(spec.log_path),
    }
    if spec.boot:
        plist["UserName"] = spec.user
        plist["GroupName"] = "staff"
    return plist

imagewright_executable()

The imagewright script beside the running Python, so the service uses this venv.

Source code in src/imagewright/service.py
105
106
107
def imagewright_executable() -> Path:
    """The ``imagewright`` script beside the running Python, so the service uses this venv."""
    return Path(sys.executable).with_name("imagewright")

install(spec, run=subprocess.run, timeout_s=60.0)

Write the property list, (re)load the service and wait for its /health.

An earlier copy of the same service is replaced.

Parameters:

Name Type Description Default
spec ServiceSpec

The service.

required
run Runner

subprocess.run or a stand-in, for the launchctl calls.

run
timeout_s float

How long to wait for /health.

60.0

Returns:

Type Description
dict

The /health JSON.

Raises:

Type Description
ServiceError

If privileges are wrong, launchctl refuses, or the server does not answer.

Source code in src/imagewright/service.py
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
def install(spec: ServiceSpec, run: Runner = subprocess.run, timeout_s: float = 60.0) -> dict:
    """Write the property list, (re)load the service and wait for its ``/health``.

    An earlier copy of the same service is replaced.

    :param spec: The service.
    :param run: ``subprocess.run`` or a stand-in, for the ``launchctl`` calls.
    :param timeout_s: How long to wait for ``/health``.
    :returns: The ``/health`` JSON.
    :raises ServiceError: If privileges are wrong, ``launchctl`` refuses, or the
        server does not answer.
    """
    _check_privileges(spec)
    if not spec.executable.exists():
        raise ServiceError(f"{spec.executable} does not exist")
    # Check the port before touching the installed service, so a refusal leaves
    # it running. The service's own port is busy with itself; that is a reinstall.
    if _installed_port(spec) != spec.port and _answers(spec.health_url):
        raise ServiceError(
            f"something else already serves {spec.health_url}; stop it first "
            "(gutenberg_kg's LaunchAgent: `make image-agent-uninstall`)"
        )
    _bootout(spec, run)
    spec.log_path.parent.mkdir(parents=True, exist_ok=True)
    spec.plist_path.parent.mkdir(parents=True, exist_ok=True)
    spec.plist_path.write_bytes(plistlib.dumps(build_plist(spec)))
    spec.plist_path.chmod(0o644)
    if spec.boot:
        os.chown(spec.plist_path, 0, 0)
    done = run(
        ["launchctl", "bootstrap", spec.domain, str(spec.plist_path)],
        capture_output=True,
        text=True,
    )
    if done.returncode != 0:
        raise ServiceError(f"launchctl bootstrap failed: {(done.stderr or '').strip()}")
    return wait_healthy(spec.health_url, timeout_s)

target_user(boot)

The account a new service runs as, and its home folder.

Under sudo that is the user who ran sudo, not root.

Parameters:

Name Type Description Default
boot bool

True when installing a boot service.

required
Source code in src/imagewright/service.py
 94
 95
 96
 97
 98
 99
100
101
102
def target_user(boot: bool) -> tuple[str, Path]:
    """The account a new service runs as, and its home folder.

    Under ``sudo`` that is the user who ran sudo, not root.

    :param boot: True when installing a boot service.
    """
    user = (os.environ.get("SUDO_USER") if boot else None) or getpass.getuser()
    return user, Path(pwd.getpwnam(user).pw_dir)

uninstall(spec, run=subprocess.run)

Stop the service and delete its property list.

Parameters:

Name Type Description Default
spec ServiceSpec

The service.

required
run Runner

subprocess.run or a stand-in, for the launchctl calls.

run

Returns:

Type Description
bool

True if a property list was removed.

Source code in src/imagewright/service.py
249
250
251
252
253
254
255
256
257
258
259
260
261
def uninstall(spec: ServiceSpec, run: Runner = subprocess.run) -> bool:
    """Stop the service and delete its property list.

    :param spec: The service.
    :param run: ``subprocess.run`` or a stand-in, for the ``launchctl`` calls.
    :returns: True if a property list was removed.
    """
    _check_privileges(spec)
    _bootout(spec, run)
    if spec.plist_path.exists():
        spec.plist_path.unlink()
        return True
    return False

wait_healthy(url, timeout_s=60.0)

Poll url until it answers 200 and return its JSON.

Parameters:

Name Type Description Default
url str

The server's /health URL.

required
timeout_s float

How long to wait.

60.0

Raises:

Type Description
ServiceError

If it never answers.

Source code in src/imagewright/service.py
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
def wait_healthy(url: str, timeout_s: float = 60.0) -> dict:
    """Poll ``url`` until it answers 200 and return its JSON.

    :param url: The server's ``/health`` URL.
    :param timeout_s: How long to wait.
    :raises ServiceError: If it never answers.
    """
    deadline = time.monotonic() + timeout_s
    while True:
        try:
            r = httpx.get(url, timeout=3)
            if r.status_code == 200:
                return r.json()
        except (httpx.HTTPError, json.JSONDecodeError):
            pass
        if time.monotonic() > deadline:
            raise ServiceError(
                f"the service is loaded but {url} did not answer in {timeout_s:.0f} s"
            )
        time.sleep(1)