flwr-nightly 1.11.0.dev20240813__py3-none-any.whl → 1.11.0.dev20240816__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.

Potentially problematic release.


This version of flwr-nightly might be problematic. Click here for more details.

Files changed (44) hide show
  1. flwr/cli/config_utils.py +2 -2
  2. flwr/cli/run/run.py +11 -6
  3. flwr/client/app.py +97 -12
  4. flwr/client/grpc_rere_client/connection.py +9 -1
  5. flwr/client/process/__init__.py +15 -0
  6. flwr/client/process/clientappio_servicer.py +144 -0
  7. flwr/client/process/process.py +143 -0
  8. flwr/client/process/utils.py +108 -0
  9. flwr/client/rest_client/connection.py +16 -3
  10. flwr/client/supernode/app.py +25 -97
  11. flwr/common/config.py +7 -2
  12. flwr/common/record/recordset.py +9 -7
  13. flwr/common/record/typeddict.py +20 -58
  14. flwr/common/recordset_compat.py +6 -6
  15. flwr/common/serde.py +24 -2
  16. flwr/common/typing.py +1 -0
  17. flwr/proto/exec_pb2.py +16 -15
  18. flwr/proto/exec_pb2.pyi +7 -4
  19. flwr/proto/message_pb2.py +2 -2
  20. flwr/proto/message_pb2.pyi +4 -1
  21. flwr/server/app.py +15 -0
  22. flwr/server/driver/grpc_driver.py +1 -0
  23. flwr/server/run_serverapp.py +18 -2
  24. flwr/server/server.py +3 -1
  25. flwr/server/superlink/driver/driver_grpc.py +3 -0
  26. flwr/server/superlink/driver/driver_servicer.py +32 -4
  27. flwr/server/superlink/ffs/disk_ffs.py +6 -3
  28. flwr/server/superlink/ffs/ffs.py +3 -3
  29. flwr/server/superlink/ffs/ffs_factory.py +47 -0
  30. flwr/server/superlink/fleet/grpc_rere/fleet_servicer.py +9 -3
  31. flwr/server/superlink/fleet/message_handler/message_handler.py +16 -1
  32. flwr/server/superlink/fleet/vce/vce_api.py +2 -2
  33. flwr/server/superlink/state/in_memory_state.py +7 -5
  34. flwr/server/superlink/state/sqlite_state.py +17 -7
  35. flwr/server/superlink/state/state.py +4 -3
  36. flwr/server/workflow/default_workflows.py +3 -1
  37. flwr/simulation/run_simulation.py +4 -1
  38. flwr/superexec/deployment.py +8 -9
  39. flwr/superexec/exec_servicer.py +1 -1
  40. {flwr_nightly-1.11.0.dev20240813.dist-info → flwr_nightly-1.11.0.dev20240816.dist-info}/METADATA +1 -1
  41. {flwr_nightly-1.11.0.dev20240813.dist-info → flwr_nightly-1.11.0.dev20240816.dist-info}/RECORD +44 -39
  42. {flwr_nightly-1.11.0.dev20240813.dist-info → flwr_nightly-1.11.0.dev20240816.dist-info}/LICENSE +0 -0
  43. {flwr_nightly-1.11.0.dev20240813.dist-info → flwr_nightly-1.11.0.dev20240816.dist-info}/WHEEL +0 -0
  44. {flwr_nightly-1.11.0.dev20240813.dist-info → flwr_nightly-1.11.0.dev20240816.dist-info}/entry_points.txt +0 -0
flwr/cli/config_utils.py CHANGED
@@ -74,13 +74,13 @@ def get_fab_metadata(fab_file: Union[Path, bytes]) -> Tuple[str, str]:
74
74
  Returns
75
75
  -------
76
76
  Tuple[str, str]
