agent.py 36 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940
  1. """Implementation of launch agent."""
  2. from __future__ import annotations
  3. import asyncio
  4. import copy
  5. import logging
  6. import os
  7. import pprint
  8. import threading
  9. import time
  10. import traceback
  11. from dataclasses import dataclass
  12. from multiprocessing import Event
  13. from typing import Any
  14. import wandb
  15. from wandb.analytics import get_sentry
  16. from wandb.apis.internal import Api
  17. from wandb.errors import CommError
  18. from wandb.sdk.launch._launch_add import launch_add
  19. from wandb.sdk.launch.runner.local_container import LocalSubmittedRun
  20. from wandb.sdk.launch.runner.local_process import LocalProcessRunner
  21. from wandb.sdk.launch.sweeps.scheduler import Scheduler
  22. from wandb.sdk.launch.utils import LAUNCH_CONFIG_FILE, resolve_build_and_registry_config
  23. from wandb.sdk.lib import runid
  24. from .. import loader
  25. from .._project_spec import LaunchProject
  26. from ..errors import LaunchDockerError, LaunchError
  27. from ..utils import (
  28. LAUNCH_DEFAULT_PROJECT,
  29. LOG_PREFIX,
  30. PROJECT_SYNCHRONOUS,
  31. event_loop_thread_exec,
  32. )
  33. from .job_status_tracker import JobAndRunStatusTracker
  34. from .run_queue_item_file_saver import RunQueueItemFileSaver
  35. AGENT_POLLING_INTERVAL = 10
  36. RECEIVED_JOB_POLLING_INTERVAL = 0.0 # more frequent when we know we have jobs
  37. AGENT_POLLING = "POLLING"
  38. AGENT_RUNNING = "RUNNING"
  39. AGENT_KILLED = "KILLED"
  40. HIDDEN_AGENT_RUN_TYPE = "sweep-controller"
  41. MAX_RESUME_COUNT = 5
  42. RUN_INFO_GRACE_PERIOD = 60
  43. DEFAULT_STOPPED_RUN_TIMEOUT = 60
  44. DEFAULT_PRINT_INTERVAL = 5 * 60
  45. VERBOSE_PRINT_INTERVAL = 20
  46. _DEFAULT_BASE_IMAGE = "python:3.12-slim"
  47. _env_timeout = os.environ.get("WANDB_LAUNCH_START_TIMEOUT")
  48. if _env_timeout:
  49. try:
  50. RUN_START_TIMEOUT = float(_env_timeout)
  51. except ValueError:
  52. raise LaunchError(
  53. f"Invalid value for WANDB_LAUNCH_START_TIMEOUT: {_env_timeout}"
  54. )
  55. else:
  56. RUN_START_TIMEOUT = 60 * 30 # default 30 minutes
  57. _logger = logging.getLogger(__name__)
  58. @dataclass
  59. class JobSpecAndQueue:
  60. job: dict[str, Any]
  61. queue: str
  62. def _convert_access(access: str) -> str:
  63. """Convert access string to a value accepted by wandb."""
  64. access = access.upper()
  65. assert access == "PROJECT" or access == "USER", (
  66. "Queue access must be either project or user"
  67. )
  68. return access
  69. def _max_from_config(config: dict[str, Any], key: str, default: int = 1) -> int | float:
  70. """Get an integer from the config, or float.inf if -1.
  71. Utility for parsing integers from the agent config with a default, infinity
  72. handling, and integer parsing. Raises more informative error if parse error.
  73. """
  74. try:
  75. val = config.get(key)
  76. if val is None:
  77. val = default
  78. max_from_config = int(val)
  79. except ValueError as e:
  80. raise LaunchError(
  81. f"Error when parsing LaunchAgent config key: ['{key}': "
  82. f"{config.get(key)}]. Error: {str(e)}"
  83. )
  84. if max_from_config == -1:
  85. return float("inf")
  86. if max_from_config < 0:
  87. raise LaunchError(
  88. f"Error when parsing LaunchAgent config key: ['{key}': "
  89. f"{config.get(key)}]. Error: negative value."
  90. )
  91. return max_from_config
  92. class InternalAgentLogger:
  93. def __init__(self, verbosity=0):
  94. self._print_to_terminal = verbosity >= 2
  95. def error(self, message: str):
  96. if self._print_to_terminal:
  97. wandb.termerror(f"{LOG_PREFIX}{message}")
  98. _logger.error(f"{LOG_PREFIX}{message}")
  99. def warn(self, message: str):
  100. if self._print_to_terminal:
  101. wandb.termwarn(f"{LOG_PREFIX}{message}")
  102. _logger.warning(f"{LOG_PREFIX}{message}")
  103. def info(self, message: str):
  104. if self._print_to_terminal:
  105. wandb.termlog(f"{LOG_PREFIX}{message}")
  106. _logger.info(f"{LOG_PREFIX}{message}")
  107. def debug(self, message: str):
  108. if self._print_to_terminal:
  109. wandb.termlog(f"{LOG_PREFIX}{message}")
  110. _logger.debug(f"{LOG_PREFIX}{message}")
  111. def construct_agent_configs(
  112. launch_config: dict | None = None,
  113. build_config: dict | None = None,
  114. ) -> tuple[dict[str, Any] | None, dict[str, Any], dict[str, Any]]:
  115. import yaml
  116. registry_config = None
  117. environment_config = None
  118. if launch_config is not None:
  119. build_config = launch_config.get("builder")
  120. registry_config = launch_config.get("registry")
  121. default_launch_config = None
  122. if os.path.exists(os.path.expanduser(LAUNCH_CONFIG_FILE)):
  123. with open(os.path.expanduser(LAUNCH_CONFIG_FILE)) as f:
  124. default_launch_config = (
  125. yaml.safe_load(f) or {}
  126. ) # In case the config is empty, we want it to be {} instead of None.
  127. environment_config = default_launch_config.get("environment")
  128. build_config, registry_config = resolve_build_and_registry_config(
  129. default_launch_config, build_config, registry_config
  130. )
  131. return environment_config, build_config, registry_config
  132. class LaunchAgent:
  133. """Launch agent class which polls run given run queues and launches runs for wandb launch."""
  134. _instance = None
  135. def __new__(cls, *args: Any, **kwargs: Any) -> LaunchAgent:
  136. """Create a new instance of the LaunchAgent.
  137. This method ensures that only one instance of the LaunchAgent is created.
  138. This is done so that information about the agent can be accessed from
  139. elsewhere in the library.
  140. """
  141. if cls._instance is None:
  142. cls._instance = super().__new__(cls)
  143. return cls._instance
  144. @classmethod
  145. def name(cls) -> str:
  146. """Return the name of the agent."""
  147. if cls._instance is None:
  148. raise LaunchError("LaunchAgent has not been initialized")
  149. name = cls._instance._name
  150. if isinstance(name, str):
  151. return name
  152. raise LaunchError(f"Found invalid name for agent {name}")
  153. @classmethod
  154. def initialized(cls) -> bool:
  155. """Return whether the agent is initialized."""
  156. return cls._instance is not None
  157. def __init__(self, api: Api, config: dict[str, Any]):
  158. """Initialize a launch agent.
  159. Arguments:
  160. api: Api object to use for making requests to the backend.
  161. config: Config dictionary for the agent.
  162. """
  163. self._entity = config["entity"]
  164. self._project = LAUNCH_DEFAULT_PROJECT
  165. self._api = api
  166. self._base_url = self._api.settings().get("base_url")
  167. self._ticks = 0
  168. self._jobs: dict[int, JobAndRunStatusTracker] = {}
  169. self._jobs_lock = threading.Lock()
  170. self._jobs_event = Event()
  171. self._jobs_event.set()
  172. self._cwd = os.getcwd()
  173. self._namespace = runid.generate_id()
  174. self._access = _convert_access("project")
  175. self._max_jobs = _max_from_config(config, "max_jobs")
  176. self._max_schedulers = _max_from_config(config, "max_schedulers")
  177. self._secure_mode = config.get("secure_mode", False)
  178. self._verbosity = config.get("verbosity", 0)
  179. self._internal_logger = InternalAgentLogger(verbosity=self._verbosity)
  180. self._last_status_print_time = 0.0
  181. self.default_config: dict[str, Any] = config
  182. self._stopped_run_timeout = config.get(
  183. "stopped_run_timeout", DEFAULT_STOPPED_RUN_TIMEOUT
  184. )
  185. self._known_warnings: list[str] = []
  186. # Get agent version from env var if present, otherwise wandb version
  187. self.version: str = "wandb@" + wandb.__version__
  188. env_agent_version = os.environ.get("WANDB_AGENT_VERSION")
  189. if env_agent_version and env_agent_version != "wandb-launch-agent":
  190. self.version = env_agent_version
  191. self._queues: list[str] = config.get("queues", ["default"])
  192. # remove project field from agent config before sending to back end
  193. # because otherwise it shows up in the config in the UI and confuses users
  194. sent_config = config.copy()
  195. if "project" in sent_config:
  196. del sent_config["project"]
  197. create_response = self._api.create_launch_agent(
  198. self._entity,
  199. self._project,
  200. self._queues,
  201. sent_config,
  202. self.version,
  203. )
  204. self._id = create_response["launchAgentId"]
  205. if self._api.entity_is_team(self._entity):
  206. wandb.termwarn(
  207. f"{LOG_PREFIX}Agent is running on team entity ({self._entity}). Members of this team will be able to run code on this device."
  208. )
  209. agent_response = self._api.get_launch_agent(self._id)
  210. self._name = agent_response["name"]
  211. self._init_agent_run()
  212. def _is_scheduler_job(self, run_spec: dict[str, Any]) -> bool:
  213. """Determine whether a job/runSpec is a sweep scheduler."""
  214. if not run_spec:
  215. self._internal_logger.debug(
  216. "Received runSpec in _is_scheduler_job that was empty"
  217. )
  218. if run_spec.get("uri") != Scheduler.PLACEHOLDER_URI:
  219. return False
  220. if run_spec.get("resource") == "local-process":
  221. # Any job pushed to a run queue that has a scheduler uri is
  222. # allowed to use local-process
  223. if run_spec.get("job"):
  224. return True
  225. # If a scheduler is local-process and run through CLI, also
  226. # confirm command is in format: [wandb scheduler <sweep>]
  227. cmd = run_spec.get("overrides", {}).get("entry_point", [])
  228. if len(cmd) < 3:
  229. return False
  230. if cmd[:2] != ["wandb", "scheduler"]:
  231. return False
  232. return True
  233. async def fail_run_queue_item(
  234. self,
  235. run_queue_item_id: str,
  236. message: str,
  237. phase: str,
  238. files: list[str] | None = None,
  239. ) -> None:
  240. fail_rqi = event_loop_thread_exec(self._api.fail_run_queue_item)
  241. await fail_rqi(run_queue_item_id, message, phase, files)
  242. def _init_agent_run(self) -> None:
  243. settings = wandb.Settings(
  244. silent=True,
  245. disable_git=True,
  246. disable_job_creation=True,
  247. )
  248. self._wandb_run = wandb.init(
  249. project=self._project,
  250. entity=self._entity,
  251. settings=settings,
  252. id=self._name,
  253. job_type=HIDDEN_AGENT_RUN_TYPE,
  254. )
  255. @property
  256. def thread_ids(self) -> list[int]:
  257. """Returns a list of keys running thread ids for the agent."""
  258. with self._jobs_lock:
  259. return list(self._jobs.keys())
  260. @property
  261. def num_running_schedulers(self) -> int:
  262. """Return just the number of schedulers."""
  263. with self._jobs_lock:
  264. return len([x for x in self._jobs if self._jobs[x].is_scheduler])
  265. @property
  266. def num_running_jobs(self) -> int:
  267. """Return the number of jobs not including schedulers."""
  268. with self._jobs_lock:
  269. return len([x for x in self._jobs if not self._jobs[x].is_scheduler])
  270. async def pop_from_queue(self, queue: str) -> Any:
  271. """Pops an item off the runqueue to run as a job.
  272. Arguments:
  273. queue: Queue to pop from.
  274. Returns:
  275. Item popped off the queue.
  276. Raises:
  277. Exception: if there is an error popping from the queue.
  278. """
  279. try:
  280. pop = event_loop_thread_exec(self._api.pop_from_run_queue)
  281. ups = await pop(
  282. queue,
  283. entity=self._entity,
  284. project=self._project,
  285. agent_id=self._id,
  286. )
  287. return ups
  288. except Exception as e:
  289. print("Exception:", e)
  290. return None
  291. def print_status(self) -> None:
  292. """Prints the current status of the agent."""
  293. self._last_status_print_time = time.time()
  294. output_str = "agent "
  295. if self._name:
  296. output_str += f"{self._name} "
  297. if self.num_running_jobs < self._max_jobs:
  298. output_str += f"polling on queues {','.join(self._queues)}, "
  299. output_str += (
  300. f"running {self.num_running_jobs} out of a maximum of {self._max_jobs} jobs"
  301. )
  302. wandb.termlog(f"{LOG_PREFIX}{output_str}")
  303. if self.num_running_jobs > 0:
  304. output_str += f": {','.join(str(job_id) for job_id in self.thread_ids)}"
  305. _logger.info(output_str)
  306. async def update_status(self, status: str) -> None:
  307. """Update the status of the agent.
  308. Arguments:
  309. status: Status to update the agent to.
  310. """
  311. _update_status = event_loop_thread_exec(self._api.update_launch_agent_status)
  312. update_ret = await _update_status(self._id, status)
  313. if not update_ret["success"]:
  314. wandb.termerror(f"{LOG_PREFIX}Failed to update agent status to {status}")
  315. def _check_run_exists_and_inited(
  316. self, entity: str, project: str, run_id: str, rqi_id: str
  317. ) -> bool:
  318. """Checks the stateof the run to ensure it has been inited. Note this will not behave well with resuming."""
  319. # Checks the _wandb key in the run config for the run queue item id. If it exists, the
  320. # submitted run definitely called init. Falls back to checking state of run.
  321. # TODO: handle resuming runs
  322. # Sweep runs exist but are in pending state, normal launch runs won't exist
  323. # so will raise a CommError.
  324. try:
  325. run_state = self._api.get_run_state(entity, project, run_id)
  326. if run_state.lower() != "pending":
  327. return True
  328. except CommError:
  329. self._internal_logger.info(
  330. f"Run {entity}/{project}/{run_id} with rqi id: {rqi_id} did not have associated run",
  331. )
  332. return False
  333. async def finish_thread_id(
  334. self,
  335. thread_id: int,
  336. exception: Exception | LaunchDockerError | None = None,
  337. ) -> None:
  338. """Removes the job from our list for now."""
  339. with self._jobs_lock:
  340. job_and_run_status = self._jobs[thread_id]
  341. if (
  342. job_and_run_status.entity is not None
  343. and job_and_run_status.entity != self._entity
  344. ):
  345. self._internal_logger.info(
  346. "Skipping check for completed run status because run is on a different entity than agent",
  347. )
  348. elif exception is not None:
  349. tb_str = traceback.format_exception(
  350. type(exception), value=exception, tb=exception.__traceback__
  351. )
  352. fnames = job_and_run_status.saver.save_contents(
  353. "".join(tb_str), "error.log", "error"
  354. )
  355. await self.fail_run_queue_item(
  356. job_and_run_status.run_queue_item_id,
  357. str(exception),
  358. job_and_run_status.err_stage,
  359. fnames,
  360. )
  361. elif job_and_run_status.project is None or job_and_run_status.run_id is None:
  362. self._internal_logger.info(
  363. f"called finish_thread_id on thread whose tracker has no project or run id. RunQueueItemID: {job_and_run_status.run_queue_item_id}",
  364. )
  365. wandb.termerror(
  366. "Missing project or run id on thread called finish thread id"
  367. )
  368. await self.fail_run_queue_item(
  369. job_and_run_status.run_queue_item_id,
  370. "submitted job was finished without assigned project or run id",
  371. "agent",
  372. )
  373. elif job_and_run_status.run is not None:
  374. called_init = False
  375. # We do some weird stuff here getting run info to check for a
  376. # created in run in W&B.
  377. #
  378. # We retry for 60 seconds with an exponential backoff in case
  379. # upsert run is taking a while.
  380. logs = None
  381. interval = 1
  382. while True:
  383. called_init = self._check_run_exists_and_inited(
  384. self._entity,
  385. job_and_run_status.project,
  386. job_and_run_status.run_id,
  387. job_and_run_status.run_queue_item_id,
  388. )
  389. if called_init or interval > RUN_INFO_GRACE_PERIOD:
  390. break
  391. if not called_init:
  392. # Fetch the logs now if we don't get run info on the
  393. # first try, in case the logs are cleaned from the runner
  394. # environment (e.g. k8s) during the run info grace period.
  395. if interval == 1:
  396. logs = await job_and_run_status.run.get_logs()
  397. await asyncio.sleep(interval)
  398. interval *= 2
  399. if not called_init:
  400. fnames = None
  401. if job_and_run_status.completed_status == "finished":
  402. _msg = "The submitted job exited successfully but failed to call wandb.init"
  403. else:
  404. _msg = "The submitted run was not successfully started"
  405. if logs:
  406. fnames = job_and_run_status.saver.save_contents(
  407. logs, "error.log", "error"
  408. )
  409. await self.fail_run_queue_item(
  410. job_and_run_status.run_queue_item_id, _msg, "run", fnames
  411. )
  412. else:
  413. self._internal_logger.info(
  414. f"Finish thread id {thread_id} had no exception and no run"
  415. )
  416. get_sentry().exception(
  417. "launch agent called finish thread id on thread without run or exception"
  418. )
  419. # TODO: keep logs or something for the finished jobs
  420. with self._jobs_lock:
  421. del self._jobs[thread_id]
  422. # update status back to polling if no jobs are running
  423. if len(self.thread_ids) == 0:
  424. await self.update_status(AGENT_POLLING)
  425. async def run_job(
  426. self, job: dict[str, Any], queue: str, file_saver: RunQueueItemFileSaver
  427. ) -> None:
  428. """Set up project and run the job.
  429. Arguments:
  430. job: Job to run.
  431. """
  432. job_copy = copy.deepcopy(job)
  433. if "runSpec" in job_copy and "_wandb_api_key" in job_copy["runSpec"]:
  434. job_copy["runSpec"]["_wandb_api_key"] = "<redacted>"
  435. _msg = f"{LOG_PREFIX}Launch agent received job:\n{pprint.pformat(job_copy)}\n"
  436. wandb.termlog(_msg)
  437. _logger.info(_msg)
  438. # update agent status
  439. await self.update_status(AGENT_RUNNING)
  440. # parse job
  441. self._internal_logger.info("Parsing launch spec")
  442. launch_spec = job["runSpec"]
  443. # Abort if this job attempts to override secure mode
  444. self._assert_secure(launch_spec)
  445. job_tracker = JobAndRunStatusTracker(job["runQueueItemId"], queue, file_saver)
  446. asyncio.create_task(
  447. self.task_run_job(
  448. launch_spec,
  449. job,
  450. self.default_config,
  451. self._api,
  452. job_tracker,
  453. )
  454. )
  455. def _assert_secure(self, launch_spec: dict[str, Any]) -> None:
  456. """If secure mode is set, make sure no vulnerable keys are overridden."""
  457. if not self._secure_mode:
  458. return
  459. k8s_config = launch_spec.get("resource_args", {}).get("kubernetes", {})
  460. pod_secure_keys = ["hostPID", "hostIPC", "hostNetwork", "initContainers"]
  461. pod_spec = k8s_config.get("spec", {}).get("template", {}).get("spec", {})
  462. for key in pod_secure_keys:
  463. if key in pod_spec:
  464. raise ValueError(
  465. f'This agent is configured to lock "{key}" in pod spec '
  466. "but the job specification attempts to override it."
  467. )
  468. container_specs = pod_spec.get("containers", [])
  469. for container_spec in container_specs:
  470. if "command" in container_spec:
  471. raise ValueError(
  472. 'This agent is configured to lock "command" in container spec '
  473. "but the job specification attempts to override it."
  474. )
  475. if launch_spec.get("overrides", {}).get("entry_point"):
  476. raise ValueError(
  477. 'This agent is configured to lock the "entrypoint" override '
  478. "but the job specification attempts to override it."
  479. )
  480. async def loop(self) -> None:
  481. """Loop infinitely to poll for jobs and run them.
  482. Raises:
  483. KeyboardInterrupt: if the agent is requested to stop.
  484. """
  485. self.print_status()
  486. if self._verbosity == 0:
  487. print_interval = DEFAULT_PRINT_INTERVAL
  488. else:
  489. print_interval = VERBOSE_PRINT_INTERVAL
  490. try:
  491. while True:
  492. job = None
  493. self._ticks += 1
  494. agent_response = self._api.get_launch_agent(self._id)
  495. if agent_response["stopPolling"]:
  496. # shutdown process and all jobs if requested from ui
  497. raise KeyboardInterrupt # noqa: TRY301
  498. if self.num_running_jobs < self._max_jobs:
  499. # only check for new jobs if we're not at max
  500. job_and_queue = await self.get_job_and_queue()
  501. # these will either both be None, or neither will be None
  502. if job_and_queue is not None:
  503. job = job_and_queue.job
  504. queue = job_and_queue.queue
  505. try:
  506. file_saver = RunQueueItemFileSaver(
  507. self._wandb_run, job["runQueueItemId"]
  508. )
  509. if (
  510. self._is_scheduler_job(job.get("runSpec", {}))
  511. and self.num_running_schedulers >= self._max_schedulers
  512. ):
  513. # If job is a scheduler, and we are already at the cap, ignore,
  514. # don't ack, and it will be pushed back onto the queue in 1 min
  515. wandb.termwarn(
  516. f"{LOG_PREFIX}Agent already running the maximum number "
  517. f"of sweep schedulers: {self._max_schedulers}. To set "
  518. "this value use `max_schedulers` key in the agent config"
  519. )
  520. continue
  521. await self.run_job(job, queue, file_saver)
  522. except Exception as e:
  523. wandb.termerror(
  524. f"{LOG_PREFIX}Error running job: {traceback.format_exc()}"
  525. )
  526. get_sentry().exception(e)
  527. # always the first phase, because we only enter phase 2 within the thread
  528. files = file_saver.save_contents(
  529. contents=traceback.format_exc(),
  530. fname="error.log",
  531. file_sub_type="error",
  532. )
  533. await self.fail_run_queue_item(
  534. run_queue_item_id=job["runQueueItemId"],
  535. message=str(e),
  536. phase="agent",
  537. files=files,
  538. )
  539. if self._ticks % 2 == 0:
  540. if len(self.thread_ids) == 0:
  541. await self.update_status(AGENT_POLLING)
  542. else:
  543. await self.update_status(AGENT_RUNNING)
  544. if time.time() - self._last_status_print_time > print_interval:
  545. self.print_status()
  546. if self.num_running_jobs == self._max_jobs or job is None:
  547. # all threads busy or did not receive job
  548. await asyncio.sleep(AGENT_POLLING_INTERVAL)
  549. else:
  550. await asyncio.sleep(RECEIVED_JOB_POLLING_INTERVAL)
  551. except KeyboardInterrupt:
  552. await self.update_status(AGENT_KILLED)
  553. wandb.termlog(f"{LOG_PREFIX}Shutting down, active jobs:")
  554. self.print_status()
  555. finally:
  556. self._jobs_event.clear()
  557. # Threaded functions
  558. async def task_run_job(
  559. self,
  560. launch_spec: dict[str, Any],
  561. job: dict[str, Any],
  562. default_config: dict[str, Any],
  563. api: Api,
  564. job_tracker: JobAndRunStatusTracker,
  565. ) -> None:
  566. rqi_id = job["runQueueItemId"]
  567. assert rqi_id
  568. exception: LaunchDockerError | Exception | None = None
  569. try:
  570. with self._jobs_lock:
  571. self._jobs[rqi_id] = job_tracker
  572. await self._task_run_job(
  573. launch_spec, job, default_config, api, rqi_id, job_tracker
  574. )
  575. except LaunchDockerError as e:
  576. wandb.termerror(
  577. f"{LOG_PREFIX}agent {self._name} encountered an issue while starting Docker, see above output for details."
  578. )
  579. exception = e
  580. get_sentry().exception(e)
  581. except LaunchError as e:
  582. wandb.termerror(f"{LOG_PREFIX}Error running job: {e}")
  583. exception = e
  584. get_sentry().exception(e)
  585. except Exception as e:
  586. wandb.termerror(f"{LOG_PREFIX}Error running job: {traceback.format_exc()}")
  587. exception = e
  588. get_sentry().exception(e)
  589. finally:
  590. await self.finish_thread_id(rqi_id, exception)
  591. async def _task_run_job(
  592. self,
  593. launch_spec: dict[str, Any],
  594. job: dict[str, Any],
  595. default_config: dict[str, Any],
  596. api: Api,
  597. thread_id: int,
  598. job_tracker: JobAndRunStatusTracker,
  599. ) -> None:
  600. project = LaunchProject.from_spec(launch_spec, api)
  601. self._set_queue_and_rqi_in_project(project, job, job_tracker.queue)
  602. ack = event_loop_thread_exec(api.ack_run_queue_item)
  603. await ack(job["runQueueItemId"], project.run_id)
  604. # don't launch sweep runs if the sweep isn't healthy
  605. await self.check_sweep_state(launch_spec, api)
  606. job_tracker.update_run_info(project)
  607. self._internal_logger.info("Fetching and validating project...")
  608. project.fetch_and_validate_project()
  609. self._internal_logger.info("Fetching resource...")
  610. resource = launch_spec.get("resource") or "local-container"
  611. backend_config: dict[str, Any] = {
  612. PROJECT_SYNCHRONOUS: False, # agent always runs async
  613. }
  614. self._internal_logger.info("Loading backend")
  615. override_build_config = launch_spec.get("builder")
  616. _, build_config, registry_config = construct_agent_configs(
  617. default_config, override_build_config
  618. )
  619. image_uri = project.docker_image or project.job_base_image
  620. entrypoint = project.get_job_entry_point()
  621. environment = loader.environment_from_config(
  622. default_config.get("environment", {})
  623. )
  624. registry = loader.registry_from_config(registry_config, environment)
  625. builder = loader.builder_from_config(build_config, environment, registry)
  626. backend = loader.runner_from_config(
  627. resource, api, backend_config, environment, registry
  628. )
  629. # TODO (nicholaspun-wandb): Refactor Builder/Runner to remove isinstance checks.
  630. if not (
  631. project.docker_image
  632. or project.job_base_image
  633. or isinstance(backend, LocalProcessRunner)
  634. ):
  635. # If no builder is configured and the job has source code,
  636. # use a default base image with the emptyDir init container
  637. # approach instead of failing.
  638. from wandb.sdk.launch.builder.noop import NoOpBuilder
  639. if isinstance(builder, NoOpBuilder) and project.job_source_type in (
  640. "artifact",
  641. "repo",
  642. ):
  643. base_image = (
  644. project._resource_args_build.get("base_image")
  645. or _DEFAULT_BASE_IMAGE
  646. )
  647. wandb.termwarn(
  648. f"{LOG_PREFIX}No builder configured. Using base image: {base_image}"
  649. )
  650. project.set_job_base_image(base_image)
  651. project._auto_default_base_image = True
  652. image_uri = base_image
  653. else:
  654. assert entrypoint is not None
  655. image_uri = await builder.build_image(project, entrypoint, job_tracker)
  656. self._internal_logger.info("Backend loaded...")
  657. if isinstance(backend, LocalProcessRunner):
  658. run = await backend.run(project, image_uri)
  659. else:
  660. assert image_uri
  661. run = await backend.run(project, image_uri)
  662. if self._is_scheduler_job(launch_spec):
  663. with self._jobs_lock:
  664. self._jobs[thread_id].is_scheduler = True
  665. wandb.termlog(
  666. f"{LOG_PREFIX}Preparing to run sweep scheduler "
  667. f"({self.num_running_schedulers}/{self._max_schedulers})"
  668. )
  669. if not run:
  670. with self._jobs_lock:
  671. job_tracker.failed_to_start = True
  672. return
  673. with self._jobs_lock:
  674. job_tracker.run = run
  675. start_time = time.time()
  676. stopped_time: float | None = None
  677. while self._jobs_event.is_set():
  678. # If run has failed to start before timeout, kill it
  679. state = (await run.get_status()).state
  680. if (
  681. state == "starting"
  682. and RUN_START_TIMEOUT > 0
  683. and time.time() - start_time > RUN_START_TIMEOUT
  684. ):
  685. await run.cancel()
  686. raise LaunchError(
  687. f"Run failed to start within {RUN_START_TIMEOUT} seconds. "
  688. "If you want to increase this timeout, set WANDB_LAUNCH_START_TIMEOUT "
  689. "to a larger value."
  690. )
  691. if await self._check_run_finished(job_tracker, launch_spec):
  692. return
  693. if await job_tracker.check_wandb_run_stopped(self._api):
  694. if stopped_time is None:
  695. stopped_time = time.time()
  696. else:
  697. if time.time() - stopped_time > self._stopped_run_timeout:
  698. await run.cancel()
  699. await asyncio.sleep(AGENT_POLLING_INTERVAL)
  700. # temp: for local, kill all jobs. we don't yet have good handling for different
  701. # types of runners in general
  702. if isinstance(run, LocalSubmittedRun) and run._command_proc is not None:
  703. run._command_proc.kill()
  704. async def check_sweep_state(self, launch_spec: dict[str, Any], api: Api) -> None:
  705. """Check the state of a sweep before launching a run for the sweep."""
  706. if launch_spec.get("sweep_id"):
  707. try:
  708. get_sweep_state = event_loop_thread_exec(api.get_sweep_state)
  709. state = await get_sweep_state(
  710. sweep=launch_spec["sweep_id"],
  711. entity=launch_spec["entity"],
  712. project=launch_spec["project"],
  713. )
  714. except Exception as e:
  715. self._internal_logger.debug(f"Fetch sweep state error: {e}")
  716. state = None
  717. if state != "RUNNING" and state != "PAUSED":
  718. raise LaunchError(
  719. f"Launch agent picked up sweep job, but sweep ({launch_spec['sweep_id']}) was in a terminal state ({state})"
  720. )
  721. async def _check_run_finished(
  722. self, job_tracker: JobAndRunStatusTracker, launch_spec: dict[str, Any]
  723. ) -> bool:
  724. if job_tracker.completed_status:
  725. return True
  726. # the run can be done before the run has started
  727. # but can also be none if the run failed to start
  728. # so if there is no run, either the run hasn't started yet
  729. # or it has failed
  730. if job_tracker.run is None:
  731. return bool(job_tracker.failed_to_start)
  732. known_error = False
  733. try:
  734. run = job_tracker.run
  735. status = await run.get_status()
  736. state = status.state
  737. for warning in status.messages:
  738. if warning not in self._known_warnings:
  739. self._known_warnings.append(warning)
  740. success = self._api.update_run_queue_item_warning(
  741. job_tracker.run_queue_item_id,
  742. warning,
  743. "Kubernetes",
  744. [],
  745. )
  746. if not success:
  747. _logger.warning(
  748. f"Error adding warning {warning} to run queue item {job_tracker.run_queue_item_id}"
  749. )
  750. self._known_warnings.remove(warning)
  751. if state == "preempted" and job_tracker.entity == self._entity:
  752. config = launch_spec.copy()
  753. config["run_id"] = job_tracker.run_id
  754. config["_resume_count"] = config.get("_resume_count", 0) + 1
  755. with self._jobs_lock:
  756. job_tracker.completed_status = state
  757. if config["_resume_count"] > MAX_RESUME_COUNT:
  758. wandb.termlog(
  759. f"{LOG_PREFIX}Run {job_tracker.run_id} has already resumed {MAX_RESUME_COUNT} times."
  760. )
  761. return True
  762. wandb.termlog(
  763. f"{LOG_PREFIX}Run {job_tracker.run_id} was preempted, requeuing..."
  764. )
  765. if "sweep_id" in config:
  766. # allow resumed runs from sweeps that have already completed by removing
  767. # the sweep id before pushing to queue
  768. del config["sweep_id"]
  769. launch_add(
  770. config=config,
  771. project_queue=self._project,
  772. queue_name=job_tracker.queue,
  773. )
  774. return True
  775. # TODO change these statuses to an enum
  776. if state in ["stopped", "failed", "finished", "preempted"]:
  777. if job_tracker.is_scheduler:
  778. wandb.termlog(f"{LOG_PREFIX}Scheduler finished with ID: {run.id}")
  779. if state == "failed":
  780. # on fail, update sweep state. scheduler run_id should == sweep_id
  781. try:
  782. self._api.set_sweep_state(
  783. sweep=job_tracker.run_id,
  784. entity=job_tracker.entity,
  785. project=job_tracker.project,
  786. state="CANCELED",
  787. )
  788. except Exception as e:
  789. raise LaunchError(f"Failed to update sweep state: {e}")
  790. else:
  791. wandb.termlog(f"{LOG_PREFIX}Job finished with ID: {run.id}")
  792. with self._jobs_lock:
  793. job_tracker.completed_status = state
  794. return True
  795. return False
  796. except LaunchError as e:
  797. wandb.termerror(
  798. f"{LOG_PREFIX}Terminating job {run.id} because it failed to start: {str(e)}"
  799. )
  800. known_error = True
  801. with self._jobs_lock:
  802. job_tracker.failed_to_start = True
  803. # TODO: make get_status robust to errors for each runner, and handle them
  804. except Exception as e:
  805. wandb.termerror(f"{LOG_PREFIX}Error getting status for job {run.id}")
  806. wandb.termerror(traceback.format_exc())
  807. _logger.info("---")
  808. _logger.info("Caught exception while getting status.")
  809. _logger.info(f"Job ID: {run.id}")
  810. _logger.info(traceback.format_exc())
  811. _logger.info("---")
  812. get_sentry().exception(e)
  813. return known_error
  814. async def get_job_and_queue(self) -> JobSpecAndQueue | None:
  815. for queue in self._queues:
  816. job = await self.pop_from_queue(queue)
  817. if job is not None:
  818. self._queues.remove(queue)
  819. self._queues.append(queue)
  820. return JobSpecAndQueue(job, queue)
  821. return None
  822. def _set_queue_and_rqi_in_project(
  823. self, project: LaunchProject, job: dict[str, Any], queue: str
  824. ) -> None:
  825. project.queue_name = queue
  826. # queue entity currently always matches the agent
  827. project.queue_entity = self._entity
  828. project.run_queue_item_id = job["runQueueItemId"]