sagemaker-core 1.0.62__py3-none-any.whl → 2.3.1__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (358) hide show
  1. sagemaker/__init__.py +2 -0
  2. sagemaker/core/__init__.py +16 -0
  3. sagemaker/core/_studio.py +116 -0
  4. sagemaker/core/_version.py +11 -0
  5. sagemaker/core/accept_types.py +131 -0
  6. sagemaker/core/analytics.py +744 -0
  7. sagemaker/core/apiutils/__init__.py +13 -0
  8. sagemaker/core/apiutils/_base_types.py +228 -0
  9. sagemaker/core/apiutils/_boto_functions.py +130 -0
  10. sagemaker/core/apiutils/_utils.py +34 -0
  11. sagemaker/core/base_deserializers.py +35 -0
  12. sagemaker/core/base_serializers.py +35 -0
  13. sagemaker/core/clarify/__init__.py +2898 -0
  14. sagemaker/core/collection.py +467 -0
  15. sagemaker/core/common_utils.py +2399 -0
  16. sagemaker/core/compute_resource_requirements/__init__.py +18 -0
  17. sagemaker/core/compute_resource_requirements/resource_requirements.py +94 -0
  18. sagemaker/core/config/__init__.py +181 -0
  19. sagemaker/core/config/config.py +238 -0
  20. sagemaker/core/config/config_manager.py +595 -0
  21. sagemaker/core/config/config_schema.py +1220 -0
  22. sagemaker/core/config/config_utils.py +297 -0
  23. {sagemaker_core/main → sagemaker/core}/config_schema.py +408 -3
  24. sagemaker/core/constants.py +73 -0
  25. sagemaker/core/content_types.py +137 -0
  26. sagemaker/core/debugger/__init__.py +39 -0
  27. sagemaker/core/debugger/debugger.py +945 -0
  28. sagemaker/core/debugger/framework_profile.py +292 -0
  29. sagemaker/core/debugger/metrics_config.py +468 -0
  30. sagemaker/core/debugger/profiler.py +42 -0
  31. sagemaker/core/debugger/profiler_config.py +190 -0
  32. sagemaker/core/debugger/profiler_constants.py +40 -0
  33. sagemaker/core/debugger/utils.py +148 -0
  34. sagemaker/core/deprecations.py +254 -0
  35. sagemaker/core/deserializers/__init__.py +10 -0
  36. sagemaker/core/deserializers/base.py +424 -0
  37. sagemaker/core/deserializers/implementations.py +157 -0
  38. sagemaker/core/drift_check_baselines.py +106 -0
  39. sagemaker/core/enums.py +51 -0
  40. sagemaker/core/environment_variables.py +101 -0
  41. sagemaker/core/exceptions.py +108 -0
  42. sagemaker/core/experiments/__init__.py +53 -0
  43. sagemaker/core/experiments/_api_types.py +251 -0
  44. sagemaker/core/experiments/_environment.py +124 -0
  45. sagemaker/core/experiments/_helper.py +294 -0
  46. sagemaker/core/experiments/_metrics.py +333 -0
  47. sagemaker/core/experiments/_run_context.py +58 -0
  48. sagemaker/core/experiments/_utils.py +216 -0
  49. sagemaker/core/experiments/experiment.py +247 -0
  50. sagemaker/core/experiments/run.py +970 -0
  51. sagemaker/core/experiments/trial.py +296 -0
  52. sagemaker/core/experiments/trial_component.py +387 -0
  53. sagemaker/core/explainer/__init__.py +24 -0
  54. sagemaker/core/explainer/clarify_explainer_config.py +298 -0
  55. sagemaker/core/explainer/explainer_config.py +44 -0
  56. sagemaker/core/fw_utils.py +1220 -0
  57. sagemaker/core/git_utils.py +415 -0
  58. sagemaker/core/helper/pipeline_variable.py +82 -0
  59. sagemaker/core/helper/session_helper.py +2977 -0
  60. sagemaker/core/hyperparameters.py +172 -0
  61. sagemaker/core/image_retriever/__init__.py +3 -0
  62. sagemaker/core/image_retriever/image_retriever.py +640 -0
  63. sagemaker/core/image_retriever/image_retriever_utils.py +509 -0
  64. sagemaker/core/image_retriever/test.py +7 -0
  65. sagemaker/core/image_uri_config/autogluon.json +1335 -0
  66. sagemaker/core/image_uri_config/blazingtext.json +50 -0
  67. sagemaker/core/image_uri_config/chainer.json +104 -0
  68. sagemaker/core/image_uri_config/clarify.json +39 -0
  69. sagemaker/core/image_uri_config/coach-mxnet.json +70 -0
  70. sagemaker/core/image_uri_config/coach-tensorflow.json +186 -0
  71. sagemaker/core/image_uri_config/data-wrangler.json +91 -0
  72. sagemaker/core/image_uri_config/debugger.json +34 -0
  73. sagemaker/core/image_uri_config/detailed-profiler.json +18 -0
  74. sagemaker/core/image_uri_config/djl-deepspeed.json +385 -0
  75. sagemaker/core/image_uri_config/djl-fastertransformer.json +167 -0
  76. sagemaker/core/image_uri_config/djl-lmi.json +136 -0
  77. sagemaker/core/image_uri_config/djl-neuronx.json +258 -0
  78. sagemaker/core/image_uri_config/djl-tensorrtllm.json +262 -0
  79. sagemaker/core/image_uri_config/factorization-machines.json +50 -0
  80. sagemaker/core/image_uri_config/forecasting-deepar.json +50 -0
  81. sagemaker/core/image_uri_config/huggingface-llm-neuronx.json +770 -0
  82. sagemaker/core/image_uri_config/huggingface-llm.json +1267 -0
  83. sagemaker/core/image_uri_config/huggingface-neuron.json +52 -0
  84. sagemaker/core/image_uri_config/huggingface-neuronx.json +686 -0
  85. sagemaker/core/image_uri_config/huggingface-tei-cpu.json +298 -0
  86. sagemaker/core/image_uri_config/huggingface-tei.json +298 -0
  87. sagemaker/core/image_uri_config/huggingface-training-compiler.json +195 -0
  88. sagemaker/core/image_uri_config/huggingface-vllm-neuronx.json +38 -0
  89. sagemaker/core/image_uri_config/huggingface.json +2287 -0
  90. sagemaker/core/image_uri_config/hyperpod-recipes-neuron.json +52 -0
  91. sagemaker/core/image_uri_config/image-classification-neo.json +43 -0
  92. sagemaker/core/image_uri_config/image-classification.json +50 -0
  93. sagemaker/core/image_uri_config/inferentia-mxnet.json +88 -0
  94. sagemaker/core/image_uri_config/inferentia-pytorch.json +127 -0
  95. sagemaker/core/image_uri_config/inferentia-tensorflow.json +88 -0
  96. sagemaker/core/image_uri_config/instance_gpu_info.json +782 -0
  97. sagemaker/core/image_uri_config/ipinsights.json +50 -0
  98. sagemaker/core/image_uri_config/kmeans.json +50 -0
  99. sagemaker/core/image_uri_config/knn.json +50 -0
  100. sagemaker/core/image_uri_config/lda.json +26 -0
  101. sagemaker/core/image_uri_config/linear-learner.json +50 -0
  102. sagemaker/core/image_uri_config/model-monitor.json +42 -0
  103. sagemaker/core/image_uri_config/mxnet.json +1154 -0
  104. sagemaker/core/image_uri_config/neo-mxnet.json +64 -0
  105. sagemaker/core/image_uri_config/neo-pytorch.json +341 -0
  106. sagemaker/core/image_uri_config/neo-tensorflow.json +109 -0
  107. sagemaker/core/image_uri_config/ntm.json +50 -0
  108. sagemaker/core/image_uri_config/object-detection.json +50 -0
  109. sagemaker/core/image_uri_config/object2vec.json +50 -0
  110. sagemaker/core/image_uri_config/pca.json +50 -0
  111. sagemaker/core/image_uri_config/pytorch-neuron.json +43 -0
  112. sagemaker/core/image_uri_config/pytorch-smp.json +218 -0
  113. sagemaker/core/image_uri_config/pytorch-training-compiler.json +80 -0
  114. sagemaker/core/image_uri_config/pytorch.json +3101 -0
  115. sagemaker/core/image_uri_config/randomcutforest.json +50 -0
  116. sagemaker/core/image_uri_config/ray-pytorch.json +46 -0
  117. sagemaker/core/image_uri_config/ray-tensorflow.json +194 -0
  118. sagemaker/core/image_uri_config/sagemaker-base-python.json +46 -0
  119. sagemaker/core/image_uri_config/sagemaker-distribution.json +37 -0
  120. sagemaker/core/image_uri_config/sagemaker-geospatial.json +13 -0
  121. sagemaker/core/image_uri_config/sagemaker-tritonserver.json +252 -0
  122. sagemaker/core/image_uri_config/semantic-segmentation.json +50 -0
  123. sagemaker/core/image_uri_config/seq2seq.json +50 -0
  124. sagemaker/core/image_uri_config/sklearn.json +494 -0
  125. sagemaker/core/image_uri_config/spark.json +280 -0
  126. sagemaker/core/image_uri_config/sparkml-serving.json +97 -0
  127. sagemaker/core/image_uri_config/stabilityai.json +53 -0
  128. sagemaker/core/image_uri_config/tensorflow.json +5086 -0
  129. sagemaker/core/image_uri_config/vw.json +25 -0
  130. sagemaker/core/image_uri_config/xgboost-neo.json +43 -0
  131. sagemaker/core/image_uri_config/xgboost.json +972 -0
  132. sagemaker/core/image_uris.py +816 -0
  133. sagemaker/core/inference_config.py +144 -0
  134. sagemaker/core/inference_recommender/__init__.py +18 -0
  135. sagemaker/core/inference_recommender/inference_recommender_mixin.py +622 -0
  136. sagemaker/core/inputs.py +366 -0
  137. sagemaker/core/instance_group.py +61 -0
  138. sagemaker/core/instance_types.py +164 -0
  139. sagemaker/core/instance_types_gpu_info.py +43 -0
  140. sagemaker/core/interactive_apps/__init__.py +41 -0
  141. sagemaker/core/interactive_apps/base_interactive_app.py +204 -0
  142. sagemaker/core/interactive_apps/detail_profiler_app.py +139 -0
  143. sagemaker/core/interactive_apps/tensorboard.py +149 -0
  144. sagemaker/core/iterators.py +197 -0
  145. sagemaker/core/job.py +380 -0
  146. sagemaker/core/jumpstart/__init__.py +156 -0
  147. sagemaker/core/jumpstart/accessors.py +390 -0
  148. sagemaker/core/jumpstart/artifacts/__init__.py +69 -0
  149. sagemaker/core/jumpstart/artifacts/environment_variables.py +252 -0
  150. sagemaker/core/jumpstart/artifacts/hyperparameters.py +120 -0
  151. sagemaker/core/jumpstart/artifacts/image_uris.py +139 -0
  152. sagemaker/core/jumpstart/artifacts/incremental_training.py +87 -0
  153. sagemaker/core/jumpstart/artifacts/instance_types.py +223 -0
  154. sagemaker/core/jumpstart/artifacts/kwargs.py +289 -0
  155. sagemaker/core/jumpstart/artifacts/metric_definitions.py +117 -0
  156. sagemaker/core/jumpstart/artifacts/model_packages.py +202 -0
  157. sagemaker/core/jumpstart/artifacts/model_uris.py +252 -0
  158. sagemaker/core/jumpstart/artifacts/payloads.py +96 -0
  159. sagemaker/core/jumpstart/artifacts/predictors.py +540 -0
  160. sagemaker/core/jumpstart/artifacts/resource_names.py +86 -0
  161. sagemaker/core/jumpstart/artifacts/resource_requirements.py +162 -0
  162. sagemaker/core/jumpstart/artifacts/script_uris.py +172 -0
  163. sagemaker/core/jumpstart/cache.py +663 -0
  164. sagemaker/core/jumpstart/configs.py +50 -0
  165. sagemaker/core/jumpstart/constants.py +198 -0
  166. sagemaker/core/jumpstart/deserializers.py +81 -0
  167. sagemaker/core/jumpstart/document.py +76 -0
  168. sagemaker/core/jumpstart/enums.py +168 -0
  169. sagemaker/core/jumpstart/exceptions.py +236 -0
  170. sagemaker/core/jumpstart/factory/utils.py +833 -0
  171. sagemaker/core/jumpstart/filters.py +597 -0
  172. sagemaker/core/jumpstart/hub/constants.py +16 -0
  173. sagemaker/core/jumpstart/hub/hub.py +291 -0
  174. sagemaker/core/jumpstart/hub/interfaces.py +936 -0
  175. sagemaker/core/jumpstart/hub/parser_utils.py +70 -0
  176. sagemaker/core/jumpstart/hub/parsers.py +288 -0
  177. sagemaker/core/jumpstart/hub/types.py +35 -0
  178. sagemaker/core/jumpstart/hub/utils.py +260 -0
  179. sagemaker/core/jumpstart/models.py +501 -0
  180. sagemaker/core/jumpstart/notebook_utils.py +575 -0
  181. sagemaker/core/jumpstart/parameters.py +20 -0
  182. sagemaker/core/jumpstart/payload_utils.py +239 -0
  183. sagemaker/core/jumpstart/region_config.json +171 -0
  184. sagemaker/core/jumpstart/search.py +171 -0
  185. sagemaker/core/jumpstart/serializers.py +81 -0
  186. sagemaker/core/jumpstart/session_utils.py +234 -0
  187. sagemaker/core/jumpstart/types.py +3044 -0
  188. sagemaker/core/jumpstart/utils.py +1731 -0
  189. sagemaker/core/jumpstart/validators.py +257 -0
  190. sagemaker/core/lambda_helper.py +312 -0
  191. sagemaker/core/lineage/__init__.py +42 -0
  192. sagemaker/core/lineage/_api_types.py +239 -0
  193. sagemaker/core/lineage/_utils.py +49 -0
  194. sagemaker/core/lineage/action.py +345 -0
  195. sagemaker/core/lineage/artifact.py +646 -0
  196. sagemaker/core/lineage/association.py +190 -0
  197. sagemaker/core/lineage/context.py +505 -0
  198. sagemaker/core/lineage/lineage_trial_component.py +191 -0
  199. sagemaker/core/lineage/query.py +732 -0
  200. sagemaker/core/lineage/visualizer.py +346 -0
  201. sagemaker/core/local/__init__.py +18 -0
  202. sagemaker/core/local/data.py +423 -0
  203. sagemaker/core/local/entities.py +678 -0
  204. sagemaker/core/local/exceptions.py +17 -0
  205. sagemaker/core/local/image.py +1243 -0
  206. sagemaker/core/local/local_session.py +739 -0
  207. sagemaker/core/local/utils.py +246 -0
  208. sagemaker/core/logs.py +181 -0
  209. sagemaker/core/metadata_properties.py +56 -0
  210. sagemaker/core/metric_definitions.py +91 -0
  211. sagemaker/core/mlflow/__init__.py +38 -0
  212. sagemaker/core/mlflow/forward_sagemaker_metrics.py +44 -0
  213. sagemaker/core/model_card/__init__.py +26 -0
  214. sagemaker/core/model_life_cycle.py +51 -0
  215. sagemaker/core/model_metrics.py +160 -0
  216. sagemaker/core/model_monitor/__init__.py +66 -0
  217. sagemaker/core/model_monitor/clarify_model_monitoring.py +1497 -0
  218. sagemaker/core/model_monitor/cron_expression_generator.py +82 -0
  219. sagemaker/core/model_monitor/data_capture_config.py +115 -0
  220. sagemaker/core/model_monitor/data_quality_monitoring_config.py +66 -0
  221. sagemaker/core/model_monitor/dataset_format.py +102 -0
  222. sagemaker/core/model_monitor/model_monitoring.py +4266 -0
  223. sagemaker/core/model_monitor/monitoring_alert.py +76 -0
  224. sagemaker/core/model_monitor/monitoring_files.py +506 -0
  225. sagemaker/core/model_monitor/utils.py +793 -0
  226. sagemaker/core/model_registry.py +480 -0
  227. sagemaker/core/model_uris.py +97 -0
  228. sagemaker/core/modules/__init__.py +19 -0
  229. sagemaker/core/modules/configs.py +239 -0
  230. sagemaker/core/modules/constants.py +37 -0
  231. sagemaker/core/modules/distributed.py +182 -0
  232. sagemaker/core/modules/local_core/local_container.py +605 -0
  233. sagemaker/core/modules/templates.py +83 -0
  234. sagemaker/core/modules/train/__init__.py +14 -0
  235. sagemaker/core/modules/train/container_drivers/__init__.py +14 -0
  236. sagemaker/core/modules/train/container_drivers/common/__init__.py +14 -0
  237. sagemaker/core/modules/train/container_drivers/common/utils.py +205 -0
  238. sagemaker/core/modules/train/container_drivers/distributed_drivers/__init__.py +14 -0
  239. sagemaker/core/modules/train/container_drivers/distributed_drivers/basic_script_driver.py +81 -0
  240. sagemaker/core/modules/train/container_drivers/distributed_drivers/mpi_driver.py +123 -0
  241. sagemaker/core/modules/train/container_drivers/distributed_drivers/mpi_utils.py +302 -0
  242. sagemaker/core/modules/train/container_drivers/distributed_drivers/torchrun_driver.py +129 -0
  243. sagemaker/core/modules/train/container_drivers/scripts/__init__.py +14 -0
  244. sagemaker/core/modules/train/container_drivers/scripts/environment.py +305 -0
  245. sagemaker/core/modules/train/sm_recipes/__init__.py +0 -0
  246. sagemaker/core/modules/train/sm_recipes/utils.py +330 -0
  247. sagemaker/core/modules/types.py +19 -0
  248. sagemaker/core/modules/utils.py +194 -0
  249. sagemaker/core/network.py +185 -0
  250. sagemaker/core/parameter.py +173 -0
  251. sagemaker/core/payloads.py +185 -0
  252. sagemaker/core/processing.py +1599 -0
  253. sagemaker/core/remote_function/__init__.py +19 -0
  254. sagemaker/core/remote_function/checkpoint_location.py +47 -0
  255. sagemaker/core/remote_function/client.py +1310 -0
  256. sagemaker/core/remote_function/core/__init__.py +0 -0
  257. sagemaker/core/remote_function/core/_custom_dispatch_table.py +72 -0
  258. sagemaker/core/remote_function/core/pipeline_variables.py +347 -0
  259. sagemaker/core/remote_function/core/serialization.py +410 -0
  260. sagemaker/core/remote_function/core/stored_function.py +223 -0
  261. sagemaker/core/remote_function/custom_file_filter.py +128 -0
  262. sagemaker/core/remote_function/errors.py +102 -0
  263. sagemaker/core/remote_function/invoke_function.py +167 -0
  264. sagemaker/core/remote_function/job.py +2121 -0
  265. sagemaker/core/remote_function/logging_config.py +38 -0
  266. sagemaker/core/remote_function/runtime_environment/__init__.py +14 -0
  267. sagemaker/core/remote_function/runtime_environment/bootstrap_runtime_environment.py +605 -0
  268. sagemaker/core/remote_function/runtime_environment/mpi_utils_remote.py +252 -0
  269. sagemaker/core/remote_function/runtime_environment/runtime_environment_manager.py +554 -0
  270. sagemaker/core/remote_function/runtime_environment/spark_app.py +18 -0
  271. sagemaker/core/remote_function/spark_config.py +149 -0
  272. sagemaker/core/resource_requirements.py +168 -0
  273. {sagemaker_core/main → sagemaker/core}/resources.py +19098 -10895
  274. sagemaker/core/s3/__init__.py +41 -0
  275. sagemaker/core/s3/client.py +367 -0
  276. sagemaker/core/s3/utils.py +175 -0
  277. sagemaker/core/script_uris.py +93 -0
  278. sagemaker/core/serializers/__init__.py +11 -0
  279. sagemaker/core/serializers/base.py +510 -0
  280. sagemaker/core/serializers/implementations.py +159 -0
  281. sagemaker/core/serializers/utils.py +223 -0
  282. sagemaker/core/serverless_inference_config.py +63 -0
  283. sagemaker/core/session_settings.py +55 -0
  284. sagemaker/core/shapes/__init__.py +3 -0
  285. sagemaker/core/shapes/model_card_shapes.py +159 -0
  286. {sagemaker_core/main → sagemaker/core/shapes}/shapes.py +5810 -1806
  287. sagemaker/core/spark/__init__.py +16 -0
  288. sagemaker/core/spark/defaults.py +16 -0
  289. sagemaker/core/spark/processing.py +1380 -0
  290. sagemaker/core/telemetry/__init__.py +23 -0
  291. sagemaker/core/telemetry/constants.py +82 -0
  292. sagemaker/core/telemetry/telemetry_logging.py +285 -0
  293. sagemaker/core/tools/__init__.py +1 -0
  294. {sagemaker_core → sagemaker/core}/tools/codegen.py +4 -4
  295. {sagemaker_core → sagemaker/core}/tools/constants.py +23 -15
  296. {sagemaker_core → sagemaker/core}/tools/data_extractor.py +1 -1
  297. {sagemaker_core → sagemaker/core}/tools/method.py +1 -1
  298. sagemaker/core/tools/model_card/generate_model_card_from_schema.py +562 -0
  299. {sagemaker_core → sagemaker/core}/tools/resources_codegen.py +165 -98
  300. {sagemaker_core → sagemaker/core}/tools/resources_extractor.py +5 -13
  301. {sagemaker_core → sagemaker/core}/tools/shapes_codegen.py +16 -17
  302. {sagemaker_core → sagemaker/core}/tools/shapes_extractor.py +29 -67
  303. {sagemaker_core → sagemaker/core}/tools/templates.py +39 -17
  304. sagemaker/core/training/__init__.py +14 -0
  305. sagemaker/core/training/configs.py +345 -0
  306. sagemaker/core/training/constants.py +37 -0
  307. sagemaker/core/training/utils.py +77 -0
  308. sagemaker/core/training_compiler/__init__.py +16 -0
  309. sagemaker/core/training_compiler/config.py +197 -0
  310. sagemaker/core/training_compiler_config.py +197 -0
  311. sagemaker/core/transformer.py +793 -0
  312. sagemaker/core/user_agent.py +76 -0
  313. sagemaker/core/utilities/__init__.py +24 -0
  314. sagemaker/core/utilities/cache.py +169 -0
  315. sagemaker/core/utilities/search_expression.py +133 -0
  316. sagemaker/core/utils/__init__.py +48 -0
  317. sagemaker/core/utils/code_injection/__init__.py +0 -0
  318. {sagemaker_core/main → sagemaker/core/utils}/code_injection/codec.py +2 -2
  319. {sagemaker_core/main → sagemaker/core/utils}/code_injection/shape_dag.py +5979 -176
  320. {sagemaker_core/main → sagemaker/core/utils}/exceptions.py +8 -8
  321. sagemaker_core/main/default_configs_helper.py → sagemaker/core/utils/intelligent_defaults_helper.py +5 -6
  322. {sagemaker_core/main → sagemaker/core/utils}/logs.py +1 -2
  323. {sagemaker_core/main → sagemaker/core/utils}/utils.py +27 -22
  324. sagemaker/core/workflow/__init__.py +152 -0
  325. sagemaker/core/workflow/conditions.py +313 -0
  326. sagemaker/core/workflow/entities.py +58 -0
  327. sagemaker/core/workflow/execution_variables.py +89 -0
  328. sagemaker/core/workflow/functions.py +193 -0
  329. sagemaker/core/workflow/parameters.py +222 -0
  330. sagemaker/core/workflow/pipeline_context.py +394 -0
  331. sagemaker/core/workflow/pipeline_definition_config.py +31 -0
  332. sagemaker/core/workflow/properties.py +285 -0
  333. sagemaker/core/workflow/step_outputs.py +65 -0
  334. sagemaker/core/workflow/utilities.py +514 -0
  335. sagemaker/lineage/__init__.py +33 -0
  336. sagemaker/lineage/action.py +28 -0
  337. sagemaker/lineage/artifact.py +28 -0
  338. sagemaker/lineage/context.py +28 -0
  339. sagemaker/lineage/lineage_trial_component.py +28 -0
  340. {sagemaker_core-1.0.62.dist-info → sagemaker_core-2.3.1.dist-info}/METADATA +28 -9
  341. sagemaker_core-2.3.1.dist-info/RECORD +351 -0
  342. sagemaker_core-2.3.1.dist-info/top_level.txt +1 -0
  343. sagemaker_core/_version.py +0 -3
  344. sagemaker_core/helper/session_helper.py +0 -769
  345. sagemaker_core/resources/__init__.py +0 -1
  346. sagemaker_core/shapes/__init__.py +0 -1
  347. sagemaker_core/tools/__init__.py +0 -1
  348. sagemaker_core-1.0.62.dist-info/RECORD +0 -35
  349. sagemaker_core-1.0.62.dist-info/top_level.txt +0 -1
  350. {sagemaker_core → sagemaker/core/helper}/__init__.py +0 -0
  351. {sagemaker_core/helper → sagemaker/core/jumpstart/factory}/__init__.py +0 -0
  352. {sagemaker_core/main → sagemaker/core/jumpstart/hub}/__init__.py +0 -0
  353. {sagemaker_core/main/code_injection → sagemaker/core/modules/local_core}/__init__.py +0 -0
  354. {sagemaker_core/main → sagemaker/core/utils}/code_injection/base.py +0 -0
  355. {sagemaker_core/main → sagemaker/core/utils}/code_injection/constants.py +0 -0
  356. {sagemaker_core/main → sagemaker/core/utils}/user_agent.py +0 -0
  357. {sagemaker_core-1.0.62.dist-info → sagemaker_core-2.3.1.dist-info}/WHEEL +0 -0
  358. {sagemaker_core-1.0.62.dist-info → sagemaker_core-2.3.1.dist-info}/licenses/LICENSE +0 -0
