Skip to content

Commit 3808cac

Browse files
Replace pkg_resources with importlib and packaging
https://setuptools.pypa.io/en/latest/pkg_resources.html: > Use of pkg_resources is deprecated in favor of importlib.resources, importlib.metadata and their backports (importlib_resources, importlib_metadata). Some useful APIs are also provided by packaging (e.g. requirements and version parsing). Users should refrain from new usage of pkg_resources and should work to port to importlib-based solutions.
1 parent bf22eba commit 3808cac

File tree

13 files changed

+36
-35
lines changed

13 files changed

+36
-35
lines changed

cli/requirements.txt

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -25,3 +25,4 @@ marshmallow~=3.10
2525
PyYAML>=5.3.1,!=5.4
2626
tabulate>=0.8.8,<=0.8.10
2727
werkzeug~=2.0
28+
packaging~=25.0

cli/setup.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,7 @@ def readme():
2929
"PyYAML>=5.3.1,!=5.4",
3030
"jinja2~=3.0",
3131
"marshmallow~=3.10",
32+
"packaging~=25.0",
3233
"aws-cdk.core~=" + CDK_VERSION,
3334
"aws-cdk.aws-batch~=" + CDK_VERSION,
3435
"aws_cdk.aws-cloudwatch~=" + CDK_VERSION,

cli/src/pcluster/api/controllers/common.py

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,7 @@
1717
from typing import List, Optional, Set, Union
1818

1919
import boto3
20-
from pkg_resources import packaging
20+
from packaging import version as packaging_version
2121

