Skip to content

Commit 7ff8a4e

Browse files
authored
[PSM interop] Introduce isort/pylint to the GKE framework (grpc#29476)
* [PSM interop] Introduce isort/pylint to the GKE framework * Update the rpc_types * Update variable type annotation style in tests/*.py
1 parent 48553e7 commit 7ff8a4e

35 files changed

+350
-325
lines changed

bin/run_channelz.py

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -178,7 +178,6 @@ def main(argv):
178178

179179
# Resource names.
180180
resource_prefix: str = xds_flags.RESOURCE_PREFIX.value
181-
resource_suffix: str = xds_flags.RESOURCE_SUFFIX.value
182181

183182
# Server
184183
server_name = xds_flags.SERVER_NAME.value

bin/run_td_setup.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -67,7 +67,7 @@
6767
KubernetesServerRunner = server_app.KubernetesServerRunner
6868

6969

70-
def main(argv):
70+
def main(argv): # pylint: disable=too-many-locals,too-many-branches,too-many-statements
7171
if len(argv) > 1:
7272
raise app.UsageError('Too many command-line arguments.')
7373

framework/helpers/datetime.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,7 @@
1414
"""This contains common helpers for working with dates and time."""
1515
import datetime
1616
import re
17-
from typing import Pattern
17+
from typing import Optional, Pattern
1818

1919
RE_ZERO_OFFSET: Pattern[str] = re.compile(r'[+\-]00:?00$')
2020

@@ -29,7 +29,7 @@ def shorten_utc_zone(utc_datetime_str: str) -> str:
2929
return RE_ZERO_OFFSET.sub('Z', utc_datetime_str)
3030

3131

32-
def iso8601_utc_time(timedelta: datetime.timedelta = None) -> str:
32+
def iso8601_utc_time(timedelta: Optional[datetime.timedelta] = None) -> str:
3333
"""Return datetime relative to current in ISO-8601 format, UTC tz."""
3434
time: datetime.datetime = utc_now()
3535
if timedelta:

framework/helpers/retryers.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -70,7 +70,7 @@ def exponential_retryer_with_timeout(
7070
def constant_retryer(*,
7171
wait_fixed: timedelta,
7272
attempts: int = 0,
73-
timeout: timedelta = None,
73+
timeout: Optional[timedelta] = None,
7474
retry_on_exceptions: Optional[Sequence[Any]] = None,
7575
logger: Optional[logging.Logger] = None,
7676
log_level: Optional[int] = logging.DEBUG) -> Retrying:

framework/infrastructure/gcp/api.py

Lines changed: 7 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -149,8 +149,9 @@ def networkservices(self, version):
149149

150150
raise NotImplementedError(f'Network Services {version} not supported')
151151

152+
@staticmethod
152153
@functools.lru_cache(None)
153-
def secrets(self, version):
154+
def secrets(version: str):
154155
if version == 'v1':
155156
return secretmanager_v1.SecretManagerServiceClient()
156157

@@ -263,7 +264,7 @@ class OperationError(Error):
263264
"""
264265
api_name: str
265266
name: str
266-
metadata: str
267+
metadata: Any
267268
code_name: code_pb2.Code
268269
error: status_pb2.Status
269270

@@ -431,9 +432,10 @@ def _delete_resource(self, collection: discovery.Resource,
431432
return False
432433

433434
# TODO(sergiitk): Use ResponseError and TransportError
434-
def _execute(self,
435-
request: HttpRequest,
436-
timeout_sec=GcpProjectApiResource._WAIT_FOR_OPERATION_SEC):
435+
def _execute( # pylint: disable=arguments-differ
436+
self,
437+
request: HttpRequest,
438+
timeout_sec=GcpProjectApiResource._WAIT_FOR_OPERATION_SEC):
437439
operation = request.execute(num_retries=self._GCP_API_RETRIES)
438440
self._wait(operation, timeout_sec)
439441

framework/infrastructure/gcp/compute.py

Lines changed: 29 additions & 28 deletions
Original file line numberDiff line numberDiff line change
@@ -26,7 +26,7 @@
2626
logger = logging.getLogger(__name__)
2727

2828

29-
class ComputeV1(gcp.api.GcpProjectApiResource):
29+
class ComputeV1(gcp.api.GcpProjectApiResource): # pylint: disable=too-many-public-methods
3030
# TODO(sergiitk): move someplace better
3131
_WAIT_FOR_BACKEND_SEC = 60 * 10
3232
_WAIT_FOR_OPERATION_SEC = 60 * 10
@@ -58,7 +58,7 @@ def create_health_check(self,
5858
name: str,
5959
protocol: HealthCheckProtocol,
6060
*,
61-
port: Optional[int] = None) -> GcpResource:
61+
port: Optional[int] = None) -> 'GcpResource':
6262
if protocol is self.HealthCheckProtocol.TCP:
6363
health_check_field = 'tcpHealthCheck'
6464
elif protocol is self.HealthCheckProtocol.GRPC:
@@ -88,7 +88,7 @@ def delete_health_check(self, name):
8888

8989
def create_firewall_rule(self, name: str, network_url: str,
9090
source_ranges: List[str],
91-
ports: List[str]) -> Optional[GcpResource]:
91+
ports: List[str]) -> Optional['GcpResource']:
9292
try:
9393
return self._insert_resource(
9494
self.api.firewalls(), {
@@ -107,7 +107,7 @@ def create_firewall_rule(self, name: str, network_url: str,
107107
# TODO(lidiz) use status_code() when we upgrade googleapiclient
108108
if http_error.resp.status == 409:
109109
logger.debug('Firewall rule %s already existed', name)
110-
return
110+
return None
111111
else:
112112
raise
113113

@@ -117,10 +117,10 @@ def delete_firewall_rule(self, name):
117117
def create_backend_service_traffic_director(
118118
self,
119119
name: str,
120-
health_check: GcpResource,
121-
affinity_header: str = None,
120+
health_check: 'GcpResource',
121+
affinity_header: Optional[str] = None,
122122
protocol: Optional[BackendServiceProtocol] = None,
123-
subset_size: Optional[int] = None) -> GcpResource:
123+
subset_size: Optional[int] = None) -> 'GcpResource':
124124
if not isinstance(protocol, self.BackendServiceProtocol):
125125
raise TypeError(f'Unexpected Backend Service protocol: {protocol}')
126126
body = {
@@ -144,7 +144,7 @@ def create_backend_service_traffic_director(
144144
}
145145
return self._insert_resource(self.api.backendServices(), body)
146146

147-
def get_backend_service_traffic_director(self, name: str) -> GcpResource:
147+
def get_backend_service_traffic_director(self, name: str) -> 'GcpResource':
148148
return self._get_resource(self.api.backendServices(),
149149
backendService=name)
150150

@@ -185,9 +185,9 @@ def create_url_map(
185185
name: str,
186186
matcher_name: str,
187187
src_hosts,
188-
dst_default_backend_service: GcpResource,
189-
dst_host_rule_match_backend_service: Optional[GcpResource] = None,
190-
) -> GcpResource:
188+
dst_default_backend_service: 'GcpResource',
189+
dst_host_rule_match_backend_service: Optional['GcpResource'] = None,
190+
) -> 'GcpResource':
191191
if dst_host_rule_match_backend_service is None:
192192
dst_host_rule_match_backend_service = dst_default_backend_service
193193
return self._insert_resource(
@@ -206,10 +206,10 @@ def create_url_map(
206206
}],
207207
})
208208

209-
def create_url_map_with_content(self, url_map_body: Any) -> GcpResource:
209+
def create_url_map_with_content(self, url_map_body: Any) -> 'GcpResource':
210210
return self._insert_resource(self.api.urlMaps(), url_map_body)
211211

212-
def patch_url_map(self, url_map: GcpResource, body, **kwargs):
212+
def patch_url_map(self, url_map: 'GcpResource', body, **kwargs):
213213
self._patch_resource(collection=self.api.urlMaps(),
214214
urlMap=url_map.name,
215215
body=body,
@@ -221,9 +221,9 @@ def delete_url_map(self, name):
221221
def create_target_grpc_proxy(
222222
self,
223223
name: str,
224-
url_map: GcpResource,
224+
url_map: 'GcpResource',
225225
validate_for_proxyless: bool = True,
226-
) -> GcpResource:
226+
) -> 'GcpResource':
227227
return self._insert_resource(
228228
self.api.targetGrpcProxies(), {
229229
'name': name,
@@ -238,8 +238,8 @@ def delete_target_grpc_proxy(self, name):
238238
def create_target_http_proxy(
239239
self,
240240
name: str,
241-
url_map: GcpResource,
242-
) -> GcpResource:
241+
url_map: 'GcpResource',
242+
) -> 'GcpResource':
243243
return self._insert_resource(self.api.targetHttpProxies(), {
244244
'name': name,
245245
'url_map': url_map.url,
@@ -252,10 +252,10 @@ def delete_target_http_proxy(self, name):
252252
def create_forwarding_rule(self,
253253
name: str,
254254
src_port: int,
255-
target_proxy: GcpResource,
255+
target_proxy: 'GcpResource',
256256
network_url: str,
257257
*,
258-
ip_address: str = '0.0.0.0') -> GcpResource:
258+
ip_address: str = '0.0.0.0') -> 'GcpResource':
259259
return self._insert_resource(
260260
self.api.globalForwardingRules(),
261261
{
@@ -367,14 +367,14 @@ def get_backend_service_backend_health(self, backend_service, backend):
367367
}).execute()
368368

369369
def _get_resource(self, collection: discovery.Resource,
370-
**kwargs) -> GcpResource:
370+
**kwargs) -> 'GcpResource':
371371
resp = collection.get(project=self.project, **kwargs).execute()
372372
logger.info('Loaded compute resource:\n%s',
373373
self.resource_pretty_format(resp))
374374
return self.GcpResource(resp['name'], resp['selfLink'])
375375

376-
def _exists_resource(self, collection: discovery.Resource,
377-
filter: str) -> bool:
376+
def _exists_resource(
377+
self, collection: discovery.Resource, filter: str) -> bool: # pylint: disable=redefined-builtin
378378
resp = collection.list(
379379
project=self.project, filter=filter,
380380
maxResults=1).execute(num_retries=self._GCP_API_RETRIES)
@@ -384,7 +384,7 @@ def _exists_resource(self, collection: discovery.Resource,
384384
return 'items' in resp and resp['items']
385385

386386
def _insert_resource(self, collection: discovery.Resource,
387-
body: Dict[str, Any]) -> GcpResource:
387+
body: Dict[str, Any]) -> 'GcpResource':
388388
logger.info('Creating compute resource:\n%s',
389389
self.resource_pretty_format(body))
390390
resp = self._execute(collection.insert(project=self.project, body=body))
@@ -420,11 +420,12 @@ def _delete_resource(self, collection: discovery.Resource,
420420
def _operation_status_done(operation):
421421
return 'status' in operation and operation['status'] == 'DONE'
422422

423-
def _execute(self,
424-
request,
425-
*,
426-
test_success_fn=None,
427-
timeout_sec=_WAIT_FOR_OPERATION_SEC):
423+
def _execute( # pylint: disable=arguments-differ
424+
self,
425+
request,
426+
*,
427+
test_success_fn=None,
428+
timeout_sec=_WAIT_FOR_OPERATION_SEC):
428429
operation = request.execute(num_retries=self._GCP_API_RETRIES)
429430
logger.debug('Response %s', operation)
430431

framework/infrastructure/gcp/iam.py

Lines changed: 8 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -33,7 +33,6 @@ class EtagConflict(gcp.api.Error):
3333
3434
https://cloud.google.com/iam/docs/policies#etag
3535
"""
36-
pass
3736

3837

3938
def handle_etag_conflict(func):
@@ -54,7 +53,7 @@ def _replace_binding(policy: 'Policy', binding: 'Policy.Binding',
5453
new_bindings = set(policy.bindings)
5554
new_bindings.discard(binding)
5655
new_bindings.add(new_binding)
57-
return dataclasses.replace(policy, bindings=frozenset(new_bindings))
56+
return dataclasses.replace(policy, bindings=frozenset(new_bindings)) # pylint: disable=too-many-function-args
5857

5958

6059
@dataclasses.dataclass(frozen=True)
@@ -190,7 +189,7 @@ class IamV1(gcp.api.GcpProjectApiResource):
190189
# Otherwise conditions are omitted, and role names returned with a suffix,
191190
# f.e. roles/iam.workloadIdentityUser_withcond_f1ec33c9beb41857dbf0
192191
# https://cloud.google.com/iam/docs/reference/rest/v1/Policy#FIELDS.version
193-
POLICY_VERSION: str = 3
192+
POLICY_VERSION: int = 3
194193

195194
def __init__(self, api_manager: gcp.api.GcpApiManager, project: str):
196195
super().__init__(api_manager.iam('v1'), project)
@@ -271,8 +270,9 @@ def add_service_account_iam_policy_binding(self, account: str, role: str,
271270
updated_binding = Policy.Binding(role, frozenset([member]))
272271
else:
273272
updated_members: FrozenSet[str] = binding.members.union({member})
274-
updated_binding: Policy.Binding = dataclasses.replace(
275-
binding, members=updated_members)
273+
updated_binding: Policy.Binding = dataclasses.replace( # pylint: disable=too-many-function-args
274+
binding,
275+
members=updated_members)
276276

277277
updated_policy: Policy = _replace_binding(policy, binding,
278278
updated_binding)
@@ -303,8 +303,9 @@ def remove_service_account_iam_policy_binding(self, account: str, role: str,
303303
return
304304

305305
updated_members: FrozenSet[str] = binding.members.difference({member})
306-
updated_binding: Policy.Binding = dataclasses.replace(
307-
binding, members=updated_members)
306+
updated_binding: Policy.Binding = dataclasses.replace( # pylint: disable=too-many-function-args
307+
binding,
308+
members=updated_members)
308309
updated_policy: Policy = _replace_binding(policy, binding,
309310
updated_binding)
310311
self.set_service_account_iam_policy(account, updated_policy)

framework/infrastructure/gcp/network_security.py

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -92,6 +92,9 @@ class _NetworkSecurityBase(gcp.api.GcpStandardCloudApiResource,
9292
metaclass=abc.ABCMeta):
9393
"""Base class for NetworkSecurity APIs."""
9494

95+
# TODO(https://github.com/grpc/grpc/issues/29532) remove pylint disable
96+
# pylint: disable=abstract-method
97+
9598
def __init__(self, api_manager: gcp.api.GcpApiManager, project: str):
9699
super().__init__(api_manager.networksecurity(self.api_version), project)
97100
# Shortcut to projects/*/locations/ endpoints
@@ -101,7 +104,7 @@ def __init__(self, api_manager: gcp.api.GcpApiManager, project: str):
101104
def api_name(self) -> str:
102105
return 'networksecurity'
103106

104-
def _execute(self, *args, **kwargs): # pylint: disable=signature-differs
107+
def _execute(self, *args, **kwargs): # pylint: disable=signature-differs,arguments-differ
105108
# Workaround TD bug: throttled operations are reported as internal.
106109
# Ref b/175345578
107110
retryer = tenacity.Retrying(

0 commit comments

Comments
 (0)