@@ -0,0 +1,1243 @@
1
+ # Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License"). You
4
+ # may not use this file except in compliance with the License. A copy of
5
+ # the License is located at
6
+ #
7
+ # http://aws.amazon.com/apache2.0/
8
+ #
9
+ # or in the "license" file accompanying this file. This file is
10
+ # distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF
11
+ # ANY KIND, either express or implied. See the License for the specific
12
+ # language governing permissions and limitations under the License.
13
+ """Placeholder docstring"""
14
+ from __future__ import absolute_import, annotations
15
+
16
+ import base64
17
+ import copy
18
+ import errno
19
+ import json
20
+ import logging
21
+ import os
22
+ import platform
23
+ import random
24
+ import re
25
+ import shlex
26
+ import shutil
27
+ import string
28
+ import subprocess
29
+ import sys
30
+ import tarfile
31
+ import tempfile
32
+
33
+ from threading import Thread
34
+ from typing import Dict, List
35
+ from six.moves.urllib.parse import urlparse
36
+
37
+ import sagemaker
38
+ from sagemaker.core.config.config_schema import CONTAINER_CONFIG, LOCAL
39
+ import sagemaker.core
40
+ from sagemaker.core.common_utils import custom_extractall_tarfile
41
+
42
+ CONTAINER_PREFIX = "algo"
43
+ STUDIO_HOST_NAME = "sagemaker-local"
44
+ DOCKER_COMPOSE_FILENAME = "docker-compose.yaml"
45
+ DOCKER_COMPOSE_HTTP_TIMEOUT_ENV = "COMPOSE_HTTP_TIMEOUT"
46
+ DOCKER_COMPOSE_HTTP_TIMEOUT = "120"
47
+
48
+ # Environment variables to be set during training
49
+ REGION_ENV_NAME = "AWS_REGION"
50
+ TRAINING_JOB_NAME_ENV_NAME = "TRAINING_JOB_NAME"
51
+ S3_ENDPOINT_URL_ENV_NAME = "S3_ENDPOINT_URL"
52
+ SM_STUDIO_LOCAL_MODE = "SM_STUDIO_LOCAL_MODE"
53
+
54
+ # SELinux Enabled
55
+ SELINUX_ENABLED = os.environ.get("SAGEMAKER_LOCAL_SELINUX_ENABLED", "False").lower() in [
56
+ "1",
57
+ "true",
58
+ "yes",
59
+ ]
60
+
61
+ logger = logging.getLogger(__name__)
62
+
63
+
64
+ class _SageMakerContainer(object):
65
+ """Handle the lifecycle and configuration of a local container execution.
66
+
67
+ This class is responsible for creating the directories and configuration
68
+ files that the docker containers will use for either training or serving.
69
+ """
70
+
71
+ def __init__(
72
+ self,
73
+ instance_type,
74
+ instance_count,
75
+ image,
76
+ sagemaker_session=None,
77
+ container_entrypoint=None,
78
+ container_arguments=None,
79
+ ):
80
+ """Initialize a SageMakerContainer instance
81
+
82
+ It uses a :class:`sagemaker.core.helper.session.Session` for general interaction
83
+ with user configuration such as getting the default sagemaker S3 bucket.
84
+ However this class does not call any of the SageMaker APIs.
85
+
86
+ Args:
87
+ instance_type (str): The instance type to use. Either 'local' or
88
+ 'local_gpu'
89
+ instance_count (int): The number of instances to create.
90
+ image (str): docker image to use.
91
+ sagemaker_session (sagemaker.core.helper.session.Session): a sagemaker session
92
+ to use when interacting with SageMaker.
93
+ container_entrypoint (str): the container entrypoint to execute
94
+ container_arguments (str): the container entrypoint arguments
95
+ """
96
+ from sagemaker.core.local.local_session import LocalSession
97
+
98
+ # check if docker-compose is installed
99
+
100
+ self.compose_cmd_prefix = _SageMakerContainer._get_compose_cmd_prefix()
101
+ self.sagemaker_session = sagemaker_session or LocalSession()
102
+ self.instance_type = instance_type
103
+ self.instance_count = instance_count
104
+ self.image = image
105
+ self.container_entrypoint = container_entrypoint
106
+ self.container_arguments = container_arguments
107
+ # Since we are using a single docker network, Generate a random suffix to attach to the
108
+ # container names. This way multiple jobs can run in parallel.
109
+ suffix = "".join(random.choice(string.ascii_lowercase + string.digits) for _ in range(5))
110
+ self.is_studio = sagemaker.core.local.utils.check_for_studio()
111
+ if self.is_studio:
112
+ if self.instance_count > 1:
113
+ raise NotImplementedError(
114
+ "Multi instance Local Mode execution is "
115
+ "currently not supported in SageMaker Studio."
116
+ )
117
+ # For studio use-case, directories need to be created in `~/tmp`, rather than /tmp
118
+ home = os.path.expanduser("~")
119
+ root_dir = os.path.join(home, "tmp")
120
+ if not os.path.isdir(root_dir):
121
+ os.mkdir(root_dir)
122
+ if self.sagemaker_session.config:
123
+ self.sagemaker_session.config["local"]["container_root"] = root_dir
124
+ else:
125
+ self.sagemaker_session.config = {"local": {"container_root": root_dir}}
126
+ # Studio only supports single instance run
127
+ self.hosts = [STUDIO_HOST_NAME]
128
+ else:
129
+ self.hosts = [
130
+ "{}-{}-{}".format(CONTAINER_PREFIX, i, suffix)
131
+ for i in range(1, self.instance_count + 1)
132
+ ]
133
+
134
+ self.container_root = None
135
+ self.container = None
136
+
137
+ @staticmethod
138
+ def _get_compose_cmd_prefix():
139
+ """Gets the Docker Compose command.
140
+
141
+ The method initially looks for 'docker compose' v2
142
+ executable, if not found looks for 'docker-compose' executable.
143
+
144
+ Returns:
145
+ Docker Compose executable split into list.
146
+
147
+ Raises:
148
+ ImportError: If Docker Compose executable was not found.
149
+ """
150
+ compose_cmd_prefix = []
151
+
152
+ output = None
153
+ try:
154
+ output = subprocess.check_output(
155
+ ["docker", "compose", "version"],
156
+ stderr=subprocess.DEVNULL,
157
+ encoding="UTF-8",
158
+ )
159
+ except subprocess.CalledProcessError:
160
+ logger.info(
161
+ "'Docker Compose' is not installed. "
162
+ "Proceeding to check for 'docker-compose' CLI."
163
+ )
164
+
165
+ if output and "v2" in output.strip():
166
+ logger.info("'Docker Compose' found using Docker CLI.")
167
+ compose_cmd_prefix.extend(["docker", "compose"])
168
+ return compose_cmd_prefix
169
+
170
+ if shutil.which("docker-compose") is not None:
171
+ logger.info("'Docker Compose' found using Docker Compose CLI.")
172
+ compose_cmd_prefix.extend(["docker-compose"])
173
+ return compose_cmd_prefix
174
+
175
+ raise ImportError(
176
+ "Docker Compose is not installed. "
177
+ "Local Mode features will not work without docker compose. "
178
+ "For more information on how to install 'docker compose', please, see "
179
+ "https://docs.docker.com/compose/install/"
180
+ )
181
+
182
+ def process(
183
+ self,
184
+ processing_inputs,
185
+ processing_output_config,
186
+ environment,
187
+ processing_job_name,
188
+ ):
189
+ """Run a processing job locally using docker-compose.
190
+
191
+ Args:
192
+ processing_inputs (dict): The processing input specification.
193
+ processing_output_config (dict): The processing output configuration specification.
194
+ environment (dict): The environment collection for the processing job.
195
+ processing_job_name (str): Name of the local processing job being run.
196
+ """
197
+
198
+ self.container_root = self._create_tmp_folder()
199
+
200
+ # A shared directory for all the containers;
201
+ # it is only mounted if the processing script is Local.
202
+ shared_dir = os.path.join(self.container_root, "shared")
203
+ os.mkdir(shared_dir)
204
+
205
+ data_dir = self._create_tmp_folder()
206
+ volumes = self._prepare_processing_volumes(
207
+ data_dir, processing_inputs, processing_output_config
208
+ )
209
+
210
+ # Create the configuration files for each container that we will create.
211
+ for host in self.hosts:
212
+ _create_processing_config_file_directories(self.container_root, host)
213
+ self.write_processing_config_files(
214
+ host,
215
+ environment,
216
+ processing_inputs,
217
+ processing_output_config,
218
+ processing_job_name,
219
+ )
220
+
221
+ self._generate_compose_file(
222
+ "process", additional_volumes=volumes, additional_env_vars=environment
223
+ )
224
+
225
+ if _ecr_login_if_needed(self.sagemaker_session.boto_session, self.image):
226
+ _pull_image(self.image)
227
+
228
+ compose_command = self._compose()
229
+ process = subprocess.Popen(
230
+ compose_command, stdout=subprocess.PIPE, stderr=subprocess.STDOUT
231
+ )
232
+
233
+ try:
234
+ _stream_output(process)
235
+ finally:
236
+ # Uploading processing outputs back to Amazon S3.
237
+ self._upload_processing_outputs(data_dir, processing_output_config)
238
+
239
+ try:
240
+ # Deleting temporary directories.
241
+ dirs_to_delete = [shared_dir, data_dir]
242
+ self._cleanup(dirs_to_delete)
243
+ except OSError:
244
+ pass
245
+
246
+ # Print our Job Complete line to have a similar experience to training on SageMaker where
247
+ # you see this line at the end.
248
+ logger.info("===== Job Complete =====")
249
+
250
+ def train(self, input_data_config, output_data_config, hyperparameters, environment, job_name):
251
+ """Run a training job locally using docker-compose.
252
+
253
+ Args:
254
+ input_data_config (dict): The Input Data Configuration, this contains data such as the
255
+ channels to be used for training.
256
+ output_data_config: The configuration of the output data.
257
+ hyperparameters (dict): The HyperParameters for the training job.
258
+ environment (dict): The environment collection for the training job.
259
+ job_name (str): Name of the local training job being run.
260
+
261
+ Returns (str): Location of the trained model.
262
+ """
263
+ self.container_root = self._create_tmp_folder()
264
+ os.mkdir(os.path.join(self.container_root, "output"))
265
+ # create output/data folder since sagemaker-containers 2.0 expects it
266
+ os.mkdir(os.path.join(self.container_root, "output", "data"))
267
+ # A shared directory for all the containers. It is only mounted if the training script is
268
+ # Local.
269
+ shared_dir = os.path.join(self.container_root, "shared")
270
+ os.mkdir(shared_dir)
271
+
272
+ data_dir = self._create_tmp_folder()
273
+ volumes = self._prepare_training_volumes(
274
+ data_dir, input_data_config, output_data_config, hyperparameters
275
+ )
276
+ # If local, source directory needs to be updated to mounted /opt/ml/code path
277
+ hyperparameters = self._update_local_src_path(
278
+ hyperparameters, key=sagemaker.serve.model_builder.DIR_PARAM_NAME
279
+ )
280
+
281
+ # Create the configuration files for each container that we will create
282
+ # Each container will map the additional local volumes (if any).
283
+ for host in self.hosts:
284
+ _create_config_file_directories(self.container_root, host)
285
+ self.write_config_files(host, hyperparameters, input_data_config)
286
+ shutil.copytree(data_dir, os.path.join(self.container_root, host, "input", "data"))
287
+
288
+ training_env_vars = {
289
+ REGION_ENV_NAME: self.sagemaker_session.boto_region_name,
290
+ TRAINING_JOB_NAME_ENV_NAME: job_name,
291
+ }
292
+ training_env_vars.update(environment)
293
+ if self.sagemaker_session.s3_resource is not None:
294
+ training_env_vars[S3_ENDPOINT_URL_ENV_NAME] = (
295
+ self.sagemaker_session.s3_resource.meta.client._endpoint.host
296
+ )
297
+
298
+ compose_data = self._generate_compose_file(
299
+ "train", additional_volumes=volumes, additional_env_vars=training_env_vars
300
+ )
301
+
302
+ if _ecr_login_if_needed(self.sagemaker_session.boto_session, self.image):
303
+ _pull_image(self.image)
304
+
305
+ compose_command = self._compose()
306
+ process = subprocess.Popen(
307
+ compose_command, stdout=subprocess.PIPE, stderr=subprocess.STDOUT
308
+ )
309
+
310
+ try:
311
+ _stream_output(process)
312
+ finally:
313
+ artifacts = self.retrieve_artifacts(compose_data, output_data_config, job_name)
314
+
315
+ # free up the training data directory as it may contain
316
+ # lots of data downloaded from S3. This doesn't delete any local
317
+ # data that was just mounted to the container.
318
+ dirs_to_delete = [data_dir, shared_dir]
319
+ self._cleanup(dirs_to_delete)
320
+
321
+ # Print our Job Complete line to have a similar experience to training on SageMaker where
322
+ # you see this line at the end.
323
+ logger.info("===== Job Complete =====")
324
+ return artifacts
325
+
326
+ def serve(self, model_dir, environment):
327
+ """Host a local endpoint using docker-compose.
328
+
329
+ Args:
330
+ primary_container (dict): dictionary containing the container runtime settings
331
+ for serving. Expected keys:
332
+ - 'ModelDataUrl' pointing to a file or s3:// location.
333
+ - 'Environment' a dictionary of environment variables to be passed to the
334
+ hosting container.
335
+ """
336
+ logger.info("serving")
337
+
338
+ self.container_root = self._create_tmp_folder()
339
+ logger.info("creating hosting dir in %s", self.container_root)
340
+
341
+ volumes = self._prepare_serving_volumes(model_dir)
342
+
343
+ # If the user script was passed as a file:// mount it to the container.
344
+ if sagemaker.serve.model_builder.DIR_PARAM_NAME.upper() in environment:
345
+ script_dir = environment[sagemaker.serve.model_builder.DIR_PARAM_NAME.upper()]
346
+ parsed_uri = urlparse(script_dir)
347
+ if parsed_uri.scheme == "file":
348
+ host_dir = os.path.abspath(parsed_uri.netloc + parsed_uri.path)
349
+ volumes.append(_Volume(host_dir, "/opt/ml/code"))
350
+ # Update path to mount location
351
+ environment = environment.copy()
352
+ environment[sagemaker.serve.model_builder.DIR_PARAM_NAME.upper()] = "/opt/ml/code"
353
+
354
+ if _ecr_login_if_needed(self.sagemaker_session.boto_session, self.image):
355
+ _pull_image(self.image)
356
+
357
+ self._generate_compose_file(
358
+ "serve", additional_env_vars=environment, additional_volumes=volumes
359
+ )
360
+
361
+ compose_command = self._compose()
362
+
363
+ self.container = _HostingContainer(compose_command)
364
+ self.container.start()
365
+
366
+ def stop_serving(self):
367
+ """Stop the serving container.
368
+
369
+ The serving container runs in async mode to allow the SDK to do other
370
+ tasks.
371
+ """
372
+ if self.container:
373
+ self.container.down()
374
+ self.container.join()
375
+ self._cleanup()
376
+ # for serving we can delete everything in the container root.
377
+ _delete_tree(self.container_root)
378
+
379
+ def retrieve_artifacts(self, compose_data, output_data_config, job_name):
380
+ """Get the model artifacts from all the container nodes.
381
+
382
+ Used after training completes to gather the data from all the
383
+ individual containers. As the official SageMaker Training Service, it
384
+ will override duplicate files if multiple containers have the same file
385
+ names.
386
+
387
+ Args:
388
+ compose_data (dict): Docker-Compose configuration in dictionary
389
+ format.
390
+ output_data_config: The configuration of the output data.
391
+ job_name: The name of the job.
392
+
393
+ Returns: Local path to the collected model artifacts.
394
+ """
395
+ # We need a directory to store the artfiacts from all the nodes
396
+ # and another one to contained the compressed final artifacts
397
+ artifacts = os.path.join(self.container_root, "artifacts")
398
+ compressed_artifacts = os.path.join(self.container_root, "compressed_artifacts")
399
+ os.mkdir(artifacts)
400
+
401
+ model_artifacts = os.path.join(artifacts, "model")
402
+ output_artifacts = os.path.join(artifacts, "output")
403
+
404
+ artifact_dirs = [model_artifacts, output_artifacts, compressed_artifacts]
405
+ for d in artifact_dirs:
406
+ os.mkdir(d)
407
+
408
+ # Gather the artifacts from all nodes into artifacts/model and artifacts/output
409
+ for host in self.hosts:
410
+ volumes = compose_data["services"][str(host)]["volumes"]
411
+ volumes = [v[:-2] if v.endswith(":z") else v for v in volumes]
412
+ for volume in volumes:
413
+ if re.search(r"^[A-Za-z]:", volume):
414
+ unit, host_dir, container_dir = volume.split(":")
415
+ host_dir = unit + ":" + host_dir
416
+ else:
417
+ host_dir, container_dir = volume.split(":")
418
+ if container_dir == "/opt/ml/model":
419
+ sagemaker.core.local.utils.recursive_copy(host_dir, model_artifacts)
420
+ elif container_dir == "/opt/ml/output":
421
+ sagemaker.core.local.utils.recursive_copy(host_dir, output_artifacts)
422
+
423
+ # Tar Artifacts -> model.tar.gz and output.tar.gz
424
+ model_files = [os.path.join(model_artifacts, name) for name in os.listdir(model_artifacts)]
425
+ output_files = [
426
+ os.path.join(output_artifacts, name) for name in os.listdir(output_artifacts)
427
+ ]
428
+ sagemaker.core.common_utils.create_tar_file(
429
+ model_files, os.path.join(compressed_artifacts, "model.tar.gz")
430
+ )
431
+ sagemaker.core.common_utils.create_tar_file(
432
+ output_files, os.path.join(compressed_artifacts, "output.tar.gz")
433
+ )
434
+
435
+ if output_data_config["S3OutputPath"] == "":
436
+ output_data = "file://%s" % compressed_artifacts
437
+ else:
438
+ # Now we just need to move the compressed artifacts to wherever they are required
439
+ output_data = sagemaker.core.local.utils.move_to_destination(
440
+ compressed_artifacts,
441
+ output_data_config["S3OutputPath"],
442
+ job_name,
443
+ self.sagemaker_session,
444
+ prefix="output",
445
+ )
446
+
447
+ _delete_tree(model_artifacts)
448
+ _delete_tree(output_artifacts)
449
+
450
+ return os.path.join(output_data, "model.tar.gz")
451
+
452
+ def write_processing_config_files(
453
+ self,
454
+ host,
455
+ environment,
456
+ processing_inputs,
457
+ processing_output_config,
458
+ processing_job_name,
459
+ ):
460
+ """Write the config files for the processing containers.
461
+
462
+ This method writes the hyperparameters, resources and input data
463
+ configuration files.
464
+
465
+ Args:
466
+ host (str): Host to write the configuration for
467
+ environment (dict): Environment variable collection.
468
+ processing_inputs (dict): Processing inputs.
469
+ processing_output_config (dict): Processing output configuration.
470
+ processing_job_name (str): Processing job name.
471
+ """
472
+ config_path = os.path.join(self.container_root, host, "config")
473
+
474
+ resource_config = {
475
+ "current_host": host,
476
+ "hosts": self.hosts,
477
+ "network_interface_name": "eth0",
478
+ "current_instance_type": self.instance_type,
479
+ }
480
+ _write_json_file(os.path.join(config_path, "resourceconfig.json"), resource_config)
481
+
482
+ processing_job_config = {
483
+ "ProcessingJobArn": processing_job_name,
484
+ "ProcessingJobName": processing_job_name,
485
+ "AppSpecification": {
486
+ "ImageUri": self.image,
487
+ "ContainerEntrypoint": self.container_entrypoint,
488
+ "ContainerArguments": self.container_arguments,
489
+ },
490
+ "Environment": environment,
491
+ "ProcessingInputs": processing_inputs,
492
+ "ProcessingOutputConfig": processing_output_config,
493
+ "ProcessingResources": {
494
+ "ClusterConfig": {
495
+ "InstanceCount": self.instance_count,
496
+ "InstanceType": self.instance_type,
497
+ "VolumeSizeInGB": 30,
498
+ "VolumeKmsKeyId": None,
499
+ }
500
+ },
501
+ "RoleArn": "<no_role>",
502
+ "StoppingCondition": {"MaxRuntimeInSeconds": 86400},
503
+ }
504
+
505
+ _write_json_file(
506
+ os.path.join(config_path, "processingjobconfig.json"), processing_job_config
507
+ )
508
+
509
+ def write_config_files(self, host, hyperparameters, input_data_config):
510
+ """Write the config files for the training containers.
511
+
512
+ This method writes the hyperparameters, resources and input data
513
+ configuration files.
514
+
515
+ Returns: None
516
+
517
+ Args:
518
+ host (str): Host to write the configuration for
519
+ hyperparameters (dict): Hyperparameters for training.
520
+ input_data_config (dict): Training input channels to be used for
521
+ training.
522
+ """
523
+ config_path = os.path.join(self.container_root, host, "input", "config")
524
+
525
+ resource_config = {
526
+ "current_host": host,
527
+ "hosts": self.hosts,
528
+ "network_interface_name": "eth0",
529
+ "current_instance_type": self.instance_type,
530
+ }
531
+
532
+ json_input_data_config = {}
533
+ for c in input_data_config:
534
+ channel_name = c["ChannelName"]
535
+ json_input_data_config[channel_name] = {"TrainingInputMode": "File"}
536
+ if "ContentType" in c:
537
+ json_input_data_config[channel_name]["ContentType"] = c["ContentType"]
538
+
539
+ _write_json_file(os.path.join(config_path, "hyperparameters.json"), hyperparameters)
540
+ _write_json_file(os.path.join(config_path, "resourceconfig.json"), resource_config)
541
+ _write_json_file(os.path.join(config_path, "inputdataconfig.json"), json_input_data_config)
542
+
543
+ def _prepare_training_volumes(
544
+ self, data_dir, input_data_config, output_data_config, hyperparameters
545
+ ):
546
+ """Prepares the training volumes based on input and output data configs.
547
+
548
+ Args:
549
+ data_dir:
550
+ input_data_config:
551
+ output_data_config:
552
+ hyperparameters:
553
+ """
554
+ shared_dir = os.path.join(self.container_root, "shared")
555
+ model_dir = os.path.join(self.container_root, "model")
556
+ volumes = []
557
+
558
+ volumes.append(_Volume(model_dir, "/opt/ml/model"))
559
+
560
+ # Mount the metadata directory if present.
561
+ # Only expected to be present on SM notebook instances.
562
+ # This is used by some DeepEngine libraries
563
+ metadata_dir = "/opt/ml/metadata"
564
+ if os.path.isdir(metadata_dir):
565
+ volumes.append(_Volume(metadata_dir, metadata_dir))
566
+
567
+ # Set up the channels for the containers. For local data we will
568
+ # mount the local directory to the container. For S3 Data we will download the S3 data
569
+ # first.
570
+ for channel in input_data_config:
571
+ uri = channel["DataUri"]
572
+ channel_name = channel["ChannelName"]
573
+ channel_dir = os.path.join(data_dir, channel_name)
574
+ os.mkdir(channel_dir)
575
+
576
+ data_source = sagemaker.core.local.data.get_data_source_instance(
577
+ uri, self.sagemaker_session
578
+ )
579
+ volumes.append(_Volume(data_source.get_root_dir(), channel=channel_name))
580
+
581
+ # If there is a training script directory and it is a local directory,
582
+ # mount it to the container.
583
+ if sagemaker.serve.model_builder.DIR_PARAM_NAME in hyperparameters:
584
+ training_dir = json.loads(hyperparameters[sagemaker.serve.model_builder.DIR_PARAM_NAME])
585
+ parsed_uri = urlparse(training_dir)
586
+ if parsed_uri.scheme == "file":
587
+ host_dir = os.path.abspath(parsed_uri.netloc + parsed_uri.path)
588
+ volumes.append(_Volume(host_dir, "/opt/ml/code"))
589
+ # Also mount a directory that all the containers can access.
590
+ volumes.append(_Volume(shared_dir, "/opt/ml/shared"))
591
+
592
+ parsed_uri = urlparse(output_data_config["S3OutputPath"])
593
+ if (
594
+ parsed_uri.scheme == "file"
595
+ and sagemaker.serve.model_builder.SAGEMAKER_OUTPUT_LOCATION in hyperparameters
596
+ ):
597
+ dir_path = os.path.abspath(parsed_uri.netloc + parsed_uri.path)
598
+ intermediate_dir = os.path.join(dir_path, "output", "intermediate")
599
+ if not os.path.exists(intermediate_dir):
600
+ os.makedirs(intermediate_dir)
601
+ volumes.append(_Volume(intermediate_dir, "/opt/ml/output/intermediate"))
602
+
603
+ return volumes
604
+
605
+ def _prepare_processing_volumes(self, data_dir, processing_inputs, processing_output_config):
606
+ """Prepares local container volumes for the processing job.
607
+
608
+ Args:
609
+ data_dir: The local data directory.
610
+ processing_inputs: The configuration of processing inputs.
611
+ processing_output_config: The configuration of processing outputs.
612
+
613
+ Returns:
614
+ The volumes configuration.
615
+ """
616
+ shared_dir = os.path.join(self.container_root, "shared")
617
+ volumes = []
618
+
619
+ # Set up the input/outputs for the container.
620
+
621
+ for item in processing_inputs:
622
+ uri = item["DataUri"]
623
+ input_container_dir = item["S3Input"]["LocalPath"]
624
+
625
+ data_source = sagemaker.core.local.data.get_data_source_instance(
626
+ uri, self.sagemaker_session
627
+ )
628
+ volumes.append(_Volume(data_source.get_root_dir(), input_container_dir))
629
+
630
+ if processing_output_config and "Outputs" in processing_output_config:
631
+ for item in processing_output_config["Outputs"]:
632
+ output_name = item["OutputName"]
633
+ output_container_dir = item["S3Output"]["LocalPath"]
634
+
635
+ output_dir = os.path.join(data_dir, "output", output_name)
636
+ os.makedirs(output_dir)
637
+
638
+ volumes.append(_Volume(output_dir, output_container_dir))
639
+
640
+ volumes.append(_Volume(shared_dir, "/opt/ml/shared"))
641
+
642
+ return volumes
643
+
644
+ def _upload_processing_outputs(self, data_dir, processing_output_config):
645
+ """Uploads processing outputs to Amazon S3.
646
+
647
+ Args:
648
+ data_dir: The local data directory.
649
+ processing_output_config: The processing output configuration.
650
+ """
651
+ if processing_output_config and "Outputs" in processing_output_config:
652
+ for item in processing_output_config["Outputs"]:
653
+ output_name = item["OutputName"]
654
+ output_s3_uri = item["S3Output"]["S3Uri"]
655
+ output_dir = os.path.join(data_dir, "output", output_name)
656
+
657
+ sagemaker.core.local.utils.move_to_destination(
658
+ output_dir, output_s3_uri, "", self.sagemaker_session
659
+ )
660
+
661
+ def _update_local_src_path(self, params, key):
662
+ """Updates the local path of source code.
663
+
664
+ Args:
665
+ params: Existing configuration parameters.
666
+ key: Lookup key for the path of the source code in the configuration parameters.
667
+
668
+ Returns:
669
+ The updated parameters.
670
+ """
671
+ if key in params:
672
+ src_dir = json.loads(params[key])
673
+ parsed_uri = urlparse(src_dir)
674
+ if parsed_uri.scheme == "file":
675
+ new_params = params.copy()
676
+ new_params[key] = json.dumps("/opt/ml/code")
677
+ return new_params
678
+ return params
679
+
680
+ def _prepare_serving_volumes(self, model_location):
681
+ """Prepares the serving volumes.
682
+
683
+ Args:
684
+ model_location: Location of the models.
685
+ """
686
+ volumes = []
687
+ host = self.hosts[0]
688
+ # Make the model available to the container. If this is a local file just mount it to
689
+ # the container as a volume. If it is an S3 location, the DataSource will download it, we
690
+ # just need to extract the tar file.
691
+ host_dir = os.path.join(self.container_root, host)
692
+ os.makedirs(host_dir)
693
+
694
+ model_data_source = sagemaker.core.local.data.get_data_source_instance(
695
+ model_location, self.sagemaker_session
696
+ )
697
+
698
+ for filename in model_data_source.get_file_list():
699
+ if tarfile.is_tarfile(filename):
700
+ with tarfile.open(filename) as tar:
701
+ custom_extractall_tarfile(tar, model_data_source.get_root_dir())
702
+
703
+ volumes.append(_Volume(model_data_source.get_root_dir(), "/opt/ml/model"))
704
+
705
+ return volumes
706
+
707
+ def _generate_compose_file(self, command, additional_volumes=None, additional_env_vars=None):
708
+ """Writes a config file describing a training/hosting environment.
709
+
710
+ This method generates a docker compose configuration file, it has an
711
+ entry for each container that will be created (based on self.hosts). it
712
+ calls
713
+ :meth:~sagemaker.local_session.SageMakerContainer._create_docker_host to
714
+ generate the config for each individual container.
715
+
716
+ Args:
717
+ command (str): either 'train' or 'serve'
718
+ additional_volumes (list): a list of volumes that will be mapped to
719
+ the containers
720
+ additional_env_vars (dict): a dictionary with additional environment
721
+ variables to be passed on to the containers.
722
+
723
+ Returns: (dict) A dictionary representation of the configuration that was written.
724
+ """
725
+ boto_session = self.sagemaker_session.boto_session
726
+ additional_volumes = additional_volumes or []
727
+ additional_env_vars = additional_env_vars or {}
728
+ environment = []
729
+ optml_dirs = set()
730
+
731
+ aws_creds = _aws_credentials(boto_session)
732
+ if aws_creds is not None:
733
+ environment.extend(aws_creds)
734
+
735
+ additional_env_var_list = ["{}={}".format(k, v) for k, v in additional_env_vars.items()]
736
+ environment.extend(additional_env_var_list)
737
+
738
+ if self.is_studio:
739
+ environment.extend([f"{SM_STUDIO_LOCAL_MODE}=True"])
740
+
741
+ if os.environ.get(DOCKER_COMPOSE_HTTP_TIMEOUT_ENV) is None:
742
+ os.environ[DOCKER_COMPOSE_HTTP_TIMEOUT_ENV] = DOCKER_COMPOSE_HTTP_TIMEOUT
743
+
744
+ if command == "train":
745
+ optml_dirs = {"output", "output/data", "input"}
746
+ elif command == "process":
747
+ optml_dirs = {"output", "config"}
748
+
749
+ services = {
750
+ h: self._create_docker_host(h, environment, optml_dirs, command, additional_volumes)
751
+ for h in self.hosts
752
+ }
753
+
754
+ if self.is_studio:
755
+ content = {
756
+ # Use version 2.3 as a minimum so that we can specify the runtime
757
+ "version": "2.3",
758
+ "services": services,
759
+ }
760
+ else:
761
+ content = {
762
+ # Use version 2.3 as a minimum so that we can specify the runtime
763
+ "version": "2.3",
764
+ "services": services,
765
+ "networks": {"sagemaker-local": {"name": "sagemaker-local"}},
766
+ }
767
+
768
+ docker_compose_path = os.path.join(self.container_root, DOCKER_COMPOSE_FILENAME)
769
+
770
+ try:
771
+ import yaml
772
+ except ImportError as e:
773
+ logger.error(
774
+ sagemaker.core.common_utils._module_import_error("yaml", "Local mode", "local")
775
+ )
776
+ raise e
777
+
778
+ yaml_content = yaml.dump(content, default_flow_style=False)
779
+ # Mask all environment vars for logging, could contain secrects.
780
+ masked_content = copy.deepcopy(content)
781
+ for _, service_data in masked_content["services"].items():
782
+ service_data["environment"] = ["[Masked]" for _ in service_data["environment"]]
783
+
784
+ masked_content_for_logging = yaml.dump(masked_content, default_flow_style=False)
785
+ logger.info("docker compose file: \n%s", masked_content_for_logging)
786
+ with open(docker_compose_path, "w") as f:
787
+ f.write(yaml_content)
788
+
789
+ return content
790
+
791
+ def _compose(self, detached=False):
792
+ """Invokes the docker compose command.
793
+
794
+ Args:
795
+ detached:
796
+ """
797
+ compose_cmd = self.compose_cmd_prefix
798
+
799
+ command = [
800
+ "-f",
801
+ os.path.join(self.container_root, DOCKER_COMPOSE_FILENAME),
802
+ "up",
803
+ "--build",
804
+ "--abort-on-container-exit" if not detached else "--detach", # mutually exclusive
805
+ ]
806
+
807
+ compose_cmd.extend(command)
808
+
809
+ logger.info("docker command: %s", " ".join(compose_cmd))
810
+ return compose_cmd
811
+
812
+ def _create_docker_host(
813
+ self,
814
+ host: str,
815
+ environment: List[str],
816
+ optml_subdirs: set[str],
817
+ command: str,
818
+ volumes: List,
819
+ ) -> Dict:
820
+ """Creates the docker host configuration.
821
+
822
+ Args:
823
+ host (str): The host address
824
+ environment (List[str]): List of environment variables
825
+ optml_subdirs (Set[str]): Set of subdirs
826
+ command (str): Either 'train' or 'serve'
827
+ volumes (list): List of volumes that will be mapped to the containers
828
+ """
829
+ optml_volumes = self._build_optml_volumes(host, optml_subdirs)
830
+ optml_volumes.extend(volumes)
831
+
832
+ container_name_prefix = "".join(
833
+ random.choice(string.ascii_lowercase + string.digits) for _ in range(10)
834
+ )
835
+ container_default_config = (
836
+ sagemaker.core.config.config_manager.SageMakerConfig.get_config_value(
837
+ f"{LOCAL}.{CONTAINER_CONFIG}", self.sagemaker_session.config
838
+ )
839
+ or {}
840
+ )
841
+
842
+ host_config = {
843
+ **container_default_config,
844
+ "image": self.image,
845
+ "container_name": f"{container_name_prefix}-{host}",
846
+ "stdin_open": True,
847
+ "tty": True,
848
+ "volumes": [v.map for v in optml_volumes],
849
+ "environment": environment,
850
+ }
851
+
852
+ is_train_with_entrypoint = False
853
+ if command == "train" and self.container_entrypoint:
854
+ # Remote function or Pipeline function step is translated into a training job
855
+ # with container_entrypoint configured
856
+ is_train_with_entrypoint = True
857
+
858
+ if command != "process" and not is_train_with_entrypoint:
859
+ host_config["command"] = command
860
+ else:
861
+ if self.container_entrypoint:
862
+ host_config["entrypoint"] = self.container_entrypoint
863
+ if self.container_arguments:
864
+ host_config["entrypoint"] = host_config["entrypoint"] + self.container_arguments
865
+
866
+ if self.is_studio:
867
+ host_config["network_mode"] = "sagemaker"
868
+ else:
869
+ host_config["networks"] = {"sagemaker-local": {"aliases": [host]}}
870
+
871
+ # for GPU support pass in nvidia as the runtime, this is equivalent
872
+ # to setting --runtime=nvidia in the docker commandline.
873
+ if self.instance_type == "local_gpu":
874
+ host_config["deploy"] = {
875
+ "resources": {
876
+ "reservations": {"devices": [{"count": "all", "capabilities": ["gpu"]}]}
877
+ }
878
+ }
879
+
880
+ if not self.is_studio and command == "serve":
881
+ serving_port = (
882
+ sagemaker.core.config.config_manager.SageMakerConfig.get_config_value(
883
+ "local.serving_port", self.sagemaker_session.config
884
+ )
885
+ or 8080
886
+ )
887
+ host_config.update({"ports": ["%s:8080" % serving_port]})
888
+
889
+ return host_config
890
+
891
+ def _create_tmp_folder(self):
892
+ """Placeholder docstring"""
893
+ root_dir = sagemaker.core.config.config_manager.SageMakerConfig.get_config_value(
894
+ "local.container_root", self.sagemaker_session.config
895
+ )
896
+ if root_dir:
897
+ root_dir = os.path.abspath(root_dir)
898
+
899
+ working_dir = tempfile.mkdtemp(dir=root_dir)
900
+
901
+ # Docker cannot mount Mac OS /var folder properly see
902
+ # https://forums.docker.com/t/var-folders-isnt-mounted-properly/9600
903
+ # Only apply this workaround if the user didn't provide an alternate storage root dir.
904
+ if root_dir is None and platform.system() == "Darwin":
905
+ working_dir = "/private{}".format(working_dir)
906
+
907
+ return os.path.abspath(working_dir)
908
+
909
+ def _build_optml_volumes(self, host, subdirs):
910
+ """Generate a list of :class:`~sagemaker.local_session.Volume`.
911
+
912
+ These are required for the container to start. It takes a folder with
913
+ the necessary files for training and creates a list of opt volumes
914
+ that the Container needs to start.
915
+
916
+ Args:
917
+ host (str): container for which the volumes will be generated.
918
+ subdirs (list): list of subdirectories that will be mapped. For
919
+ example: ['input', 'output', 'model']
920
+
921
+ Returns: (list) List of :class:`~sagemaker.local_session.Volume`
922
+ """
923
+ volumes = []
924
+
925
+ for subdir in subdirs:
926
+ host_dir = os.path.join(self.container_root, host, subdir)
927
+ container_dir = "/opt/ml/{}".format(subdir)
928
+ volume = _Volume(host_dir, container_dir)
929
+ volumes.append(volume)
930
+
931
+ return volumes
932
+
933
+ def _cleanup(self, dirs_to_delete=None):
934
+ """Cleans up directories and the like.
935
+
936
+ Args:
937
+ dirs_to_delete:
938
+ """
939
+ if dirs_to_delete:
940
+ for d in dirs_to_delete:
941
+ _delete_tree(d)
942
+
943
+ # Free the container config files.
944
+ for host in self.hosts:
945
+ container_config_path = os.path.join(self.container_root, host)
946
+ _delete_tree(container_config_path)
947
+
948
+
949
+ class _HostingContainer(Thread):
950
+ """Placeholder docstring."""
951
+
952
+ def __init__(self, command):
953
+ """Creates a new threaded hosting container.
954
+
955
+ Args:
956
+ command (dict): docker compose command
957
+ """
958
+ Thread.__init__(self)
959
+ self.command = command
960
+ self.process = None
961
+
962
+ def run(self):
963
+ """Placeholder docstring"""
964
+ self.process = subprocess.Popen(
965
+ self.command, stdout=subprocess.PIPE, stderr=subprocess.PIPE
966
+ )
967
+ try:
968
+ _stream_output(self.process)
969
+ except RuntimeError as e:
970
+ # _stream_output() doesn't have the command line. We will handle the exception
971
+ # which contains the exit code and append the command line to it.
972
+ msg = "Failed to run: %s, %s" % (self.command, str(e))
973
+ raise RuntimeError(msg)
974
+
975
+ def down(self):
976
+ """Placeholder docstring"""
977
+ if os.name != "nt":
978
+ sagemaker.core.local.utils.kill_child_processes(self.process.pid)
979
+ self.process.terminate()
980
+
981
+
982
+ class _Volume(object):
983
+ """Represent a Volume that will be mapped to a container."""
984
+
985
+ def __init__(self, host_dir, container_dir=None, channel=None):
986
+ """Create a Volume instance.
987
+
988
+ The container path can be provided as a container_dir or as a channel name but not both.
989
+
990
+ Args:
991
+ host_dir (str): path to the volume data in the host
992
+ container_dir (str): path inside the container that host_dir will be mapped to
993
+ channel (str): channel name that the host_dir represents. It will be mapped as
994
+ /opt/ml/input/data/<channel> in the container.
995
+ """
996
+ if not container_dir and not channel:
997
+ raise ValueError("Either container_dir or channel must be declared.")
998
+
999
+ if container_dir and channel:
1000
+ raise ValueError("container_dir and channel cannot be declared together.")
1001
+
1002
+ self.container_dir = container_dir if container_dir else "/opt/ml/input/data/" + channel
1003
+ self.host_dir = host_dir
1004
+ map_format = "{}:{}"
1005
+ if platform.system() == "Linux" and SELINUX_ENABLED:
1006
+ # Support mounting shared volumes in SELinux enabled hosts
1007
+ map_format += ":z"
1008
+ if platform.system() == "Darwin" and host_dir.startswith("/var"):
1009
+ self.host_dir = os.path.join("/private", host_dir)
1010
+
1011
+ self.map = map_format.format(self.host_dir, self.container_dir)
1012
+
1013
+
1014
+ def _stream_output(process):
1015
+ """Stream the output of a process to stdout
1016
+
1017
+ This function takes an existing process that will be polled for output.
1018
+ Only stdout will be polled and sent to sys.stdout.
1019
+
1020
+ Args:
1021
+ process (subprocess.Popen): a process that has been started with
1022
+ stdout=PIPE and stderr=STDOUT
1023
+
1024
+ Returns (int): process exit code
1025
+ """
1026
+ exit_code = None
1027
+
1028
+ while exit_code is None:
1029
+ stdout = process.stdout.readline().decode("utf-8")
1030
+ sys.stdout.write(stdout)
1031
+ exit_code = process.poll()
1032
+
1033
+ if exit_code not in [0, 130]:
1034
+ raise RuntimeError(f"Failed to run: {process.args}. Process exited with code: {exit_code}")
1035
+
1036
+ return exit_code
1037
+
1038
+
1039
+ def _check_output(cmd, *popenargs, **kwargs):
1040
+ """Makes a call to `subprocess.check_output` for the given command and args.
1041
+
1042
+ Args:
1043
+ cmd:
1044
+ *popenargs:
1045
+ **kwargs:
1046
+ """
1047
+ if isinstance(cmd, str):
1048
+ cmd = shlex.split(cmd)
1049
+
1050
+ success = True
1051
+ try:
1052
+ output = subprocess.check_output(cmd, *popenargs, **kwargs)
1053
+ except subprocess.CalledProcessError as e:
1054
+ output = e.output
1055
+ success = False
1056
+
1057
+ output = output.decode("utf-8")
1058
+ if not success:
1059
+ logger.error("Command output: %s", output)
1060
+ raise Exception("Failed to run %s" % ",".join(cmd))
1061
+
1062
+ return output
1063
+
1064
+
1065
+ def _create_processing_config_file_directories(root, host):
1066
+ """Creates the directory for the processing config files.
1067
+
1068
+ Args:
1069
+ root: The root path.
1070
+ host: The current host.
1071
+ """
1072
+ for d in ["config"]:
1073
+ os.makedirs(os.path.join(root, host, d))
1074
+
1075
+
1076
+ def _create_config_file_directories(root, host):
1077
+ """Creates the directories for the config files.
1078
+
1079
+ Args:
1080
+ root:
1081
+ host:
1082
+ """
1083
+ for d in ["input", "input/config", "output", "model"]:
1084
+ os.makedirs(os.path.join(root, host, d))
1085
+
1086
+
1087
+ def _delete_tree(path):
1088
+ """Makes a call to `shutil.rmtree` for the given path.
1089
+
1090
+ Args:
1091
+ path:
1092
+ """
1093
+ try:
1094
+ shutil.rmtree(path)
1095
+ except OSError as exc:
1096
+ # on Linux, when docker writes to any mounted volume, it uses the container's user. In most
1097
+ # cases this is root. When the container exits and we try to delete them we can't because
1098
+ # root owns those files. We expect this to happen, so we handle EACCESS. Any other error
1099
+ # we will raise the exception up.
1100
+ if exc.errno == errno.EACCES:
1101
+ logger.warning("Failed to delete: %s Please remove it manually.", path)
1102
+ else:
1103
+ logger.error("Failed to delete: %s", path)
1104
+ raise
1105
+
1106
+
1107
+ def _aws_credentials(session):
1108
+ """Provides the AWS credentials of the session as a paired list of strings.
1109
+
1110
+ These can be used to set environment variables on command execution.
1111
+
1112
+ Args:
1113
+ session:
1114
+ """
1115
+ try:
1116
+ creds = session.get_credentials()
1117
+ access_key = creds.access_key
1118
+ secret_key = creds.secret_key
1119
+ token = creds.token
1120
+
1121
+ # The presence of a token indicates the credentials are short-lived and as such are risky
1122
+ # to be used as they might expire while running.
1123
+ # Long-lived credentials are available either through
1124
+ # 1. boto session
1125
+ # 2. EC2 Metadata Service (SageMaker Notebook instances or EC2 instances with roles
1126
+ # attached them)
1127
+ # Short-lived credentials available via boto session are permitted to support running on
1128
+ # machines with no EC2 Metadata Service but a warning is provided about their danger
1129
+ if token is None:
1130
+ logger.info("Using the long-lived AWS credentials found in session")
1131
+ return [
1132
+ "AWS_ACCESS_KEY_ID=%s" % (str(access_key)),
1133
+ "AWS_SECRET_ACCESS_KEY=%s" % (str(secret_key)),
1134
+ ]
1135
+ if _use_short_lived_credentials() or not _aws_credentials_available_in_metadata_service():
1136
+ logger.warning(
1137
+ "Using the short-lived AWS credentials found in session. They might expire while "
1138
+ "running."
1139
+ )
1140
+ return [
1141
+ "AWS_ACCESS_KEY_ID=%s" % (str(access_key)),
1142
+ "AWS_SECRET_ACCESS_KEY=%s" % (str(secret_key)),
1143
+ "AWS_SESSION_TOKEN=%s" % (str(token)),
1144
+ ]
1145
+ logger.info(
1146
+ "No AWS credentials found in session but credentials from EC2 Metadata Service are "
1147
+ "available."
1148
+ )
1149
+ return None
1150
+ except Exception as e: # pylint: disable=broad-except
1151
+ logger.info("Could not get AWS credentials: %s", e)
1152
+
1153
+ return None
1154
+
1155
+
1156
+ def _aws_credentials_available_in_metadata_service():
1157
+ """Placeholder docstring"""
1158
+ import botocore
1159
+ from botocore.credentials import InstanceMetadataProvider
1160
+ from botocore.utils import InstanceMetadataFetcher
1161
+
1162
+ session = botocore.session.Session()
1163
+ instance_metadata_provider = InstanceMetadataProvider(
1164
+ iam_role_fetcher=InstanceMetadataFetcher(
1165
+ timeout=session.get_config_variable("metadata_service_timeout"),
1166
+ num_attempts=session.get_config_variable("metadata_service_num_attempts"),
1167
+ user_agent=session.user_agent(),
1168
+ )
1169
+ )
1170
+ return not instance_metadata_provider.load() is None
1171
+
1172
+
1173
+ def _use_short_lived_credentials():
1174
+ """Use short-lived AWS credentials found in session."""
1175
+ return os.environ.get("USE_SHORT_LIVED_CREDENTIALS") == "1"
1176
+
1177
+
1178
+ def _write_json_file(filename, content):
1179
+ """Write the contents dict as json to the file.
1180
+
1181
+ Args:
1182
+ filename:
1183
+ content:
1184
+ """
1185
+ with open(filename, "w") as f:
1186
+ json.dump(content, f)
1187
+
1188
+
1189
+ def _ecr_login_if_needed(boto_session, image):
1190
+ """Log into ECR, if needed.
1191
+
1192
+ Of note, only ECR images need login.
1193
+
1194
+ Args:
1195
+ boto_session:
1196
+ image:
1197
+ """
1198
+ sagemaker_pattern = re.compile(sagemaker.core.common_utils.ECR_URI_PATTERN)
1199
+ sagemaker_match = sagemaker_pattern.match(image)
1200
+ if not sagemaker_match:
1201
+ return False
1202
+
1203
+ # do we have the image?
1204
+ if _check_output("docker images -q %s" % image).strip():
1205
+ return False
1206
+
1207
+ if not boto_session:
1208
+ raise RuntimeError(
1209
+ "A boto session is required to login to ECR."
1210
+ "Please pull the image: %s manually." % image
1211
+ )
1212
+
1213
+ ecr = boto_session.client("ecr")
1214
+ auth = ecr.get_authorization_token(registryIds=[image.split(".")[0]])
1215
+ authorization_data = auth["authorizationData"][0]
1216
+
1217
+ raw_token = base64.b64decode(authorization_data["authorizationToken"])
1218
+ token = raw_token.decode("utf-8").strip("AWS:")
1219
+ ecr_url = auth["authorizationData"][0]["proxyEndpoint"]
1220
+
1221
+ # Log in to ecr, but use communicate to not print creds to the console
1222
+ cmd = f"docker login {ecr_url} -u AWS --password-stdin".split()
1223
+ proc = subprocess.Popen(
1224
+ cmd,
1225
+ stdin=subprocess.PIPE,
1226
+ )
1227
+
1228
+ proc.communicate(input=token.encode())
1229
+
1230
+ return True
1231
+
1232
+
1233
+ def _pull_image(image):
1234
+ """Invokes the docker pull command for the given image.
1235
+
1236
+ Args:
1237
+ image:
1238
+ """
1239
+ pull_image_command = ("docker pull %s" % image).strip()
1240
+ logger.info("docker command: %s", pull_image_command)
1241
+
1242
+ subprocess.check_output(pull_image_command.split())
1243
+ logger.info("image pulled: %s", image)