1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 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 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 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 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463
|
from __future__ import annotations
import copy
import logging
import sys
import warnings
import weakref
from json import dumps
from typing import Any
import dask
import dask.config
from distributed.deploy.spec import ProcessInterface, SpecCluster
logger = logging.getLogger(__name__)
class Process(ProcessInterface):
"""A superclass for SSH Workers and Nannies
See Also
--------
Worker
Scheduler
"""
def __init__(self, **kwargs):
self.connection = None
self.proc = None
super().__init__(**kwargs)
async def start(self):
assert self.connection
weakref.finalize(
self, self.proc.kill
) # https://github.com/ronf/asyncssh/issues/112
await super().start()
async def close(self):
if self.proc:
self.proc.kill() # https://github.com/ronf/asyncssh/issues/112
if self.connection:
self.connection.close()
await super().close()
class Worker(Process):
"""A Remote Dask Worker controlled by SSH
Parameters
----------
scheduler: str
The address of the scheduler
address: str
The hostname where we should run this worker
worker_class: str
The python class to use to create the worker.
connect_options: dict
kwargs to be passed to asyncssh connections
remote_python: str
Path to Python on remote node to run this worker.
kwargs: dict
These will be passed through the dask worker CLI to the
dask.distributed.Worker class
"""
def __init__( # type: ignore[no-untyped-def]
self,
scheduler: str,
address: str,
connect_options: dict,
kwargs: dict,
worker_module="deprecated",
worker_class="distributed.Nanny",
remote_python=None,
loop=None,
name=None,
):
super().__init__()
if worker_module != "deprecated":
raise ValueError(
"worker_module has been deprecated in favor of worker_class. "
"Please specify a Python class rather than a CLI module."
)
self.address = address
self.scheduler = scheduler
self.worker_class = worker_class
self.connect_options = connect_options
self.kwargs = copy.copy(kwargs)
self.name = name
self.remote_python = remote_python
if kwargs.get("nprocs") is not None and kwargs.get("n_workers") is not None:
raise ValueError(
"Both nprocs and n_workers were specified. Use n_workers only."
)
elif kwargs.get("nprocs") is not None:
warnings.warn(
"The nprocs argument will be removed in a future release. It has been "
"renamed to n_workers.",
FutureWarning,
)
self.n_workers = self.kwargs.pop("nprocs", 1)
else:
self.n_workers = self.kwargs.pop("n_workers", 1)
@property
def nprocs(self):
warnings.warn(
"The nprocs attribute will be removed in a future release. It has been "
"renamed to n_workers.",
FutureWarning,
)
return self.n_workers
@nprocs.setter
def nprocs(self, value):
warnings.warn(
"The nprocs attribute will be removed in a future release. It has been "
"renamed to n_workers.",
FutureWarning,
)
self.n_workers = value
async def start(self):
try:
import asyncssh # import now to avoid adding to module startup time
except ImportError:
raise ImportError(
"Dask's SSHCluster requires the `asyncssh` package to be installed. "
"Please install it using pip or conda."
)
self.connection = await asyncssh.connect(self.address, **self.connect_options)
result = await self.connection.run("uname")
if result.exit_status == 0:
set_env = 'env DASK_INTERNAL_INHERIT_CONFIG="{}"'.format(
dask.config.serialize(dask.config.global_config)
)
else:
result = await self.connection.run("cmd /c ver")
if result.exit_status == 0:
set_env = "set DASK_INTERNAL_INHERIT_CONFIG={} &&".format(
dask.config.serialize(dask.config.global_config)
)
else:
raise Exception(
"Worker failed to set DASK_INTERNAL_INHERIT_CONFIG variable "
)
if not self.remote_python:
self.remote_python = sys.executable
cmd = " ".join(
[
set_env,
self.remote_python,
"-m",
"distributed.cli.dask_spec",
self.scheduler,
"--spec",
"'%s'"
% dumps(
{
i: {
"cls": self.worker_class,
"opts": {
**self.kwargs,
},
}
for i in range(self.n_workers)
}
),
]
)
self.proc = await self.connection.create_process(cmd)
# We watch stderr in order to get the address, then we return
started_workers = 0
while started_workers < self.n_workers:
line = await self.proc.stderr.readline()
if not line.strip():
raise Exception("Worker failed to start")
logger.info(line.strip())
if "worker at" in line:
started_workers += 1
logger.debug("%s", line)
await super().start()
class Scheduler(Process):
"""A Remote Dask Scheduler controlled by SSH
Parameters
----------
address: str
The hostname where we should run this worker
connect_options: dict
kwargs to be passed to asyncssh connections
remote_python: str
Path to Python on remote node to run this scheduler.
kwargs: dict
These will be passed through the dask scheduler CLI to the
dask.distributed.Scheduler class
"""
def __init__(
self,
address: str,
connect_options: dict,
kwargs: dict,
remote_python: str | None = None,
):
super().__init__()
self.address = address
self.kwargs = kwargs
self.connect_options = connect_options
self.remote_python = remote_python or sys.executable
async def start(self):
try:
import asyncssh # import now to avoid adding to module startup time
except ImportError:
raise ImportError(
"Dask's SSHCluster requires the `asyncssh` package to be installed. "
"Please install it using pip or conda."
)
logger.debug("Created Scheduler Connection")
self.connection = await asyncssh.connect(self.address, **self.connect_options)
result = await self.connection.run("uname")
if result.exit_status == 0:
set_env = 'env DASK_INTERNAL_INHERIT_CONFIG="{}"'.format(
dask.config.serialize(dask.config.global_config)
)
else:
result = await self.connection.run("cmd /c ver")
if result.exit_status == 0:
set_env = "set DASK_INTERNAL_INHERIT_CONFIG={} &&".format(
dask.config.serialize(dask.config.global_config)
)
else:
raise Exception(
"Scheduler failed to set DASK_INTERNAL_INHERIT_CONFIG variable "
)
cmd = " ".join(
[
set_env,
self.remote_python,
"-m",
"distributed.cli.dask_spec",
"--spec",
"'%s'" % dumps({"cls": "distributed.Scheduler", "opts": self.kwargs}),
]
)
self.proc = await self.connection.create_process(cmd)
# We watch stderr in order to get the address, then we return
while True:
line = await self.proc.stderr.readline()
if not line.strip():
raise Exception("Worker failed to start")
logger.info(line.strip())
if "Scheduler at" in line:
self.address = line.split("Scheduler at:")[1].strip()
break
logger.debug("%s", line)
await super().start()
old_cluster_kwargs = {
"scheduler_addr",
"scheduler_port",
"worker_addrs",
"nthreads",
"nprocs",
"n_workers",
"ssh_username",
"ssh_port",
"ssh_private_key",
"nohost",
"logdir",
"remote_python",
"memory_limit",
"worker_port",
"nanny_port",
"remote_dask_worker",
}
def SSHCluster(
hosts: list[str] | None = None,
connect_options: dict | list[dict] | None = None,
worker_options: dict | None = None,
scheduler_options: dict | None = None,
worker_module: str = "deprecated",
worker_class: str = "distributed.Nanny",
remote_python: str | list[str] | None = None,
**kwargs: Any,
) -> SpecCluster:
"""Deploy a Dask cluster using SSH
The SSHCluster function deploys a Dask Scheduler and Workers for you on a
set of machine addresses that you provide. The first address will be used
for the scheduler while the rest will be used for the workers (feel free to
repeat the first hostname if you want to have the scheduler and worker
co-habitate one machine.)
You may configure the scheduler and workers by passing
``scheduler_options`` and ``worker_options`` dictionary keywords. See the
``dask.distributed.Scheduler`` and ``dask.distributed.Worker`` classes for
details on the available options, but the defaults should work in most
situations.
You may configure your use of SSH itself using the ``connect_options``
keyword, which passes values to the ``asyncssh.connect`` function. For
more information on these see the documentation for the ``asyncssh``
library https://asyncssh.readthedocs.io .
Parameters
----------
hosts
List of hostnames or addresses on which to launch our cluster.
The first will be used for the scheduler and the rest for workers.
connect_options
Keywords to pass through to :func:`asyncssh.connect`.
This could include things such as ``port``, ``username``, ``password``
or ``known_hosts``. See docs for :func:`asyncssh.connect` and
:class:`asyncssh.SSHClientConnectionOptions` for full information.
If a list it must have the same length as ``hosts``.
worker_options
Keywords to pass on to workers.
scheduler_options
Keywords to pass on to scheduler.
worker_class
The python class to use to create the worker(s).
remote_python
Path to Python on remote nodes.
Examples
--------
Create a cluster with one worker:
>>> from dask.distributed import Client, SSHCluster
>>> cluster = SSHCluster(["localhost", "localhost"])
>>> client = Client(cluster)
Create a cluster with three workers, each with two threads
and host the dashdoard on port 8797:
>>> from dask.distributed import Client, SSHCluster
>>> cluster = SSHCluster(
... ["localhost", "localhost", "localhost", "localhost"],
... connect_options={"known_hosts": None},
... worker_options={"nthreads": 2},
... scheduler_options={"port": 0, "dashboard_address": ":8797"}
... )
>>> client = Client(cluster)
Create a cluster with two workers on each host:
>>> from dask.distributed import Client, SSHCluster
>>> cluster = SSHCluster(
... ["localhost", "localhost", "localhost", "localhost"],
... connect_options={"known_hosts": None},
... worker_options={"nthreads": 2, "n_workers": 2},
... scheduler_options={"port": 0, "dashboard_address": ":8797"}
... )
>>> client = Client(cluster)
An example using a different worker class, in particular the
``CUDAWorker`` from the ``dask-cuda`` project:
>>> from dask.distributed import Client, SSHCluster
>>> cluster = SSHCluster(
... ["localhost", "hostwithgpus", "anothergpuhost"],
... connect_options={"known_hosts": None},
... scheduler_options={"port": 0, "dashboard_address": ":8797"},
... worker_class="dask_cuda.CUDAWorker")
>>> client = Client(cluster)
See Also
--------
dask.distributed.Scheduler
dask.distributed.Worker
asyncssh.connect
"""
connect_options = connect_options or {}
worker_options = worker_options or {}
scheduler_options = scheduler_options or {}
if worker_module != "deprecated":
raise ValueError(
"worker_module has been deprecated in favor of worker_class. "
"Please specify a Python class rather than a CLI module."
)
if set(kwargs) & old_cluster_kwargs:
from distributed.deploy.old_ssh import SSHCluster as OldSSHCluster
warnings.warn(
"Note that the SSHCluster API has been replaced. "
"We're routing you to the older implementation. "
"This will be removed in the future"
)
kwargs.setdefault("worker_addrs", hosts)
return OldSSHCluster(**kwargs) # type: ignore
if not hosts:
raise ValueError(
f"`hosts` must be a non empty list, value {repr(hosts)!r} found."
)
if isinstance(connect_options, list) and len(connect_options) != len(hosts):
raise RuntimeError(
"When specifying a list of connect_options you must provide a "
"dictionary for each address."
)
if isinstance(remote_python, list) and len(remote_python) != len(hosts):
raise RuntimeError(
"When specifying a list of remote_python you must provide a "
"path for each address."
)
scheduler = {
"cls": Scheduler,
"options": {
"address": hosts[0],
"connect_options": connect_options
if isinstance(connect_options, dict)
else connect_options[0],
"kwargs": scheduler_options,
"remote_python": remote_python[0]
if isinstance(remote_python, list)
else remote_python,
},
}
workers = {
i: {
"cls": Worker,
"options": {
"address": host,
"connect_options": connect_options
if isinstance(connect_options, dict)
else connect_options[i + 1],
"kwargs": worker_options,
"worker_class": worker_class,
"remote_python": remote_python[i + 1]
if isinstance(remote_python, list)
else remote_python,
},
}
for i, host in enumerate(hosts[1:])
}
return SpecCluster(workers, scheduler, name="SSHCluster", **kwargs)
|