77
- The `fab_version` and `fab_id` of the given Flower App Bundle.
77
+ The `fab_id` and `fab_version` of the given Flower App Bundle.
78
78
  """
79
79
  conf = get_fab_config(fab_file)
80
80
 
81
81
  return (
82
- conf["project"]["version"],
83
82
  f"{conf['tool']['flwr']['app']['publisher']}/{conf['project']['name']}",
83
+ conf["project"]["version"],
84
84
  )
85
85
 
86
86
 
flwr/cli/run/run.py CHANGED
@@ -14,6 +14,7 @@
14
14
  # ==============================================================================
15
15
  """Flower command line interface `run` command."""
16
16
 
17
+ import hashlib
17
18
  import subprocess
18
19
  import sys
19
20
  from logging import DEBUG
@@ -28,11 +29,17 @@ from flwr.cli.config_utils import load_and_validate
28
29
  from flwr.common.config import flatten_dict, parse_config_args
29
30
  from flwr.common.grpc import GRPC_MAX_MESSAGE_LENGTH, create_channel
30
31
  from flwr.common.logger import log
31
- from flwr.common.serde import user_config_to_proto
32
+ from flwr.common.serde import fab_to_proto, user_config_to_proto
33
+ from flwr.common.typing import Fab
32
34
  from flwr.proto.exec_pb2 import StartRunRequest # pylint: disable=E0611
33
35
  from flwr.proto.exec_pb2_grpc import ExecStub
34
36
 
35
37
 
38
+ def on_channel_state_change(channel_connectivity: str) -> None:
39
+ """Log channel connectivity."""
40
+ log(DEBUG, channel_connectivity)
41
+
42
+
36
43
  # pylint: disable-next=too-many-locals
37
44
  def run(
38
45
  app: Annotated[
@@ -120,10 +127,6 @@ def _run_with_superexec(
120
127
  config_overrides: Optional[List[str]],
121
128
  ) -> None:
122
129
 
123
- def on_channel_state_change(channel_connectivity: str) -> None:
124
- """Log channel connectivity."""
125
- log(DEBUG, channel_connectivity)
126
-
127
130
  insecure_str = federation_config.get("insecure")
128
131
  if root_certificates := federation_config.get("root-certificates"):
129
132
  root_certificates_bytes = Path(root_certificates).read_bytes()
@@ -163,9 +166,11 @@ def _run_with_superexec(
163
166
  stub = ExecStub(channel)
164
167
 
165
168
  fab_path = Path(build(app))
169
+ content = fab_path.read_bytes()
170
+ fab = Fab(hashlib.sha256(content).hexdigest(), content)
166
171
 
167
172
  req = StartRunRequest(
168
- fab_file=fab_path.read_bytes(),
173
+ fab=fab_to_proto(fab),
169
174
  override_config=user_config_to_proto(
170
175
  parse_config_args(config_overrides, separator=",")
171
176
  ),
flwr/client/app.py CHANGED
@@ -15,6 +15,7 @@
15
15
  """Flower client app."""
16
16
 
17
17
  import signal
18
+ import subprocess
18
19
  import sys
19
20
  import time
20
21
  from dataclasses import dataclass
@@ -22,9 +23,12 @@ from logging import ERROR, INFO, WARN
22
23
  from pathlib import Path
23
24
  from typing import Callable, ContextManager, Dict, Optional, Tuple, Type, Union
24
25
 
26
+ import grpc
25
27
  from cryptography.hazmat.primitives.asymmetric import ec
26
28
  from grpc import RpcError
27
29
 
30
+ from flwr.cli.config_utils import get_fab_metadata
31
+ from flwr.cli.install import install_from_fab
28
32
  from flwr.client.client import Client
29
33
  from flwr.client.client_app import ClientApp, LoadClientAppError
30
34
  from flwr.client.typing import ClientFnExt
@@ -32,6 +36,7 @@ from flwr.common import GRPC_MAX_MESSAGE_LENGTH, Context, EventType, Message, ev
32
36
  from flwr.common.address import parse_address
33
37
  from flwr.common.constant import (
34
38
  MISSING_EXTRA_REST,
39
+ RUN_ID_NUM_BYTES,
35
40
  TRANSPORT_TYPE_GRPC_ADAPTER,
36
41
  TRANSPORT_TYPE_GRPC_BIDI,
37
42
  TRANSPORT_TYPE_GRPC_RERE,
@@ -43,6 +48,9 @@ from flwr.common.logger import log, warn_deprecated_feature
43
48
  from flwr.common.message import Error
44
49
  from flwr.common.retry_invoker import RetryInvoker, RetryState, exponential
45
50
  from flwr.common.typing import Fab, Run, UserConfig
51
+ from flwr.proto.clientappio_pb2_grpc import add_ClientAppIoServicer_to_server
52
+ from flwr.server.superlink.fleet.grpc_bidi.grpc_server import generic_create_grpc_server
53
+ from flwr.server.superlink.state.utils import generate_rand_int_from_bytes
46
54
 
47
55
  from .grpc_adapter_client.connection import grpc_adapter
48
56
  from .grpc_client.connection import grpc_connection
@@ -50,6 +58,9 @@ from .grpc_rere_client.connection import grpc_request_response
50
58
  from .message_handler.message_handler import handle_control_message
51
59
  from .node_state import NodeState
52
60
  from .numpy_client import NumPyClient
61
+ from .process.clientappio_servicer import ClientAppIoInputs, ClientAppIoServicer
62
+
63
+ ADDRESS_CLIENTAPPIO_API_GRPC_RERE = "0.0.0.0:9094"
53
64
 
54
65
 
55
66
  def _check_actionable_client(
@@ -158,7 +169,7 @@ def start_client(
158
169
  >>> )
159
170
  """
