Skip to content

Commit 13eda8f

Browse files
fix code
1 parent 58ca533 commit 13eda8f

File tree

3 files changed

+36
-33
lines changed

3 files changed

+36
-33
lines changed

services/dask-sidecar/src/simcore_service_dask_sidecar/computational_sidecar/models.py

Lines changed: 14 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@
33
from models_library.basic_regex import SIMPLE_VERSION_RE
44
from models_library.services import ServiceMetaDataPublished
55
from packaging import version
6-
from pydantic import BaseModel, ByteSize, Extra, Field, validator
6+
from pydantic import BaseModel, ByteSize, ConfigDict, Field, ValidationInfo, field_validator
77

88
LEGACY_INTEGRATION_VERSION = version.Version("0")
99
PROGRESS_REGEXP: re.Pattern[str] = re.compile(
@@ -36,23 +36,24 @@ class ContainerHostConfig(BaseModel):
3636
default=None,
3737
alias="MemorySwap",
3838
description="Total memory limit (memory + swap). Set as -1 to enable unlimited swap.",
39+
validate_default=True,
3940
)
4041
nano_cpus: int = Field(
4142
..., alias="NanoCPUs", description="CPU quota in units of 10-9 CPUs"
4243
)
4344

44-
@validator("memory_swap", pre=True, always=True)
45+
@field_validator("memory_swap", mode="before")
4546
@classmethod
46-
def ensure_no_memory_swap_means_no_swap(cls, v, values):
47+
def ensure_no_memory_swap_means_no_swap(cls, v, info: ValidationInfo):
4748
if v is None:
4849
# if not set it will be the same value as memory to ensure swap is disabled
49-
return values["memory"]
50+
return info.data["memory"]
5051
return v
5152

52-
@validator("memory_swap")
53+
@field_validator("memory_swap")
5354
@classmethod
54-
def ensure_memory_swap_cannot_be_unlimited_nor_smaller_than_memory(cls, v, values):
55-
if v < values["memory"]:
55+
def ensure_memory_swap_cannot_be_unlimited_nor_smaller_than_memory(cls, v, info: ValidationInfo):
56+
if v < info.data["memory"]:
5657
msg = "Memory swap cannot be set to a smaller value than memory"
5758
raise ValueError(msg)
5859
return v
@@ -71,26 +72,24 @@ class ImageLabels(BaseModel):
7172
default=str(LEGACY_INTEGRATION_VERSION),
7273
alias="integration-version",
7374
description="integration version number",
74-
regex=SIMPLE_VERSION_RE,
75+
pattern=SIMPLE_VERSION_RE,
7576
examples=["1.0.0"],
7677
)
7778
progress_regexp: str = Field(
7879
default=PROGRESS_REGEXP.pattern,
7980
alias="progress_regexp",
8081
description="regexp pattern for detecting computational service's progress",
8182
)
83+
model_config = ConfigDict(extra="ignore")
8284

83-
class Config:
84-
extra = Extra.ignore
85-
86-
@validator("integration_version", pre=True)
85+
@field_validator("integration_version", mode="before")
8786
@classmethod
8887
def default_integration_version(cls, v):
8988
if v is None:
9089
return ImageLabels().integration_version
9190
return v
9291

93-
@validator("progress_regexp", pre=True)
92+
@field_validator("progress_regexp", mode="before")
9493
@classmethod
9594
def default_progress_regexp(cls, v):
9695
if v is None:
@@ -104,6 +103,6 @@ def get_progress_regexp(self) -> re.Pattern[str]:
104103
return re.compile(self.progress_regexp)
105104

106105