2222
from pcluster.api.errors import (
2323
BadRequestException,
@@ -110,12 +110,12 @@ def check_cluster_version(cluster: Cluster, exact_match: bool = False) -> bool:
110110
return False
111111

112112
if exact_match:
113-
return packaging.version.parse(cluster.stack.version) == packaging.version.parse(get_installed_version())
113+
return packaging_version.parse(cluster.stack.version) == packaging_version.parse(get_installed_version())
114114
else:
115115
return (
116-
packaging.version.parse(packaging.version.parse(get_installed_version()).base_version)
117-
>= packaging.version.parse(cluster.stack.version)
118-
>= packaging.version.parse("3.0.0a0")
116+
packaging_version.parse(packaging_version.parse(get_installed_version()).base_version)
117+
>= packaging_version.parse(cluster.stack.version)
118+
>= packaging_version.parse("3.0.0a0")
119119
)
120120

121121

cli/src/pcluster/api/util.py

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,7 @@
1717
import subprocess # nosec B404
1818

1919
import six
20-
from pkg_resources import packaging
20+
from packaging import version as packaging_version
2121

2222
from pcluster.api import typing_utils
2323
from pcluster.constants import NODEJS_INCOMPATIBLE_VERSION_RANGE, NODEJS_MIN_VERSION
@@ -221,19 +221,19 @@ def _assert_node_version():
221221
LOGGER.critical(message)
222222
raise Exception(message)
223223

224-
node_version = packaging.version.parse(node_version_string)
224+
node_version = packaging_version.parse(node_version_string)
225225

226-
if node_version < packaging.version.parse(NODEJS_MIN_VERSION):
226+
if node_version < packaging_version.parse(NODEJS_MIN_VERSION):
227227
message = (
228228
f"AWS CDK library used by ParallelCluster requires Node.js version >= {NODEJS_MIN_VERSION},"
229229
" see installation instructions here: https://docs.aws.amazon.com/parallelcluster/latest/ug/install-v3.html"
230230
)
231231
LOGGER.critical(message)
232232
raise Exception(message)
233233
if (
234-
packaging.version.parse(NODEJS_INCOMPATIBLE_VERSION_RANGE[0])
234+
packaging_version.parse(NODEJS_INCOMPATIBLE_VERSION_RANGE[0])
235235
<= node_version
236-
<= packaging.version.parse(NODEJS_INCOMPATIBLE_VERSION_RANGE[1])
236+
<= packaging_version.parse(NODEJS_INCOMPATIBLE_VERSION_RANGE[1])
237237
):
238238
message = (
239239
f"AWS CDK library used by ParallelCluster requires Node.js to not be in the range"

cli/src/pcluster/config/cluster_config.py

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -16,10 +16,9 @@
1616
from abc import abstractmethod
1717
from collections import defaultdict
1818
from enum import Enum
19+
from importlib.resources import files # nosemgrep: python.lang.compatibility.python37.python37-compatibility-importlib2
1920
from typing import Dict, List, Union
2021

21-
import pkg_resources
22-
2322
from pcluster.aws.aws_api import AWSApi
2423
from pcluster.aws.aws_resources import InstanceTypeInfo
2524
from pcluster.aws.common import AWSClientError, get_region
@@ -2192,7 +2191,7 @@ def _register_validators(self, context: ValidatorContext = None):
21922191
@property
21932192
def scheduler_resources(self):
21942193
"""Return scheduler specific resources."""
2195-
return pkg_resources.resource_filename(__name__, "../resources/batch")
2194+
return str(files(__package__).parent / "resources" / "batch")
21962195

21972196

21982197
class _BaseSlurmComputeResource(BaseComputeResource):

cli/src/pcluster/models/cluster.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -20,9 +20,9 @@
2020
from copy import deepcopy
2121
from datetime import datetime
2222
from enum import Enum
23+
from importlib.resources import files # nosemgrep: python.lang.compatibility.python37.python37-compatibility-importlib2
2324
from typing import List, Optional, Set, Tuple
2425

25-
import pkg_resources
2626
from marshmallow import ValidationError
2727

2828
from pcluster.aws.aws_api import AWSApi
@@ -586,7 +586,7 @@ def _upload_artifacts(self):
586586
LOGGER.info("Uploading cluster artifacts to S3...")
587587
self._check_bucket_existence()
588588
try:
589-
resources = pkg_resources.resource_filename(__name__, "../resources/custom_resources")
589+
resources = str(files(__package__).parent / "resources" / "custom_resources")
590590
self.bucket.upload_resources(
591591
resource_dir=resources, custom_artifacts_name=PCLUSTER_S3_ARTIFACTS_DICT.get("custom_artifacts_name")
592592
)

cli/src/pcluster/models/compute_fleet_status_manager.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,7 @@
1515
from enum import Enum
1616

1717
from boto3.dynamodb.conditions import Attr
18-
from pkg_resources import packaging
18+
from packaging import version as packaging_version
1919

2020
from pcluster.aws.aws_api import AWSApi
2121
from pcluster.aws.common import AWSClientError
@@ -146,7 +146,7 @@ def get_status_with_last_updated_time(
146146
@staticmethod
147147
def get_manager(cluster_name, version):
148148
"""Return compute fleet status manager based on version and plugin."""
149-
if packaging.version.parse(version) < packaging.version.parse("3.2.0a0"):
149+
if packaging_version.parse(version) < packaging_version.parse("3.2.0a0"):
150150
return PlainTextComputeFleetStatusManager(cluster_name)
151151
else:
152152
return JsonComputeFleetStatusManager(cluster_name)

cli/src/pcluster/models/imagebuilder.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -19,9 +19,9 @@
1919
import re
2020
import tempfile
2121
from datetime import datetime
22+
from importlib.resources import files # nosemgrep: python.lang.compatibility.python37.python37-compatibility-importlib2
2223
from typing import Set
2324

24-
import pkg_resources
2525
from marshmallow.exceptions import ValidationError
2626

2727
from pcluster.aws.aws_api import AWSApi
@@ -532,7 +532,7 @@ def _upload_artifacts(self):
532532
# upload cfn template
533533
self.bucket.upload_cfn_template(self.template_body, self._s3_artifacts_dict.get("template_name"))
534534

535-
resources = pkg_resources.resource_filename(__name__, "../resources/custom_resources")
535+
resources = str(files(__package__).parent / "resources" / "custom_resources")
536536
self.bucket.upload_resources(
537537
resource_dir=resources, custom_artifacts_name=self._s3_artifacts_dict.get("custom_artifacts_name")
538538
)

cli/src/pcluster/templates/cdk_builder_utils.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -12,9 +12,9 @@
1212
# pylint: disable=too-many-lines
1313
import abc
1414
from hashlib import sha1, sha256
15+
from importlib.resources import files # nosemgrep: python.lang.compatibility.python37.python37-compatibility-importlib2
1516
from typing import List, Union
1617

17-
import pkg_resources
1818
from aws_cdk import aws_ec2 as ec2
1919
from aws_cdk import aws_iam as iam
2020
from aws_cdk import aws_lambda as awslambda
@@ -77,7 +77,7 @@ def create_hash_suffix(string_to_hash: str):
7777

7878
def get_user_data_content(user_data_path: str):
7979
"""Retrieve user data content."""
80-
user_data_file_path = pkg_resources.resource_filename(__name__, user_data_path)
80+
user_data_file_path = str(files(__package__) / user_data_path)
8181
with open(user_data_file_path, "r", encoding="utf-8") as user_data_file:
8282
user_data_content = user_data_file.read()
8383
return user_data_content

cli/src/pcluster/utils.py

Lines changed: 8 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,8 @@
2323
import urllib
2424
import zipfile
2525
from concurrent.futures import ThreadPoolExecutor
26+
from importlib.metadata import version
27+
from importlib.resources import files # nosemgrep: python.lang.compatibility.python37.python37-compatibility-importlib2
2628
from io import BytesIO
2729
from shlex import quote
2830
from typing import Callable, NoReturn
@@ -31,8 +33,8 @@
3133

3234
import boto3
3335
import dateutil.parser
34-
import pkg_resources
3536
import yaml
37+
from packaging.version import parse
3638
from yaml import SafeLoader
3739
from yaml.constructor import ConstructorError
3840
from yaml.resolver import BaseResolver
@@ -149,8 +151,8 @@ def zip_dir(path):
149151
"""
150152
file_out = BytesIO()
151153
with zipfile.ZipFile(file_out, "w", zipfile.ZIP_DEFLATED) as ziph:
152-
for root, _, files in os.walk(path):
153-
for file in files:
154+
for root, _, files_list in os.walk(path):
155+
for file in files_list:
154156
_add_file_to_zip(
155157
ziph,
156158
os.path.join(root, file),
@@ -305,8 +307,8 @@ def get_templates_bucket_path():
305307

306308
def get_installed_version(base_version_only: bool = False):
307309
"""Get the version of the installed aws-parallelcluster package."""
308-
pkg_distribution = pkg_resources.get_distribution("aws-parallelcluster")
309-
return pkg_distribution.version if not base_version_only else pkg_distribution.parsed_version.base_version
310+
pkg_version = version("aws-parallelcluster")
311+
return pkg_version if not base_version_only else parse(pkg_version).base_version
310312

311313

312314
def warn(message):
@@ -576,7 +578,7 @@ def retrieve_supported_regions():
576578
retrieve_supported_regions.cache = f.read().decode("utf-8").split("\n")
577579
except URLError:
578580
# When the file is not found on the URL, use local file. This is useful when developing new versions.
579-
with open(pkg_resources.resource_filename(__name__, "/resources/supported-regions"), encoding="utf-8") as f:
581+
with open(str(files(__package__) / "resources" / "supported-regions"), encoding="utf-8") as f:
580582
retrieve_supported_regions.cache = f.read().split("\n")
581583
return retrieve_supported_regions.cache
582584

0 commit comments

Comments
 (0)