Skip to content

Commit 9cc0278

Browse files
[pre-commit.ci] pre-commit autoupdate (#450)
* [pre-commit.ci] pre-commit autoupdate updates: - [github.com/astral-sh/ruff-pre-commit: v0.15.1 → v0.15.2](astral-sh/ruff-pre-commit@v0.15.1...v0.15.2) * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * fix: resolve ruff v0.15.2 linting errors --------- Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com> Co-authored-by: Meni Yakove <myakove@gmail.com>
1 parent c94f5e9 commit 9cc0278

7 files changed

Lines changed: 53 additions & 57 deletions

File tree

.pre-commit-config.yaml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -42,7 +42,7 @@ repos:
4242
- id: detect-secrets
4343

4444
- repo: https://github.com/astral-sh/ruff-pre-commit
45-
rev: v0.15.1
45+
rev: v0.15.2
4646
hooks:
4747
- id: ruff
4848
args: [--fix]

ocp_utilities/cluster_versions.py

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,14 @@
11
from __future__ import annotations
2+
23
import functools
34
import re
4-
from typing import Dict, List
55

66
import requests
77
from bs4 import BeautifulSoup, ResultSet
88
from kubernetes.dynamic import DynamicClient
99
from ocp_resources.cluster_version import ClusterVersion
10-
from simple_logger.logger import get_logger
1110
from semver import Version
11+
from simple_logger.logger import get_logger
1212

1313
from ocp_utilities.exceptions import ClusterVersionNotFoundError
1414

@@ -25,7 +25,7 @@ def parse_openshift_release_url() -> ResultSet:
2525

2626

2727
@functools.cache
28-
def get_accepted_cluster_versions() -> Dict[str, Dict[str, List[str]]]:
28+
def get_accepted_cluster_versions() -> dict[str, dict[str, list[str]]]:
2929
"""
3030
Get all accepted cluster versions from https://openshift-release.apps.ci.l2s4.p1.openshiftapps.com
3131
@@ -48,7 +48,7 @@ def get_accepted_cluster_versions() -> Dict[str, Dict[str, List[str]]]:
4848
'rc': {'4.15': ['4.15.0-0.rc-2022-05-25-113430']},
4949
'fc': {'4.15': ['4.15.0-0.fc-2022-05-25-113430']}}
5050
"""
51-
_accepted_version_dict: Dict[str, Dict[str, List[str]]] = {}
51+
_accepted_version_dict: dict[str, dict[str, list[str]]] = {}
5252
for tr in parse_openshift_release_url():
5353
version, status = [_tr for _tr in tr.text.splitlines() if _tr][:2]
5454
if status == "Accepted":

ocp_utilities/debugger.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -16,4 +16,4 @@ class WebDebugger(WebPdb):
1616
"""
1717

1818
def __init__(self) -> None:
19-
super().__init__(host="0.0.0.0", port=int(os.environ.get("PYTHON_REMOTE_DEBUG_PORT", 1212)))
19+
super().__init__(host="0.0.0.0", port=int(os.environ.get("PYTHON_REMOTE_DEBUG_PORT", "1212")))

ocp_utilities/infra.py

Lines changed: 12 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@
66
import os
77
import re
88
import shlex
9-
from typing import Any, Dict, List, Optional
9+
from typing import Any
1010

1111
import urllib3
1212
from deprecation import deprecated
@@ -44,7 +44,7 @@ def get_client(**kwargs: Any) -> DynamicClient:
4444
return get_dynamic_client(**kwargs)
4545

4646

47-
def assert_nodes_ready(nodes: List[Node]) -> None:
47+
def assert_nodes_ready(nodes: list[Node]) -> None:
4848
"""
4949
Validates all nodes are in ready
5050
@@ -60,7 +60,7 @@ def assert_nodes_ready(nodes: List[Node]) -> None:
6060
raise NodeNotReadyError(f"Following nodes are not in ready state: {not_ready_nodes}")
6161

6262

63-
def assert_nodes_schedulable(nodes: List[Node]) -> None:
63+
def assert_nodes_schedulable(nodes: list[Node]) -> None:
6464
"""
6565
Validates all nodes are in schedulable state
6666
@@ -76,7 +76,7 @@ def assert_nodes_schedulable(nodes: List[Node]) -> None:
7676
raise NodeUnschedulableError(f"Following nodes are in unscheduled state: {unschedulable_nodes}")
7777

7878

79-
def assert_pods_failed_or_pending(pods: List[Pod]) -> None:
79+
def assert_pods_failed_or_pending(pods: list[Pod]) -> None:
8080
"""
8181
Validates all pods are not in failed nor pending phase
8282
@@ -103,8 +103,8 @@ def assert_pods_failed_or_pending(pods: List[Pod]) -> None:
103103

104104

105105
def assert_nodes_in_healthy_condition(
106-
nodes: List[Node],
107-
healthy_node_condition_type: Optional[Dict[str, str]],
106+
nodes: list[Node],
107+
healthy_node_condition_type: dict[str, str] | None,
108108
) -> None:
109109
"""
110110
Validates nodes are in a healthy condition.
@@ -169,7 +169,7 @@ class DynamicClassCreator:
169169
"""
170170

171171
def __init__(self) -> None:
172-
self.created_classes: Dict[Any, Any] = {}
172+
self.created_classes: dict[Any, Any] = {}
173173

174174
def __call__(self, base_class: Any) -> Any: # TODO: return `BaseResource` class
175175
if base_class in self.created_classes:
@@ -206,7 +206,7 @@ def clean_up(self) -> bool:
206206
resource_object=self,
207207
collect_pod_logs=data_collector_dict.get("collect_pod_logs", False),
208208
)
209-
except Exception as exception_:
209+
except Exception as exception_: # noqa: BLE001
210210
LOGGER.warning(
211211
f"[Data collector] failed to collect data for {self.kind} {self.name}\nexception: {exception_}"
212212
)
@@ -309,13 +309,13 @@ def create_icsp_from_file(icsp_file_path: str) -> ImageContentSourcePolicy:
309309
return icsp
310310

