config.py 9.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297
  1. """Definition of the config object used by the Launch agent."""
  2. from __future__ import annotations
  3. from enum import Enum
  4. # ValidationError is imported for exception type checking purposes only.
  5. from pydantic import ( # type: ignore
  6. BaseModel,
  7. Field,
  8. ValidationError,
  9. root_validator,
  10. validator,
  11. )
  12. import wandb
  13. from wandb.sdk.launch.utils import (
  14. AZURE_BLOB_REGEX,
  15. AZURE_CONTAINER_REGISTRY_URI_REGEX,
  16. ELASTIC_CONTAINER_REGISTRY_URI_REGEX,
  17. GCP_ARTIFACT_REGISTRY_URI_REGEX,
  18. GCS_URI_RE,
  19. S3_URI_RE,
  20. )
  21. __all__ = [
  22. "ValidationError",
  23. "AgentConfig",
  24. ]
  25. class EnvironmentType(str, Enum):
  26. """Enum of valid environment types."""
  27. aws = "aws"
  28. gcp = "gcp"
  29. azure = "azure"
  30. class RegistryType(str, Enum):
  31. """Enum of valid registry types."""
  32. ecr = "ecr"
  33. acr = "acr"
  34. gcr = "gcr"
  35. class BuilderType(str, Enum):
  36. """Enum of valid builder types."""
  37. docker = "docker"
  38. kaniko = "kaniko"
  39. noop = "noop"
  40. class TargetPlatform(str, Enum):
  41. """Enum of valid target platforms."""
  42. linux_amd64 = "linux/amd64"
  43. linux_arm64 = "linux/arm64"
  44. class RegistryConfig(BaseModel):
  45. """Configuration for registry block.
  46. Note that we don't forbid extra fields here because:
  47. - We want to allow all fields supported by each registry
  48. - We will perform validation on the registry object itself later
  49. - Registry block is being deprecated in favor of destination field in builder
  50. """
  51. type: RegistryType | None = Field(
  52. None,
  53. description="The type of registry to use.",
  54. )
  55. uri: str | None = Field(
  56. None,
  57. description="The URI of the registry.",
  58. )
  59. @validator("uri") # type: ignore
  60. @classmethod
  61. def validate_uri(cls, uri: str) -> str:
  62. return validate_registry_uri(uri)
  63. class EnvironmentConfig(BaseModel):
  64. """Configuration for the environment block."""
  65. type: EnvironmentType | None = Field(
  66. None,
  67. description="The type of environment to use.",
  68. )
  69. region: str | None = Field(..., description="The region to use.")
  70. class Config:
  71. extra = "allow"
  72. @root_validator(pre=True) # type: ignore
  73. @classmethod
  74. def check_extra_fields(cls, values: dict) -> dict:
  75. """Check for extra fields and print a warning."""
  76. for key in values:
  77. if key not in ["type", "region"]:
  78. wandb.termwarn(
  79. f"Unrecognized field {key} in environment block. Please check your config file."
  80. )
  81. return values
  82. class BuilderConfig(BaseModel):
  83. type: BuilderType | None = Field(
  84. None,
  85. description="The type of builder to use.",
  86. )
  87. destination: str | None = Field(
  88. None,
  89. description="The destination to use for the built image. If not provided, "
  90. "the image will be pushed to the registry.",
  91. )
  92. platform: TargetPlatform | None = Field(
  93. None,
  94. description="The platform to use for the built image. If not provided, "
  95. "the platform will be detected automatically.",
  96. )
  97. build_context_store: str | None = Field(
  98. None,
  99. description="The build context store to use. Required for kaniko builds.",
  100. alias="build-context-store",
  101. )
  102. build_job_name: str | None = Field(
  103. "wandb-launch-container-build",
  104. description="Name prefix of the build job.",
  105. alias="build-job-name",
  106. )
  107. secret_name: str | None = Field(
  108. None,
  109. description="The name of the secret to use for the build job.",
  110. alias="secret-name",
  111. )
  112. secret_key: str | None = Field(
  113. None,
  114. description="The key of the secret to use for the build job.",
  115. alias="secret-key",
  116. )
  117. kaniko_image: str | None = Field(
  118. "gcr.io/kaniko-project/executor:latest",
  119. description="The image to use for the kaniko executor.",
  120. alias="kaniko-image",
  121. )
  122. @validator("build_context_store") # type: ignore
  123. @classmethod
  124. def validate_build_context_store(
  125. cls, build_context_store: str | None
  126. ) -> str | None:
  127. """Validate that the build context store is a valid container registry URI."""
  128. if build_context_store is None:
  129. return None
  130. for regex in [
  131. S3_URI_RE,
  132. GCS_URI_RE,
  133. AZURE_BLOB_REGEX,
  134. ]:
  135. if regex.match(build_context_store):
  136. return build_context_store
  137. raise ValueError(
  138. "Invalid build context store. Build context store must be a URI for an "
  139. "S3 bucket, GCS bucket, or Azure blob."
  140. )
  141. @root_validator(pre=True) # type: ignore
  142. @classmethod
  143. def validate_docker(cls, values: dict) -> dict:
  144. """Right now there are no required fields for docker builds."""
  145. return values
  146. @validator("destination") # type: ignore
  147. @classmethod
  148. def validate_destination(cls, destination: str | None) -> str | None:
  149. """Validate that the destination is a valid container registry URI."""
  150. if destination is None:
  151. return None
  152. return validate_registry_uri(destination)
  153. class AgentConfig(BaseModel):
  154. """Configuration for the Launch agent."""
  155. queues: list[str] = Field(
  156. default=[],
  157. description="The queues to use for this agent.",
  158. )
  159. entity: str | None = Field(
  160. description="The W&B entity to use for this agent.",
  161. )
  162. max_jobs: int | None = Field(
  163. 1,
  164. description="The maximum number of jobs to run concurrently.",
  165. )
  166. max_schedulers: int | None = Field(
  167. 1,
  168. description="The maximum number of sweep schedulers to run concurrently.",
  169. )
  170. secure_mode: bool | None = Field(
  171. False,
  172. description="Whether to use secure mode for this agent. If True, the "
  173. "agent will reject runs that attempt to override the entrypoint or image.",
  174. )
  175. registry: RegistryConfig | None = Field(
  176. None,
  177. description="The registry to use.",
  178. )
  179. environment: EnvironmentConfig | None = Field(
  180. None,
  181. description="The environment to use.",
  182. )
  183. builder: BuilderConfig | None = Field(
  184. None,
  185. description="The builder to use.",
  186. )
  187. verbosity: int | None = Field(
  188. 0,
  189. description="How verbose to print, 0 = default, 1 = verbose, 2 = very verbose",
  190. )
  191. stopped_run_timeout: int | None = Field(
  192. 60,
  193. description="How many seconds to wait after receiving the stop command before forcibly cancelling a run.",
  194. )
  195. class Config:
  196. extra = "forbid"
  197. def validate_registry_uri(uri: str) -> str:
  198. """Validate that the registry URI is a valid container registry URI.
  199. The URI should resolve to an image name in a container registry. The recognized
  200. formats are for ECR, ACR, and GCP Artifact Registry. If the URI does not match
  201. any of these formats, a warning is printed indicating the registry type is not
  202. recognized and the agent can't guarantee that images can be pushed.
  203. If the format is recognized but does not resolve to an image name, an
  204. error is raised. For example, if the URI is an ECR URI but does not include
  205. an image name or includes a tag as well as an image name, an error is raised.
  206. """
  207. tag_msg = (
  208. "Destination for built images may not include a tag, but the URI provided "
  209. "includes the suffix '{tag}'. Please remove the tag and try again. The agent "
  210. "will automatically tag each image with a unique hash of the source code."
  211. )
  212. if uri.startswith("https://"):
  213. uri = uri[8:]
  214. match = GCP_ARTIFACT_REGISTRY_URI_REGEX.match(uri)
  215. if match:
  216. if match.group("tag"):
  217. raise ValueError(tag_msg.format(tag=match.group("tag")))
  218. if not match.group("image_name"):
  219. raise ValueError(
  220. "An image name must be specified in the URI for a GCP Artifact Registry. "
  221. "Please provide a uri with the format "
  222. "'https://<region>-docker.pkg.dev/<project>/<repository>/<image>'."
  223. )
  224. return uri
  225. match = AZURE_CONTAINER_REGISTRY_URI_REGEX.match(uri)
  226. if match:
  227. if match.group("tag"):
  228. raise ValueError(tag_msg.format(tag=match.group("tag")))
  229. if not match.group("repository"):
  230. raise ValueError(
  231. "A repository name must be specified in the URI for an "
  232. "Azure Container Registry. Please provide a uri with the format "
  233. "'https://<registry-name>.azurecr.io/<repository>'."
  234. )
  235. return uri
  236. match = ELASTIC_CONTAINER_REGISTRY_URI_REGEX.match(uri)
  237. if match:
  238. if match.group("tag"):
  239. raise ValueError(tag_msg.format(tag=match.group("tag")))
  240. if not match.group("repository"):
  241. raise ValueError(
  242. "A repository name must be specified in the URI for an "
  243. "Elastic Container Registry. Please provide a uri with the format "
  244. "'https://<account-id>.dkr.ecr.<region>.amazonaws.com/<repository>'."
  245. )
  246. return uri
  247. wandb.termwarn(
  248. f"Unable to recognize registry type in URI {uri}. You are responsible "
  249. "for ensuring the agent can push images to this registry."
  250. )
  251. return uri