160
171
  event(EventType.START_CLIENT_ENTER)
161
- _start_client_internal(
172
+ start_client_internal(
162
173
  server_address=server_address,
163
174
  node_config={},
164
175
  load_client_app_fn=None,
@@ -179,7 +190,7 @@ def start_client(
179
190
  # pylint: disable=too-many-branches
180
191
  # pylint: disable=too-many-locals
181
192
  # pylint: disable=too-many-statements
182
- def _start_client_internal(
193
+ def start_client_internal(
183
194
  *,
184
195
  server_address: str,
185
196
  node_config: UserConfig,
@@ -196,6 +207,8 @@ def _start_client_internal(
196
207
  max_retries: Optional[int] = None,
197
208
  max_wait_time: Optional[float] = None,
198
209
  flwr_path: Optional[Path] = None,
210
+ isolate: Optional[bool] = False,
211
+ supernode_address: Optional[str] = ADDRESS_CLIENTAPPIO_API_GRPC_RERE,
199
212
  ) -> None:
200
213
  """Start a Flower client node which connects to a Flower server.
201
214
 
@@ -243,6 +256,13 @@ def _start_client_internal(
243
256
  If set to None, there is no limit to the total time.
244
257
  flwr_path: Optional[Path] (default: None)
245
258
  The fully resolved path containing installed Flower Apps.
259
+ isolate : Optional[bool] (default: False)
260
+ Whether to run `ClientApp` in a separate process. By default, this value is
261
+ `False`, and the `ClientApp` runs in the same process as the SuperNode. If
262
+ `True`, the `ClientApp` runs in an isolated process and communicates using
263
+ gRPC at the address `supernode_address`.
264
+ supernode_address : Optional[str] (default: `ADDRESS_CLIENTAPPIO_API_GRPC_RERE`)
265
+ The SuperNode gRPC server address.
246
266
  """
247
267
  if insecure is None:
248
268
  insecure = root_certificates is None
@@ -268,6 +288,13 @@ def _start_client_internal(
268
288
 
269
289
  load_client_app_fn = _load_client_app
270
290
 
291
+ if isolate:
292
+ if supernode_address is None:
293
+ raise ValueError("`supernode_address` required when `isolate` is set")
294
+ _clientappio_grpc_server, clientappio_servicer = run_clientappio_api_grpc(
295
+ address=supernode_address
296
+ )
297
+
271
298
  # At this point, only `load_client_app_fn` should be used
272
299
  # Both `client` and `client_fn` must not be used directly
273
300
 
@@ -333,7 +360,7 @@ def _start_client_internal(
333
360
  root_certificates,
334
361
  authentication_keys,
335
362
  ) as conn:
336
- receive, send, create_node, delete_node, get_run, _ = conn
363
+ receive, send, create_node, delete_node, get_run, get_fab = conn
337
364
 
338
365
  # Register node when connecting the first time
339
366
  if node_state is None:
@@ -398,11 +425,22 @@ def _start_client_internal(
398
425
  runs[run_id] = get_run(run_id)
399
426
  # If get_run is None, i.e., in grpc-bidi mode
400
427
  else:
401
- runs[run_id] = Run(run_id, "", "", {})
428
+ runs[run_id] = Run(run_id, "", "", "", {})
429
+
430
+ run: Run = runs[run_id]
431
+ if get_fab is not None and run.fab_hash:
432
+ fab = get_fab(run.fab_hash)
433
+ install_from_fab(fab.content, flwr_path, True)
434
+ fab_id, fab_version = get_fab_metadata(fab.content)
435
+ else:
436
+ fab = None
437
+ fab_id, fab_version = run.fab_id, run.fab_version
438
+
439
+ run.fab_id, run.fab_version = fab_id, fab_version
402
440
 
403
441
  # Register context for this run
404
442
  node_state.register_context(
405
- run_id=run_id, run=runs[run_id], flwr_path=flwr_path
443
+ run_id=run_id, run=run, flwr_path=flwr_path
406
444
  )
407
445
 
408
446
  # Retrieve context for this run
@@ -416,14 +454,44 @@ def _start_client_internal(
416
454
 
417
455
  # Handle app loading and task message
418
456
  try:
419
- # Load ClientApp instance
420
- run: Run = runs[run_id]
421
- client_app: ClientApp = load_client_app_fn(
422
- run.fab_id, run.fab_version
423
- )
457
+ if isolate and supernode_address is not None:
458
+ # Generate SuperNode token
459
+ token: int = generate_rand_int_from_bytes(RUN_ID_NUM_BYTES)
460
+
461
+ # Share Message and Context with servicer
462
+ clientappio_servicer.set_inputs(
463
+ ClientAppIoInputs(
464
+ message=message,
465
+ context=context,
466
+ run=run,
467
+ token=token,
468
+ )
469
+ )
424
470
 
425
- # Execute ClientApp
426
- reply_message = client_app(message=message, context=context)
471
+ # Run `ClientApp` in subprocess
472
+ command = [
473
+ "flwr-clientapp",
474
+ "--supernode",
475
+ supernode_address,
476
+ "--token",
477
+ str(token),
478
+ ]
479
+ subprocess.run(
480
+ command,
481
+ stdout=None,
482
+ stderr=None,
483
+ check=True,
484
+ )
485
+ outputs = clientappio_servicer.get_outputs()
486
+ reply_message, context = outputs.message, outputs.context
487
+ else:
488
+ # Load ClientApp instance
489
+ client_app: ClientApp = load_client_app_fn(
490
+ fab_id, fab_version
491
+ )
492
+
493
+ # Execute ClientApp
494
+ reply_message = client_app(message=message, context=context)
427
495
  except Exception as ex: # pylint: disable=broad-exception-caught
428
496
 
429
497
  # Legacy grpc-bidi
@@ -667,3 +735,20 @@ class _AppStateTracker:
667
735
 
668
736
  signal.signal(signal.SIGINT, signal_handler)
669
737
  signal.signal(signal.SIGTERM, signal_handler)
738
+
739
+
740
+ def run_clientappio_api_grpc(address: str) -> Tuple[grpc.Server, ClientAppIoServicer]:
741
+ """Run ClientAppIo API gRPC server."""
742
+ clientappio_servicer: grpc.Server = ClientAppIoServicer()
743
+ clientappio_add_servicer_to_server_fn = add_ClientAppIoServicer_to_server
744
+ clientappio_grpc_server = generic_create_grpc_server(
745
+ servicer_and_add_fn=(
746
+ clientappio_servicer,
747
+ clientappio_add_servicer_to_server_fn,
748
+ ),
749
+ server_address=address,
750
+ max_message_length=GRPC_MAX_MESSAGE_LENGTH,
751
+ )
752
+ log(INFO, "Starting Flower ClientAppIo gRPC server on %s", address)
753
+ clientappio_grpc_server.start()
754
+ return clientappio_grpc_server, clientappio_servicer
@@ -46,6 +46,7 @@ from flwr.common.serde import (
46
46
  user_config_from_proto,
47
47
  )
48
48
  from flwr.common.typing import Fab, Run
49
+ from flwr.proto.fab_pb2 import GetFabRequest, GetFabResponse # pylint: disable=E0611
49
50
  from flwr.proto.fleet_pb2 import ( # pylint: disable=E0611
50
51
  CreateNodeRequest,
51
52
  DeleteNodeRequest,
@@ -286,12 +287,19 @@ def grpc_request_response( # pylint: disable=R0913, R0914, R0915
286
287
  run_id,
287
288
  get_run_response.run.fab_id,
288
289
  get_run_response.run.fab_version,
290
+ get_run_response.run.fab_hash,
289
291
  user_config_from_proto(get_run_response.run.override_config),
290
292
  )
291
293
 
292
294
  def get_fab(fab_hash: str) -> Fab:
293
295
  # Call FleetAPI
294
- raise NotImplementedError
296
+ get_fab_request = GetFabRequest(hash_str=fab_hash)
297
+ get_fab_response: GetFabResponse = retry_invoker.invoke(
298
+ stub.GetFab,
299
+ request=get_fab_request,
300
+ )
301
+
302
+ return Fab(get_fab_response.fab.hash_str, get_fab_response.fab.content)
295
303
 
296
304
  try:
297
305
  # Yield methods
@@ -0,0 +1,15 @@
1
+ # Copyright 2024 Flower Labs GmbH. All Rights Reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ # ==============================================================================
15
+ """Flower AppIO service."""
@@ -0,0 +1,144 @@
1
+ # Copyright 2024 Flower Labs GmbH. All Rights Reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ # ==============================================================================
15
+ """ClientAppIo API servicer."""
16
+
17
+
18
+ from dataclasses import dataclass
19
+ from logging import DEBUG, ERROR
20
+ from typing import Optional
21
+
22
+ import grpc
23
+
24
+ from flwr.common import Context, Message, typing
25
+ from flwr.common.logger import log
26
+ from flwr.common.serde import (
27
+ clientappstatus_to_proto,
28
+ context_from_proto,
29
+ context_to_proto,
30
+ message_from_proto,
31
+ message_to_proto,
32
+ run_to_proto,
33
+ )
34
+ from flwr.common.typing import Run
35
+
36
+ # pylint: disable=E0611
37
+ from flwr.proto import clientappio_pb2_grpc
38
+ from flwr.proto.clientappio_pb2 import ( # pylint: disable=E0401
39
+ PullClientAppInputsRequest,
40
+ PullClientAppInputsResponse,
41
+ PushClientAppOutputsRequest,
42
+ PushClientAppOutputsResponse,
43
+ )
44
+
45
+
46
+ @dataclass
47
+ class ClientAppIoInputs:
48
+ """Specify the inputs to the ClientApp."""
49
+
50
+ message: Message
51
+ context: Context
52
+ run: Run
53
+ token: int
54
+
55
+
56
+ @dataclass
57
+ class ClientAppIoOutputs:
58
+ """Specify the outputs from the ClientApp."""
59
+
60
+ message: Message
61
+ context: Context
62
+
63
+
64
+ # pylint: disable=C0103,W0613,W0201
65
+ class ClientAppIoServicer(clientappio_pb2_grpc.ClientAppIoServicer):
66
+ """ClientAppIo API servicer."""
67
+
68
+ def __init__(self) -> None:
69
+ self.clientapp_input: Optional[ClientAppIoInputs] = None
70
+ self.clientapp_output: Optional[ClientAppIoOutputs] = None
71
+
72
+ def PullClientAppInputs(
73
+ self, request: PullClientAppInputsRequest, context: grpc.ServicerContext
74
+ ) -> PullClientAppInputsResponse:
75
+ """Pull Message, Context, and Run."""
76
+ log(DEBUG, "ClientAppIo.PullClientAppInputs")
77
+ if self.clientapp_input is None:
78
+ raise ValueError(
79
+ "ClientAppIoInputs not set before calling `PullClientAppInputs`."
80
+ )
81
+ if request.token != self.clientapp_input.token:
82
+ context.abort(
83
+ grpc.StatusCode.INVALID_ARGUMENT,
84
+ "Mismatch between ClientApp and SuperNode token",
85
+ )
86
+ return PullClientAppInputsResponse(
87
+ message=message_to_proto(self.clientapp_input.message),
88
+ context=context_to_proto(self.clientapp_input.context),
89
+ run=run_to_proto(self.clientapp_input.run),
90
+ )
91
+
92
+ def PushClientAppOutputs(
93
+ self, request: PushClientAppOutputsRequest, context: grpc.ServicerContext
94
+ ) -> PushClientAppOutputsResponse:
95
+ """Push Message and Context."""
96
+ log(DEBUG, "ClientAppIo.PushClientAppOutputs")
97
+ if self.clientapp_input is None:
98
+ raise ValueError(
99
+ "ClientAppIoInputs not set before calling `PushClientAppOutputs`."
100
+ )
101
+ if request.token != self.clientapp_input.token:
102
+ context.abort(
103
+ grpc.StatusCode.INVALID_ARGUMENT,
104
+ "Mismatch between ClientApp and SuperNode token",
105
+ )
106
+ try:
107
+ # Update Message and Context
108
+ self.clientapp_output = ClientAppIoOutputs(
109
+ message=message_from_proto(request.message),
110
+ context=context_from_proto(request.context),
111
+ )
112
+
113
+ # Set status
114
+ code = typing.ClientAppOutputCode.SUCCESS
115
+ status = typing.ClientAppOutputStatus(code=code, message="Success")
116
+ proto_status = clientappstatus_to_proto(status=status)
117
+ return PushClientAppOutputsResponse(status=proto_status)
118
+ except Exception as e: # pylint: disable=broad-exception-caught
119
+ log(ERROR, "ClientApp failed to push message to SuperNode, %s", e)
120
+ code = typing.ClientAppOutputCode.UNKNOWN_ERROR
121
+ status = typing.ClientAppOutputStatus(code=code, message="Push failed")
122
+ proto_status = clientappstatus_to_proto(status=status)
123
+ return PushClientAppOutputsResponse(status=proto_status)
124
+
125
+ def set_inputs(self, clientapp_input: ClientAppIoInputs) -> None:
126
+ """Set ClientApp inputs."""
127
+ log(DEBUG, "ClientAppIo.SetInputs")
128
+ if self.clientapp_input is not None or self.clientapp_output is not None:
129
+ raise ValueError(
130
+ "ClientAppIoInputs and ClientAppIoOutputs must not be set before "
131
+ "calling `set_inputs`."
132
+ )
133
+ self.clientapp_input = clientapp_input
134
+
135
+ def get_outputs(self) -> ClientAppIoOutputs:
136
+ """Get ClientApp outputs."""
137
+ log(DEBUG, "ClientAppIo.GetOutputs")
138
+ if self.clientapp_output is None:
139
+ raise ValueError("ClientAppIoOutputs not set before calling `get_outputs`.")
140
+ # Set outputs to a local variable and clear self.clientapp_output
141
+ output: ClientAppIoOutputs = self.clientapp_output
142
+ self.clientapp_input = None
143
+ self.clientapp_output = None
144
+ return output
@@ -0,0 +1,143 @@
1
+ # Copyright 2024 Flower Labs GmbH. All Rights Reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ # ==============================================================================
15
+ """Flower ClientApp process."""
16
+
17
+ from logging import DEBUG, ERROR, INFO
18
+ from typing import Tuple
19
+
20
+ import grpc
21
+
22
+ from flwr.client.client_app import ClientApp, LoadClientAppError
23
+ from flwr.common import Context, Message
24
+ from flwr.common.constant import ErrorCode
25
+ from flwr.common.grpc import create_channel
26
+ from flwr.common.logger import log
27
+ from flwr.common.message import Error
28
+ from flwr.common.serde import (
29
+ context_from_proto,
30
+ context_to_proto,
31
+ message_from_proto,
32
+ message_to_proto,
33
+ run_from_proto,
34
+ )
35
+ from flwr.common.typing import Run
36
+
37
+ # pylint: disable=E0611
38
+ from flwr.proto.clientappio_pb2 import (
39
+ PullClientAppInputsRequest,
40
+ PullClientAppInputsResponse,
41
+ PushClientAppOutputsRequest,
42
+ PushClientAppOutputsResponse,
43
+ )
44
+ from flwr.proto.clientappio_pb2_grpc import ClientAppIoStub
45
+
46
+ from .utils import get_load_client_app_fn
47
+
48
+
49
+ def on_channel_state_change(channel_connectivity: str) -> None:
50
+ """Log channel connectivity."""
51
+ log(DEBUG, channel_connectivity)
52
+
53
+
54
+ def run_clientapp( # pylint: disable=R0914
55
+ supernode: str,
56
+ token: int,
57
+ ) -> None:
58
+ """Run Flower ClientApp process.
59
+
60
+ Parameters
61
+ ----------
62
+ supernode : str
63
+ Address of SuperNode
64
+ token : int
65
+ Unique SuperNode token for ClientApp-SuperNode authentication
66
+ """
67
+ channel = create_channel(
68
+ server_address=supernode,
69
+ insecure=True,
70
+ )
71
+ channel.subscribe(on_channel_state_change)
72
+
73
+ try:
74
+ stub = ClientAppIoStub(channel)
75
+
76
+ # Pull Message, Context, and Run from SuperNode
77
+ message, context, run = pull_message(stub=stub, token=token)
78
+
79
+ load_client_app_fn = get_load_client_app_fn(
80
+ default_app_ref="",
81
+ app_path=None,
82
+ multi_app=True,
83
+ flwr_dir=None,
84
+ )
85
+
86
+ try:
87
+ # Load ClientApp
88
+ client_app: ClientApp = load_client_app_fn(run.fab_id, run.fab_version)
89
+
90
+ # Execute ClientApp
91
+ reply_message = client_app(message=message, context=context)
92
+ except Exception as ex: # pylint: disable=broad-exception-caught
93
+ # Don't update/change NodeState
94
+
95
+ e_code = ErrorCode.CLIENT_APP_RAISED_EXCEPTION
96
+ # Ex fmt: "<class 'ZeroDivisionError'>:<'division by zero'>"
97
+ reason = str(type(ex)) + ":<'" + str(ex) + "'>"
98
+ exc_entity = "ClientApp"
99
+ if isinstance(ex, LoadClientAppError):
100
+ reason = "An exception was raised when attempting to load `ClientApp`"
101
+ e_code = ErrorCode.LOAD_CLIENT_APP_EXCEPTION
102
+
103
+ log(ERROR, "%s raised an exception", exc_entity, exc_info=ex)
104
+
105
+ # Create error message
106
+ reply_message = message.create_error_reply(
107
+ error=Error(code=e_code, reason=reason)
108
+ )
109
+
110
+ # Push Message and Context to SuperNode
111
+ _ = push_message(stub=stub, token=token, message=reply_message, context=context)
112
+
113
+ except KeyboardInterrupt:
114
+ log(INFO, "Closing connection")
115
+ except grpc.RpcError as e:
116
+ log(ERROR, "GRPC error occurred: %s", str(e))
117
+ finally:
118
+ channel.close()
119
+
120
+
121
+ def pull_message(stub: grpc.Channel, token: int) -> Tuple[Message, Context, Run]:
122
+ """Pull message from SuperNode to ClientApp."""
123
+ res: PullClientAppInputsResponse = stub.PullClientAppInputs(
124
+ PullClientAppInputsRequest(token=token)
125
+ )
126
+ message = message_from_proto(res.message)
127
+ context = context_from_proto(res.context)
128
+ run = run_from_proto(res.run)
129
+ return message, context, run
130
+
131
+
132
+ def push_message(
133
+ stub: grpc.Channel, token: int, message: Message, context: Context
134
+ ) -> PushClientAppOutputsResponse:
135
+ """Push message to SuperNode from ClientApp."""
136
+ proto_message = message_to_proto(message)
137
+ proto_context = context_to_proto(context)
138
+ res: PushClientAppOutputsResponse = stub.PushClientAppOutputs(
139
+ PushClientAppOutputsRequest(
140
+ token=token, message=proto_message, context=proto_context
141
+ )
142
+ )
143
+ return res