311311

312-
def create_icsp(icsp_name: str, repository_digest_mirrors: List[Dict[str, Any]]) -> ImageContentSourcePolicy:
312+
def create_icsp(icsp_name: str, repository_digest_mirrors: list[dict[str, Any]]) -> ImageContentSourcePolicy:
313313
icsp = ImageContentSourcePolicy(name=icsp_name, repository_digest_mirrors=repository_digest_mirrors)
314314
icsp.deploy()
315315
return icsp
316316

317317

318-
def dict_base64_encode(_dict: Dict[Any, Any]) -> str:
318+
def dict_base64_encode(_dict: dict[Any, Any]) -> str:
319319
"""
320320
Encoding dict in base64
321321
@@ -329,7 +329,7 @@ def dict_base64_encode(_dict: Dict[Any, Any]) -> str:
329329

330330

331331
def create_update_secret(
332-
secret_data_dict: Dict[str, Dict[str, Dict[str, str]]],
332+
secret_data_dict: dict[str, dict[str, dict[str, str]]],
333333
name: str,
334334
namespace: str,
335335
admin_client: DynamicClient = None,
@@ -374,7 +374,7 @@ def create_update_secret(
374374
return secret.deploy()
375375

376376

377-
def get_pods_by_name_prefix(client: DynamicClient, pod_prefix: str, namespace: str) -> List[Pod]:
377+
def get_pods_by_name_prefix(client: DynamicClient, pod_prefix: str, namespace: str) -> list[Pod]:
378378
"""
379379
Args:
380380
client (DynamicClient): OCP Client to use.

ocp_utilities/monitoring.py

Lines changed: 21 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -1,25 +1,24 @@
11
from __future__ import annotations
2+
23
import json
34
import re
45
from json import JSONDecodeError
5-
from typing import Any, Dict, List
6+
from typing import Any
67

78
import requests
89
from kubernetes.dynamic import DynamicClient
10+
from ocp_resources.resource import get_client
911
from ocp_resources.route import Route
10-
from timeout_sampler import TimeoutExpiredError, TimeoutSampler
1112
from simple_logger.logger import get_logger
12-
13-
from ocp_resources.resource import get_client
14-
13+
from timeout_sampler import TimeoutExpiredError, TimeoutSampler
1514

1615
TIMEOUT_2MIN = 2 * 60
1716
TIMEOUT_10MIN = 10 * 60
1817

1918
LOGGER = get_logger(name=__name__)
2019

2120