107-
assert set(ImageLabels.__fields__).issubset(
108-
ServiceMetaDataPublished.__fields__
106+
assert set(ImageLabels.model_fields).issubset(
107+
ServiceMetaDataPublished.model_fields
109108
), "ImageLabels must be compatible with ServiceDockerData"

services/dask-sidecar/src/simcore_service_dask_sidecar/settings.py

Lines changed: 8 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@
22
from typing import Any
33

44
from models_library.basic_types import LogLevel
5-
from pydantic import Field, validator
5+
from pydantic import AliasChoices, Field, field_validator
66
from settings_library.base import BaseCustomSettings
77
from settings_library.utils_logging import MixinLoggingSettings
88

@@ -14,7 +14,9 @@ class Settings(BaseCustomSettings, MixinLoggingSettings):
1414
SC_BOOT_MODE: str | None = None
1515
LOG_LEVEL: LogLevel = Field(
1616
LogLevel.INFO.value,
17-
env=["DASK_SIDECAR_LOGLEVEL", "SIDECAR_LOGLEVEL", "LOG_LEVEL", "LOGLEVEL"],
17+
validation_alias=AliasChoices(
18+
"DASK_SIDECAR_LOGLEVEL", "SIDECAR_LOGLEVEL", "LOG_LEVEL", "LOGLEVEL"
19+
),
1820
)
1921

2022
# sidecar config ---
@@ -37,7 +39,9 @@ class Settings(BaseCustomSettings, MixinLoggingSettings):
3739

3840
DASK_LOG_FORMAT_LOCAL_DEV_ENABLED: bool = Field(
3941
default=False,
40-
env=["DASK_LOG_FORMAT_LOCAL_DEV_ENABLED", "LOG_FORMAT_LOCAL_DEV_ENABLED"],
42+
validation_alias=AliasChoices(
43+
"DASK_LOG_FORMAT_LOCAL_DEV_ENABLED", "LOG_FORMAT_LOCAL_DEV_ENABLED"
44+
),
4145
description="Enables local development log format. WARNING: make sure it is disabled if you want to have structured logs!",
4246
)
4347

@@ -50,7 +54,7 @@ def as_worker(self) -> bool:
5054
assert self.DASK_SCHEDULER_HOST is not None # nosec
5155
return as_worker
5256

53-
@validator("LOG_LEVEL", pre=True)
57+
@field_validator("LOG_LEVEL", mode="before")
5458
@classmethod
5559
def _validate_loglevel(cls, value: Any) -> str:
5660
return cls.validate_log_level(f"{value}")

services/dask-sidecar/tests/unit/test_tasks.py

Lines changed: 14 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -41,7 +41,7 @@
4141
from models_library.services import ServiceMetaDataPublished
4242
from models_library.services_resources import BootMode
4343
from packaging import version
44-
from pydantic import AnyUrl, SecretStr, parse_obj_as
44+
from pydantic import AnyUrl, SecretStr, TypeAdapter
4545
from pytest_mock.plugin import MockerFixture
4646
from pytest_simcore.helpers.typing_env import EnvVarsDict
4747
from settings_library.s3 import S3Settings
@@ -178,7 +178,7 @@ def integration_version(request: pytest.FixtureRequest) -> version.Version:
178178

179179
@pytest.fixture
180180
def additional_envs(faker: Faker) -> dict[EnvVarKey, str]:
181-
return parse_obj_as(dict[EnvVarKey, str], faker.pydict(allowed_types=(str,)))
181+
return TypeAdapter(dict[EnvVarKey, str]).validate_python(faker.pydict(allowed_types=(str,)))
182182

183183

184184
@pytest.fixture
@@ -198,7 +198,7 @@ def sleeper_task(
198198
list_of_files = [file_on_s3_server() for _ in range(NUM_FILES)]
199199

200200
# defines the inputs of the task
201-
input_data = TaskInputData.parse_obj(
201+
input_data = TaskInputData.model_validate(
202202
{
203203
"input_1": 23,
204204
"input_23": "a string input",
@@ -276,7 +276,7 @@ def sleeper_task(
276276
"pytest_bool": False,
277277
}
278278
output_file_url = s3_remote_file_url(file_path="output_file")
279-
expected_output_keys = TaskOutputDataSchema.parse_obj(
279+
expected_output_keys = TaskOutputDataSchema.model_validate(
280280
{
281281
**(
282282
{k: {"required": True} for k in jsonable_outputs}
@@ -295,7 +295,7 @@ def sleeper_task(
295295
),
296296
}
297297
)
298-
expected_output_data = TaskOutputData.parse_obj(
298+
expected_output_data = TaskOutputData.model_validate(
299299
{
300300
**(
301301
jsonable_outputs
@@ -395,10 +395,10 @@ def _creator(command: list[str] | None = None) -> ServiceExampleParam:
395395
service_version="latest",
396396
command=command
397397
or ["/bin/bash", "-c", "echo 'hello I'm an empty ubuntu task!"],
398-
input_data=TaskInputData.parse_obj({}),
399-
output_data_keys=TaskOutputDataSchema.parse_obj({}),
398+
input_data=TaskInputData.model_validate({}),
399+
output_data_keys=TaskOutputDataSchema.model_validate({}),
400400
log_file_url=s3_remote_file_url(file_path="log.dat"),
401-
expected_output_data=TaskOutputData.parse_obj({}),
401+
expected_output_data=TaskOutputData.model_validate({}),
402402
expected_logs=[],
403403
integration_version=integration_version,
404404
task_envs={},
@@ -437,8 +437,8 @@ def caplog_info_level(
437437
def mocked_get_image_labels(
438438
integration_version: version.Version, mocker: MockerFixture
439439
) -> mock.Mock:
440-
labels: ImageLabels = parse_obj_as(
441-
ImageLabels, ServiceMetaDataPublished.Config.schema_extra["examples"][0]
440+
labels: ImageLabels = TypeAdapter(ImageLabels).validate_python(
441+
ServiceMetaDataPublished.model_config["json_schema_extra"]["examples"][0],
442442
)
443443
labels.integration_version = f"{integration_version}"
444444
return mocker.patch(
@@ -580,15 +580,15 @@ async def test_run_computational_sidecar_dask(
580580

581581
# check that the task produces expected logs
582582
worker_progresses = [
583-
TaskProgressEvent.parse_raw(msg).progress for msg in progress_sub.buffer
583+
TaskProgressEvent.model_validate_json(msg).progress for msg in progress_sub.buffer
584584
]
585585
# check ordering
586586
assert worker_progresses == sorted(
587587
set(worker_progresses)
588588
), "ordering of progress values incorrectly sorted!"
589589
assert worker_progresses[0] == 0, "missing/incorrect initial progress value"
590590
assert worker_progresses[-1] == 1, "missing/incorrect final progress value"
591-
worker_logs = [TaskLogEvent.parse_raw(msg).log for msg in log_sub.buffer]
591+
worker_logs = [TaskLogEvent.model_validate_json(msg).log for msg in log_sub.buffer]
592592
print(f"<-- we got {len(worker_logs)} lines of logs")
593593

594594
for log in sleeper_task.expected_logs:
@@ -649,7 +649,7 @@ async def test_run_computational_sidecar_dask_does_not_lose_messages_with_pubsub
649649

650650
# check that the task produces expected logs
651651
worker_progresses = [
652-
TaskProgressEvent.parse_raw(msg).progress for msg in progress_sub.buffer
652+
TaskProgressEvent.model_validate_json(msg).progress for msg in progress_sub.buffer
653653
]
654654
# check length
655655
assert len(worker_progresses) == len(
@@ -659,7 +659,7 @@ async def test_run_computational_sidecar_dask_does_not_lose_messages_with_pubsub
659659
assert worker_progresses[0] == 0, "missing/incorrect initial progress value"
660660
assert worker_progresses[-1] == 1, "missing/incorrect final progress value"
661661

662-
worker_logs = [TaskLogEvent.parse_raw(msg).log for msg in log_sub.buffer]
662+
worker_logs = [TaskLogEvent.model_validate_json(msg).log for msg in log_sub.buffer]
663663
# check all the awaited logs are in there
664664
filtered_worker_logs = filter(lambda log: "This is iteration" in log, worker_logs)
665665
assert len(list(filtered_worker_logs)) == NUMBER_OF_LOGS

0 commit comments

Comments
 (0)