22-
class Prometheus(object):
21+
class Prometheus:
2322
"""
2423
For accessing Prometheus cluster metrics
2524
@@ -69,7 +68,7 @@ def _get_route(self) -> str:
6968
route = Route(namespace=self.namespace, name=self.resource_name, client=self.client).instance.spec.host
7069
return f"https://{route}"
7170

72-
def _get_response(self, query: str) -> Dict[str, Any]:
71+
def _get_response(self, query: str) -> dict[str, Any]:
7372
response = requests.get(f"{self.api_url}{query}", headers=self.headers, verify=self.verify_ssl)
7473

7574
try:
@@ -81,7 +80,7 @@ def _get_response(self, query: str) -> Dict[str, Any]:
8180
)
8281
raise
8382

84-
def query(self, query: str) -> Dict[str, Any]:
83+
def query(self, query: str) -> dict[str, Any]:
8584
"""
8685
get the prometheus query result
8786
@@ -93,7 +92,7 @@ def query(self, query: str) -> Dict[str, Any]:
9392
"""
9493
return self._get_response(query=f"{self.api_v1}/query?query={query}")
9594

96-
def get_all_alerts_by_alert_name(self, alert_name: str) -> List[Dict[str, Any]]:
95+
def get_all_alerts_by_alert_name(self, alert_name: str) -> list[dict[str, Any]]:
9796
"""
9897
Get alert by alert name if it's an active alert
9998
@@ -107,13 +106,9 @@ def get_all_alerts_by_alert_name(self, alert_name: str) -> List[Dict[str, Any]]:
107106
list: list containing alert metrics
108107
"""
109108
alerts = self.alerts()
110-
alert_list = []
111-
for alert in alerts["data"]["alerts"]:
112-
if alert["labels"]["alertname"] == alert_name:
113-
alert_list.append(alert)
114-
return alert_list
109+
return [alert for alert in alerts["data"]["alerts"] if alert["labels"]["alertname"] == alert_name]
115110

116-
def get_firing_alerts(self, alert_name: str) -> List[Dict[str, Any]]:
111+
def get_firing_alerts(self, alert_name: str) -> list[dict[str, Any]]:
117112
"""
118113
get all the firing alerts from list of active alerts
119114
"""
@@ -145,14 +140,17 @@ def get_scrape_interval(self) -> int:
145140
response = self._get_response(query=f"{self.api_v1}/targets")
146141
result = response.get("data", {}).get("activeTargets", [])
147142
for item in result:
148-
if item and item.get("labels", {}).get("job") == "prometheus-k8s":
149-
if scrape_interval := item.get("scrapeInterval"):
150-
if scrape_interval_match := re.match(r"\d+", scrape_interval):
151-
return int(scrape_interval_match.group())
143+
if (
144+
item
145+
and item.get("labels", {}).get("job") == "prometheus-k8s"
146+
and (scrape_interval := item.get("scrapeInterval"))
147+
and (scrape_interval_match := re.match(r"\d+", scrape_interval))
148+
):
149+
return int(scrape_interval_match.group())
152150

153151
return 30
154152

155-
def query_sampler(self, query: str, timeout: int = TIMEOUT_2MIN) -> List[Any]:
153+
def query_sampler(self, query: str, timeout: int = TIMEOUT_2MIN) -> list[Any]:
156154
"""
157155
Sample output for query function
158156
@@ -183,13 +181,13 @@ def query_sampler(self, query: str, timeout: int = TIMEOUT_2MIN) -> List[Any]:
183181

184182
return []
185183

186-
def alerts(self) -> Dict[str, Any]:
184+
def alerts(self) -> dict[str, Any]:
187185
"""
188186
get all the active alerts
189187
"""
190188
return self._get_response(query=f"{self.api_v1}/alerts")
191189

192-
def get_alerts_by_state(self, alert_name: str, state: str = "firing") -> List[Dict[str, Any]]:
190+
def get_alerts_by_state(self, alert_name: str, state: str = "firing") -> list[dict[str, Any]]:
193191
"""
194192
get all the alerts from list of active alerts according the state
195193
"""
@@ -198,7 +196,7 @@ def get_alerts_by_state(self, alert_name: str, state: str = "firing") -> List[Di
198196

199197
def wait_for_alert_by_state_sampler(
200198
self, alert_name: str, timeout: int = TIMEOUT_10MIN, state: str = "firing"
201-
) -> List[Dict[str, Any]]:
199+
) -> list[dict[str, Any]]:
202200
"""
203201
Sample output for an alert if found in the state provided in the args.
204202

ocp_utilities/must_gather.py

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,11 @@
1+
import os
12
import shlex
23
import shutil
34
from pathlib import Path
4-
import os
55

66
from pyhelper_utils.shell import run_command
77
from simple_logger.logger import get_logger
88

9-
109
LOGGER = get_logger(name=__name__)
1110

1211

@@ -89,7 +88,7 @@ def collect_must_gather(
8988
)
9089
LOGGER.success("must-gather collected")
9190

92-
except Exception as ex:
91+
except Exception as ex: # noqa: BLE001
9392
LOGGER.error(
9493
f"Failed to run must-gather \n{ex}",
9594
)

ocp_utilities/operators.py

Lines changed: 12 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,7 @@
1+
from __future__ import annotations
2+
13
from pprint import pformat
2-
from typing import Any, Dict, List, Optional
4+
from typing import Any
35

46
from kubernetes.dynamic import DynamicClient
57
from kubernetes.dynamic.exceptions import ResourceNotFoundError
@@ -12,13 +14,12 @@
1214
from ocp_resources.operator_group import OperatorGroup
1315
from ocp_resources.resource import ResourceEditor
1416
from ocp_resources.subscription import Subscription
15-
from timeout_sampler import TimeoutExpiredError, TimeoutSampler, TimeoutWatch
1617
from ocp_resources.validating_webhook_config import ValidatingWebhookConfiguration
1718
from simple_logger.logger import get_logger
18-
from ocp_utilities.must_gather import collect_must_gather
19+
from timeout_sampler import TimeoutExpiredError, TimeoutSampler, TimeoutWatch
1920

2021
from ocp_utilities.infra import cluster_resource, create_icsp, create_update_secret
21-
22+
from ocp_utilities.must_gather import collect_must_gather
2223

2324
LOGGER = get_logger(name=__name__)
2425
TIMEOUT_5MIN = 5 * 60
@@ -148,7 +149,7 @@ def get_csv_by_name(admin_client: DynamicClient, csv_name: str, namespace: str)
148149

149150
def install_operator(
150151
admin_client: DynamicClient,
151-
target_namespaces: Optional[List[str]],
152+
target_namespaces: list[str] | None,
152153
name: str,
153154
channel: str,
154155
source: str = "",
@@ -190,9 +191,8 @@ def install_operator(
190191
catalog_source = None
191192
operator_market_namespace = "openshift-marketplace"
192193

193-
if must_gather_output_dir:
194-
if not cluster_name:
195-
raise ValueError("'cluster_name' param is required for running must-gather of cluster")
194+
if must_gather_output_dir and not cluster_name:
195+
raise ValueError("'cluster_name' param is required for running must-gather of cluster")
196196
try:
197197
if iib_index_image:
198198
if not brew_token:
@@ -345,7 +345,7 @@ def create_catalog_source_for_iib_install(
345345

346346
def _manipulate_validating_webhook_configuration(
347347
_validating_webhook_configuration: ValidatingWebhookConfiguration,
348-
) -> Dict[str, Any]:
348+
) -> dict[str, Any]:
349349
_resource_name = "imagecontentsourcepolicies"
350350
_validating_webhook_configuration_dict = _validating_webhook_configuration.instance.to_dict()
351351
for webhook in _validating_webhook_configuration_dict["webhooks"]:
@@ -358,7 +358,7 @@ def _manipulate_validating_webhook_configuration(
358358

359359
return _validating_webhook_configuration_dict
360360

361-
def _icsp(_repository_digest_mirrors: List[Dict[str, Any]]) -> None:
361+
def _icsp(_repository_digest_mirrors: list[dict[str, Any]]) -> None:
362362
if icsp.exists:
363363
ResourceEditor(
364364
patches={icsp: {"spec:": {"repository_digest_mirrors": _repository_digest_mirrors}}}
@@ -375,7 +375,7 @@ def _icsp(_repository_digest_mirrors: List[Dict[str, Any]]) -> None:
375375
_iib_index_image = iib_index_image.replace(source_iib_registry, brew_registry)
376376
icsp = ImageContentSourcePolicy(name="brew-registry")
377377
validating_webhook_configuration = ValidatingWebhookConfiguration(name="sre-imagecontentpolicies-validation")
378-
repository_digest_mirrors: List[Dict[str, Any]] = [
378+
repository_digest_mirrors: list[dict[str, Any]] = [
379379
{
380380
"source": f"{source_iib_registry}/{brew_image_repo}",
381381
"mirrors": [f"{brew_registry}/{brew_image_repo}"],
@@ -412,13 +412,12 @@ def _icsp(_repository_digest_mirrors: List[Dict[str, Any]]) -> None:
412412
admin_client=admin_client,
413413
)
414414

415-
iib_catalog_source = create_catalog_source_from_image(
415+
return create_catalog_source_from_image(
416416
admin_client=admin_client,
417417
name=name,
418418
namespace=operator_market_namespace,
419419
image=_iib_index_image,
420420
)
421-
return iib_catalog_source
422421

423422

424423
def create_catalog_source_from_image(

0 commit comments

Comments
 (0)