flwr-nightly 1.8.0.dev20240315__py3-none-any.whl → 1.15.0.dev20250114__py3-none-any.whl

Sign up to get free protection for your applications and to get access to all the features.
Files changed (311) hide show
  1. flwr/cli/app.py +16 -2
  2. flwr/cli/build.py +181 -0
  3. flwr/cli/cli_user_auth_interceptor.py +90 -0
  4. flwr/cli/config_utils.py +343 -0
  5. flwr/cli/example.py +4 -1
  6. flwr/cli/install.py +253 -0
  7. flwr/cli/log.py +182 -0
  8. flwr/{server/superlink/state → cli/login}/__init__.py +4 -10
  9. flwr/cli/login/login.py +88 -0
  10. flwr/cli/ls.py +327 -0
  11. flwr/cli/new/__init__.py +1 -0
  12. flwr/cli/new/new.py +210 -66
  13. flwr/cli/new/templates/app/.gitignore.tpl +163 -0
  14. flwr/cli/new/templates/app/LICENSE.tpl +202 -0
  15. flwr/cli/new/templates/app/README.baseline.md.tpl +127 -0
  16. flwr/cli/new/templates/app/README.flowertune.md.tpl +66 -0
  17. flwr/cli/new/templates/app/README.md.tpl +16 -32
  18. flwr/cli/new/templates/app/code/__init__.baseline.py.tpl +1 -0
  19. flwr/cli/new/templates/app/code/__init__.py.tpl +1 -1
  20. flwr/cli/new/templates/app/code/client.baseline.py.tpl +58 -0
  21. flwr/cli/new/templates/app/code/client.huggingface.py.tpl +55 -0
  22. flwr/cli/new/templates/app/code/client.jax.py.tpl +50 -0
  23. flwr/cli/new/templates/app/code/client.mlx.py.tpl +73 -0
  24. flwr/cli/new/templates/app/code/client.numpy.py.tpl +7 -7
  25. flwr/cli/new/templates/app/code/client.pytorch.py.tpl +30 -21
  26. flwr/cli/new/templates/app/code/client.sklearn.py.tpl +63 -0
  27. flwr/cli/new/templates/app/code/client.tensorflow.py.tpl +57 -1
  28. flwr/cli/new/templates/app/code/dataset.baseline.py.tpl +36 -0
  29. flwr/cli/new/templates/app/code/flwr_tune/__init__.py +15 -0
  30. flwr/cli/new/templates/app/code/flwr_tune/client_app.py.tpl +126 -0
  31. flwr/cli/new/templates/app/code/flwr_tune/dataset.py.tpl +87 -0
  32. flwr/cli/new/templates/app/code/flwr_tune/models.py.tpl +78 -0
  33. flwr/cli/new/templates/app/code/flwr_tune/server_app.py.tpl +94 -0
  34. flwr/cli/new/templates/app/code/flwr_tune/strategy.py.tpl +83 -0
  35. flwr/cli/new/templates/app/code/model.baseline.py.tpl +80 -0
  36. flwr/cli/new/templates/app/code/server.baseline.py.tpl +46 -0
  37. flwr/cli/new/templates/app/code/server.huggingface.py.tpl +38 -0
  38. flwr/cli/new/templates/app/code/server.jax.py.tpl +26 -0
  39. flwr/cli/new/templates/app/code/server.mlx.py.tpl +31 -0
  40. flwr/cli/new/templates/app/code/server.numpy.py.tpl +22 -9
  41. flwr/cli/new/templates/app/code/server.pytorch.py.tpl +21 -18
  42. flwr/cli/new/templates/app/code/server.sklearn.py.tpl +36 -0
  43. flwr/cli/new/templates/app/code/server.tensorflow.py.tpl +29 -1
  44. flwr/cli/new/templates/app/code/strategy.baseline.py.tpl +1 -0
  45. flwr/cli/new/templates/app/code/task.huggingface.py.tpl +102 -0
  46. flwr/cli/new/templates/app/code/task.jax.py.tpl +57 -0
  47. flwr/cli/new/templates/app/code/task.mlx.py.tpl +102 -0
  48. flwr/cli/new/templates/app/code/task.numpy.py.tpl +7 -0
  49. flwr/cli/new/templates/app/code/task.pytorch.py.tpl +29 -24
  50. flwr/cli/new/templates/app/code/task.sklearn.py.tpl +67 -0
  51. flwr/cli/new/templates/app/code/task.tensorflow.py.tpl +53 -0
  52. flwr/cli/new/templates/app/code/utils.baseline.py.tpl +1 -0
  53. flwr/cli/new/templates/app/pyproject.baseline.toml.tpl +138 -0
  54. flwr/cli/new/templates/app/pyproject.flowertune.toml.tpl +68 -0
  55. flwr/cli/new/templates/app/pyproject.huggingface.toml.tpl +46 -0
  56. flwr/cli/new/templates/app/pyproject.jax.toml.tpl +35 -0
  57. flwr/cli/new/templates/app/pyproject.mlx.toml.tpl +39 -0
  58. flwr/cli/new/templates/app/pyproject.numpy.toml.tpl +25 -12
  59. flwr/cli/new/templates/app/pyproject.pytorch.toml.tpl +29 -14
  60. flwr/cli/new/templates/app/pyproject.sklearn.toml.tpl +35 -0
  61. flwr/cli/new/templates/app/pyproject.tensorflow.toml.tpl +29 -14
  62. flwr/cli/run/__init__.py +1 -0
  63. flwr/cli/run/run.py +212 -34
  64. flwr/cli/stop.py +130 -0
  65. flwr/cli/utils.py +240 -5
  66. flwr/client/__init__.py +3 -2
  67. flwr/client/app.py +432 -255
  68. flwr/client/client.py +1 -11
  69. flwr/client/client_app.py +74 -13
  70. flwr/client/clientapp/__init__.py +22 -0
  71. flwr/client/clientapp/app.py +259 -0
  72. flwr/client/clientapp/clientappio_servicer.py +244 -0
  73. flwr/client/clientapp/utils.py +115 -0
  74. flwr/client/dpfedavg_numpy_client.py +7 -8
  75. flwr/client/grpc_adapter_client/__init__.py +15 -0
  76. flwr/client/grpc_adapter_client/connection.py +98 -0
  77. flwr/client/grpc_client/connection.py +21 -7
  78. flwr/client/grpc_rere_client/__init__.py +1 -1
  79. flwr/client/grpc_rere_client/client_interceptor.py +176 -0
  80. flwr/client/grpc_rere_client/connection.py +163 -56
  81. flwr/client/grpc_rere_client/grpc_adapter.py +167 -0
  82. flwr/client/heartbeat.py +74 -0
  83. flwr/client/message_handler/__init__.py +1 -1
  84. flwr/client/message_handler/message_handler.py +10 -11
  85. flwr/client/mod/__init__.py +5 -5
  86. flwr/client/mod/centraldp_mods.py +4 -2
  87. flwr/client/mod/comms_mods.py +5 -4
  88. flwr/client/mod/localdp_mod.py +10 -5
  89. flwr/client/mod/secure_aggregation/__init__.py +1 -1
  90. flwr/client/mod/secure_aggregation/secaggplus_mod.py +26 -26
  91. flwr/client/mod/utils.py +2 -4
  92. flwr/client/nodestate/__init__.py +26 -0
  93. flwr/client/nodestate/in_memory_nodestate.py +38 -0
  94. flwr/client/nodestate/nodestate.py +31 -0
  95. flwr/client/nodestate/nodestate_factory.py +38 -0
  96. flwr/client/numpy_client.py +8 -31
  97. flwr/client/rest_client/__init__.py +1 -1
  98. flwr/client/rest_client/connection.py +199 -176
  99. flwr/client/run_info_store.py +112 -0
  100. flwr/client/supernode/__init__.py +24 -0
  101. flwr/client/supernode/app.py +321 -0
  102. flwr/client/typing.py +1 -0
  103. flwr/common/__init__.py +17 -11
  104. flwr/common/address.py +47 -3
  105. flwr/common/args.py +153 -0
  106. flwr/common/auth_plugin/__init__.py +24 -0
  107. flwr/common/auth_plugin/auth_plugin.py +121 -0
  108. flwr/common/config.py +243 -0
  109. flwr/common/constant.py +132 -1
  110. flwr/common/context.py +32 -2
  111. flwr/common/date.py +22 -4
  112. flwr/common/differential_privacy.py +2 -2
  113. flwr/common/dp.py +2 -4
  114. flwr/common/exit_handlers.py +3 -3
  115. flwr/common/grpc.py +164 -5
  116. flwr/common/logger.py +230 -12
  117. flwr/common/message.py +191 -106
  118. flwr/common/object_ref.py +179 -44
  119. flwr/common/pyproject.py +1 -0
  120. flwr/common/record/__init__.py +2 -1
  121. flwr/common/record/configsrecord.py +58 -18
  122. flwr/common/record/metricsrecord.py +57 -17
  123. flwr/common/record/parametersrecord.py +88 -20
  124. flwr/common/record/recordset.py +153 -30
  125. flwr/common/record/typeddict.py +30 -55
  126. flwr/common/recordset_compat.py +31 -12
  127. flwr/common/retry_invoker.py +123 -30
  128. flwr/common/secure_aggregation/__init__.py +1 -1
  129. flwr/common/secure_aggregation/crypto/__init__.py +1 -1
  130. flwr/common/secure_aggregation/crypto/shamir.py +11 -11
  131. flwr/common/secure_aggregation/crypto/symmetric_encryption.py +68 -4
  132. flwr/common/secure_aggregation/ndarrays_arithmetic.py +17 -17
  133. flwr/common/secure_aggregation/quantization.py +8 -8
  134. flwr/common/secure_aggregation/secaggplus_constants.py +1 -1
  135. flwr/common/secure_aggregation/secaggplus_utils.py +10 -12
  136. flwr/common/serde.py +298 -19
  137. flwr/common/telemetry.py +65 -29
  138. flwr/common/typing.py +120 -19
  139. flwr/common/version.py +17 -3
  140. flwr/proto/clientappio_pb2.py +45 -0
  141. flwr/proto/clientappio_pb2.pyi +132 -0
  142. flwr/proto/clientappio_pb2_grpc.py +135 -0
  143. flwr/proto/clientappio_pb2_grpc.pyi +53 -0
  144. flwr/proto/exec_pb2.py +62 -0
  145. flwr/proto/exec_pb2.pyi +212 -0
  146. flwr/proto/exec_pb2_grpc.py +237 -0
  147. flwr/proto/exec_pb2_grpc.pyi +93 -0
  148. flwr/proto/fab_pb2.py +31 -0
  149. flwr/proto/fab_pb2.pyi +65 -0
  150. flwr/proto/fab_pb2_grpc.py +4 -0
  151. flwr/proto/fab_pb2_grpc.pyi +4 -0
  152. flwr/proto/fleet_pb2.py +42 -23
  153. flwr/proto/fleet_pb2.pyi +123 -1
  154. flwr/proto/fleet_pb2_grpc.py +170 -0
  155. flwr/proto/fleet_pb2_grpc.pyi +61 -0
  156. flwr/proto/grpcadapter_pb2.py +32 -0
  157. flwr/proto/grpcadapter_pb2.pyi +43 -0
  158. flwr/proto/grpcadapter_pb2_grpc.py +66 -0
  159. flwr/proto/grpcadapter_pb2_grpc.pyi +24 -0
  160. flwr/proto/log_pb2.py +29 -0
  161. flwr/proto/log_pb2.pyi +39 -0
  162. flwr/proto/log_pb2_grpc.py +4 -0
  163. flwr/proto/log_pb2_grpc.pyi +4 -0
  164. flwr/proto/message_pb2.py +41 -0
  165. flwr/proto/message_pb2.pyi +128 -0
  166. flwr/proto/message_pb2_grpc.py +4 -0
  167. flwr/proto/message_pb2_grpc.pyi +4 -0
  168. flwr/proto/node_pb2.py +1 -1
  169. flwr/proto/recordset_pb2.py +35 -33
  170. flwr/proto/recordset_pb2.pyi +40 -14
  171. flwr/proto/run_pb2.py +64 -0
  172. flwr/proto/run_pb2.pyi +268 -0
  173. flwr/proto/run_pb2_grpc.py +4 -0
  174. flwr/proto/run_pb2_grpc.pyi +4 -0
  175. flwr/proto/serverappio_pb2.py +52 -0
  176. flwr/proto/{driver_pb2.pyi → serverappio_pb2.pyi} +62 -20
  177. flwr/proto/serverappio_pb2_grpc.py +410 -0
  178. flwr/proto/serverappio_pb2_grpc.pyi +160 -0
  179. flwr/proto/simulationio_pb2.py +38 -0
  180. flwr/proto/simulationio_pb2.pyi +65 -0
  181. flwr/proto/simulationio_pb2_grpc.py +239 -0
  182. flwr/proto/simulationio_pb2_grpc.pyi +94 -0
  183. flwr/proto/task_pb2.py +7 -8
  184. flwr/proto/task_pb2.pyi +8 -5
  185. flwr/proto/transport_pb2.py +8 -8
  186. flwr/proto/transport_pb2.pyi +9 -6
  187. flwr/server/__init__.py +2 -10
  188. flwr/server/app.py +579 -402
  189. flwr/server/client_manager.py +8 -6
  190. flwr/server/compat/app.py +6 -62
  191. flwr/server/compat/app_utils.py +14 -8
  192. flwr/server/compat/driver_client_proxy.py +25 -58
  193. flwr/server/compat/legacy_context.py +5 -4
  194. flwr/server/driver/__init__.py +2 -0
  195. flwr/server/driver/driver.py +36 -131
  196. flwr/server/driver/grpc_driver.py +217 -81
  197. flwr/server/driver/inmemory_driver.py +182 -0
  198. flwr/server/history.py +28 -29
  199. flwr/server/run_serverapp.py +15 -126
  200. flwr/server/server.py +50 -44
  201. flwr/server/server_app.py +59 -10
  202. flwr/server/serverapp/__init__.py +22 -0
  203. flwr/server/serverapp/app.py +256 -0
  204. flwr/server/serverapp_components.py +52 -0
  205. flwr/server/strategy/__init__.py +2 -2
  206. flwr/server/strategy/aggregate.py +37 -23
  207. flwr/server/strategy/bulyan.py +9 -9
  208. flwr/server/strategy/dp_adaptive_clipping.py +25 -25
  209. flwr/server/strategy/dp_fixed_clipping.py +23 -22
  210. flwr/server/strategy/dpfedavg_adaptive.py +8 -8
  211. flwr/server/strategy/dpfedavg_fixed.py +13 -12
  212. flwr/server/strategy/fault_tolerant_fedavg.py +11 -11
  213. flwr/server/strategy/fedadagrad.py +9 -9
  214. flwr/server/strategy/fedadam.py +20 -10
  215. flwr/server/strategy/fedavg.py +16 -16
  216. flwr/server/strategy/fedavg_android.py +17 -17
  217. flwr/server/strategy/fedavgm.py +9 -9
  218. flwr/server/strategy/fedmedian.py +5 -5
  219. flwr/server/strategy/fedopt.py +6 -6
  220. flwr/server/strategy/fedprox.py +7 -7
  221. flwr/server/strategy/fedtrimmedavg.py +8 -8
  222. flwr/server/strategy/fedxgb_bagging.py +12 -12
  223. flwr/server/strategy/fedxgb_cyclic.py +10 -10
  224. flwr/server/strategy/fedxgb_nn_avg.py +6 -6
  225. flwr/server/strategy/fedyogi.py +9 -9
  226. flwr/server/strategy/krum.py +9 -9
  227. flwr/server/strategy/qfedavg.py +16 -16
  228. flwr/server/strategy/strategy.py +10 -10
  229. flwr/server/superlink/driver/__init__.py +2 -2
  230. flwr/server/superlink/driver/serverappio_grpc.py +61 -0
  231. flwr/server/superlink/driver/serverappio_servicer.py +363 -0
  232. flwr/server/superlink/ffs/__init__.py +24 -0
  233. flwr/server/superlink/ffs/disk_ffs.py +108 -0
  234. flwr/server/superlink/ffs/ffs.py +79 -0
  235. flwr/server/superlink/ffs/ffs_factory.py +47 -0
  236. flwr/server/superlink/fleet/__init__.py +1 -1
  237. flwr/server/superlink/fleet/grpc_adapter/__init__.py +15 -0
  238. flwr/server/superlink/fleet/grpc_adapter/grpc_adapter_servicer.py +162 -0
  239. flwr/server/superlink/fleet/grpc_bidi/__init__.py +1 -1
  240. flwr/server/superlink/fleet/grpc_bidi/flower_service_servicer.py +4 -2
  241. flwr/server/superlink/fleet/grpc_bidi/grpc_bridge.py +3 -2
  242. flwr/server/superlink/fleet/grpc_bidi/grpc_client_proxy.py +1 -1
  243. flwr/server/superlink/fleet/grpc_bidi/grpc_server.py +5 -154
  244. flwr/server/superlink/fleet/grpc_rere/__init__.py +1 -1
  245. flwr/server/superlink/fleet/grpc_rere/fleet_servicer.py +120 -13
  246. flwr/server/superlink/fleet/grpc_rere/server_interceptor.py +228 -0
  247. flwr/server/superlink/fleet/message_handler/__init__.py +1 -1
  248. flwr/server/superlink/fleet/message_handler/message_handler.py +153 -9
  249. flwr/server/superlink/fleet/rest_rere/__init__.py +1 -1
  250. flwr/server/superlink/fleet/rest_rere/rest_api.py +119 -81
  251. flwr/server/superlink/fleet/vce/__init__.py +1 -0
  252. flwr/server/superlink/fleet/vce/backend/__init__.py +4 -4
  253. flwr/server/superlink/fleet/vce/backend/backend.py +8 -9
  254. flwr/server/superlink/fleet/vce/backend/raybackend.py +87 -68
  255. flwr/server/superlink/fleet/vce/vce_api.py +208 -146
  256. flwr/server/superlink/linkstate/__init__.py +28 -0
  257. flwr/server/superlink/linkstate/in_memory_linkstate.py +581 -0
  258. flwr/server/superlink/linkstate/linkstate.py +389 -0
  259. flwr/server/superlink/{state/state_factory.py → linkstate/linkstate_factory.py} +19 -10
  260. flwr/server/superlink/linkstate/sqlite_linkstate.py +1236 -0
  261. flwr/server/superlink/linkstate/utils.py +389 -0
  262. flwr/server/superlink/simulation/__init__.py +15 -0
  263. flwr/server/superlink/simulation/simulationio_grpc.py +65 -0
  264. flwr/server/superlink/simulation/simulationio_servicer.py +186 -0
  265. flwr/server/superlink/utils.py +65 -0
  266. flwr/server/typing.py +2 -0
  267. flwr/server/utils/__init__.py +1 -1
  268. flwr/server/utils/tensorboard.py +5 -5
  269. flwr/server/utils/validator.py +31 -11
  270. flwr/server/workflow/default_workflows.py +70 -26
  271. flwr/server/workflow/secure_aggregation/secagg_workflow.py +1 -0
  272. flwr/server/workflow/secure_aggregation/secaggplus_workflow.py +40 -27
  273. flwr/simulation/__init__.py +12 -5
  274. flwr/simulation/app.py +247 -315
  275. flwr/simulation/legacy_app.py +402 -0
  276. flwr/simulation/ray_transport/__init__.py +1 -1
  277. flwr/simulation/ray_transport/ray_actor.py +42 -67
  278. flwr/simulation/ray_transport/ray_client_proxy.py +37 -17
  279. flwr/simulation/ray_transport/utils.py +1 -0
  280. flwr/simulation/run_simulation.py +306 -163
  281. flwr/simulation/simulationio_connection.py +89 -0
  282. flwr/superexec/__init__.py +15 -0
  283. flwr/superexec/app.py +59 -0
  284. flwr/superexec/deployment.py +188 -0
  285. flwr/superexec/exec_grpc.py +80 -0
  286. flwr/superexec/exec_servicer.py +231 -0
  287. flwr/superexec/exec_user_auth_interceptor.py +101 -0
  288. flwr/superexec/executor.py +96 -0
  289. flwr/superexec/simulation.py +124 -0
  290. {flwr_nightly-1.8.0.dev20240315.dist-info → flwr_nightly-1.15.0.dev20250114.dist-info}/METADATA +33 -26
  291. flwr_nightly-1.15.0.dev20250114.dist-info/RECORD +328 -0
  292. flwr_nightly-1.15.0.dev20250114.dist-info/entry_points.txt +12 -0
  293. flwr/cli/flower_toml.py +0 -140
  294. flwr/cli/new/templates/app/flower.toml.tpl +0 -13
  295. flwr/cli/new/templates/app/requirements.numpy.txt.tpl +0 -2
  296. flwr/cli/new/templates/app/requirements.pytorch.txt.tpl +0 -4
  297. flwr/cli/new/templates/app/requirements.tensorflow.txt.tpl +0 -4
  298. flwr/client/node_state.py +0 -48
  299. flwr/client/node_state_tests.py +0 -65
  300. flwr/proto/driver_pb2.py +0 -44
  301. flwr/proto/driver_pb2_grpc.py +0 -169
  302. flwr/proto/driver_pb2_grpc.pyi +0 -66
  303. flwr/server/superlink/driver/driver_grpc.py +0 -54
  304. flwr/server/superlink/driver/driver_servicer.py +0 -129
  305. flwr/server/superlink/state/in_memory_state.py +0 -230
  306. flwr/server/superlink/state/sqlite_state.py +0 -630
  307. flwr/server/superlink/state/state.py +0 -154
  308. flwr_nightly-1.8.0.dev20240315.dist-info/RECORD +0 -211
  309. flwr_nightly-1.8.0.dev20240315.dist-info/entry_points.txt +0 -9
  310. {flwr_nightly-1.8.0.dev20240315.dist-info → flwr_nightly-1.15.0.dev20250114.dist-info}/LICENSE +0 -0
  311. {flwr_nightly-1.8.0.dev20240315.dist-info → flwr_nightly-1.15.0.dev20250114.dist-info}/WHEEL +0 -0
flwr/cli/install.py ADDED
@@ -0,0 +1,253 @@
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 command line interface `install` command."""
16
+
17
+
18
+ import hashlib
19
+ import shutil
20
+ import tempfile
21
+ import zipfile
22
+ from io import BytesIO
23
+ from pathlib import Path
24
+ from typing import IO, Annotated, Optional, Union
25
+
26
+ import typer
27
+
28
+ from flwr.common.config import get_flwr_dir, get_metadata_from_config
29
+ from flwr.common.constant import FAB_HASH_TRUNCATION
30
+
31
+ from .config_utils import load_and_validate
32
+ from .utils import get_sha256_hash
33
+
34
+
35
+ def install(
36
+ source: Annotated[
37
+ Optional[Path],
38
+ typer.Argument(metavar="source", help="The source FAB file to install."),
39
+ ] = None,
40
+ flwr_dir: Annotated[
41
+ Optional[Path],
42
+ typer.Option(help="The desired install path."),
43
+ ] = None,
44
+ ) -> None:
45
+ """Install a Flower App Bundle.
46
+
47
+ It can be ran with a single FAB file argument:
48
+
49
+ ``flwr install ./target_project.fab``
50
+
51
+ The target install directory can be specified with ``--flwr-dir``:
52
+
53
+ ``flwr install ./target_project.fab --flwr-dir ./docs/flwr``
54
+
55
+ This will install ``target_project`` to ``./docs/flwr/``. By default,
56
+ ``flwr-dir`` is equal to:
57
+
58
+ - ``$FLWR_HOME/`` if ``$FLWR_HOME`` is defined
59
+ - ``$XDG_DATA_HOME/.flwr/`` if ``$XDG_DATA_HOME`` is defined
60
+ - ``$HOME/.flwr/`` in all other cases
61
+ """
62
+ if source is None:
63
+ source = Path(typer.prompt("Enter the source FAB file"))
64
+
65
+ source = source.resolve()
66
+ if not source.exists() or not source.is_file():
67
+ typer.secho(
68
+ f"❌ The source {source} does not exist or is not a file.",
69
+ fg=typer.colors.RED,
70
+ bold=True,
71
+ )
72
+ raise typer.Exit(code=1)
73
+
74
+ if source.suffix != ".fab":
75
+ typer.secho(
76
+ f"❌ The source {source} is not a `.fab` file.",
77
+ fg=typer.colors.RED,
78
+ bold=True,
79
+ )
80
+ raise typer.Exit(code=1)
81
+
82
+ install_from_fab(source, flwr_dir)
83
+
84
+
85
+ def install_from_fab(
86
+ fab_file: Union[Path, bytes],
87
+ flwr_dir: Optional[Path],
88
+ skip_prompt: bool = False,
89
+ ) -> Path:
90
+ """Install from a FAB file after extracting and validating."""
91
+ fab_file_archive: Union[Path, IO[bytes]]
92
+ fab_name: Optional[str]
93
+ if isinstance(fab_file, bytes):
94
+ fab_file_archive = BytesIO(fab_file)
95
+ fab_hash = hashlib.sha256(fab_file).hexdigest()
96
+ fab_name = None
97
+ elif isinstance(fab_file, Path):
98
+ fab_file_archive = fab_file
99
+ fab_hash = hashlib.sha256(fab_file.read_bytes()).hexdigest()
100
+ fab_name = fab_file.stem
101
+ else:
102
+ raise ValueError("fab_file must be either a Path or bytes")
103
+
104
+ with tempfile.TemporaryDirectory() as tmpdir:
105
+ with zipfile.ZipFile(fab_file_archive, "r") as zipf:
106
+ zipf.extractall(tmpdir)
107
+ tmpdir_path = Path(tmpdir)
108
+ info_dir = tmpdir_path / ".info"
109
+ if not info_dir.exists():
110
+ typer.secho(
111
+ "❌ FAB file has incorrect format.",
112
+ fg=typer.colors.RED,
113
+ bold=True,
114
+ )
115
+ raise typer.Exit(code=1)
116
+
117
+ content_file = info_dir / "CONTENT"
118
+
119
+ if not content_file.exists() or not _verify_hashes(
120
+ content_file.read_text(), tmpdir_path
121
+ ):
122
+ typer.secho(
123
+ "❌ File hashes couldn't be verified.",
124
+ fg=typer.colors.RED,
125
+ bold=True,
126
+ )
127
+ raise typer.Exit(code=1)
128
+
129
+ shutil.rmtree(info_dir)
130
+
131
+ installed_path = validate_and_install(
132
+ tmpdir_path, fab_hash, fab_name, flwr_dir, skip_prompt
133
+ )
134
+
135
+ return installed_path
136
+
137
+
138
+ # pylint: disable=too-many-locals
139
+ def validate_and_install(
140
+ project_dir: Path,
141
+ fab_hash: str,
142
+ fab_name: Optional[str],
143
+ flwr_dir: Optional[Path],
144
+ skip_prompt: bool = False,
145
+ ) -> Path:
146
+ """Validate TOML files and install the project to the desired directory."""
147
+ config, _, _ = load_and_validate(project_dir / "pyproject.toml", check_module=False)
148
+
149
+ if config is None:
150
+ typer.secho(
151
+ "❌ Invalid config inside FAB file.",
152
+ fg=typer.colors.RED,
153
+ bold=True,
154
+ )
155
+ raise typer.Exit(code=1)
156
+
157
+ version, fab_id = get_metadata_from_config(config)
158
+ publisher, project_name = fab_id.split("/")
159
+ config_metadata = (publisher, project_name, version, fab_hash)
160
+
161
+ if fab_name:
162
+ _validate_fab_and_config_metadata(fab_name, config_metadata)
163
+
164
+ install_dir: Path = (
165
+ (get_flwr_dir() if not flwr_dir else flwr_dir)
166
+ / "apps"
167
+ / f"{publisher}.{project_name}.{version}.{fab_hash[:FAB_HASH_TRUNCATION]}"
168
+ )
169
+ if install_dir.exists():
170
+ if skip_prompt:
171
+ return install_dir
172
+ if not typer.confirm(
173
+ typer.style(
174
+ f"\n💬 {project_name} version {version} is already installed, "
175
+ "do you want to reinstall it?",
176
+ fg=typer.colors.MAGENTA,
177
+ bold=True,
178
+ )
179
+ ):
180
+ return install_dir
181
+
182
+ install_dir.mkdir(parents=True, exist_ok=True)
183
+
184
+ # Move contents from source directory
185
+ for item in project_dir.iterdir():
186
+ if item.is_dir():
187
+ shutil.copytree(item, install_dir / item.name, dirs_exist_ok=True)
188
+ else:
189
+ shutil.copy2(item, install_dir / item.name)
190
+
191
+ typer.secho(
192
+ f"🎊 Successfully installed {project_name} to {install_dir}.",
193
+ fg=typer.colors.GREEN,
194
+ bold=True,
195
+ )
196
+
197
+ return install_dir
198
+
199
+
200
+ def _verify_hashes(list_content: str, tmpdir: Path) -> bool:
201
+ """Verify file hashes based on the LIST content."""
202
+ for line in list_content.strip().split("\n"):
203
+ rel_path, hash_expected, _ = line.split(",")
204
+ file_path = tmpdir / rel_path
205
+ if not file_path.exists() or get_sha256_hash(file_path) != hash_expected:
206
+ return False
207
+ return True
208
+
209
+
210
+ def _validate_fab_and_config_metadata(
211
+ fab_name: str, config_metadata: tuple[str, str, str, str]
212
+ ) -> None:
213
+ """Validate metadata from the FAB filename and config."""
214
+ publisher, project_name, version, fab_hash = config_metadata
215
+
216
+ fab_name = fab_name.removesuffix(".fab")
217
+
218
+ fab_publisher, fab_project_name, fab_version, fab_shorthash = fab_name.split(".")
219
+ fab_version = fab_version.replace("-", ".")
220
+
221
+ # Check FAB filename format
222
+ if (
223
+ f"{fab_publisher}.{fab_project_name}.{fab_version}"
224
+ != f"{publisher}.{project_name}.{version}"
225
+ or len(fab_shorthash) != FAB_HASH_TRUNCATION # Verify hash length
226
+ ):
227
+ typer.secho(
228
+ "❌ FAB file has incorrect name. The file name must follow the format "
229
+ "`<publisher>.<project_name>.<version>.<8hexchars>.fab`.",
230
+ fg=typer.colors.RED,
231
+ bold=True,
232
+ )
233
+ raise typer.Exit(code=1)
234
+
235
+ # Verify hash is a valid hexadecimal
236
+ try:
237
+ _ = int(fab_shorthash, 16)
238
+ except Exception as e:
239
+ typer.secho(
240
+ f"❌ FAB file has an invalid hexadecimal string `{fab_shorthash}`.",
241
+ fg=typer.colors.RED,
242
+ bold=True,
243
+ )
244
+ raise typer.Exit(code=1) from e
245
+
246
+ # Verify shorthash matches
247
+ if fab_shorthash != fab_hash[:FAB_HASH_TRUNCATION]:
248
+ typer.secho(
249
+ "❌ The hash in the FAB file name does not match the hash of the FAB.",
250
+ fg=typer.colors.RED,
251
+ bold=True,
252
+ )
253
+ raise typer.Exit(code=1)
flwr/cli/log.py ADDED
@@ -0,0 +1,182 @@
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 command line interface `log` command."""
16
+
17
+
18
+ import time
19
+ from logging import DEBUG, ERROR, INFO
20
+ from pathlib import Path
21
+ from typing import Annotated, Any, Optional, cast
22
+
23
+ import grpc
24
+ import typer
25
+
26
+ from flwr.cli.config_utils import (
27
+ exit_if_no_address,
28
+ load_and_validate,
29
+ process_loaded_project_config,
30
+ validate_federation_in_project_config,
31
+ )
32
+ from flwr.common.constant import CONN_RECONNECT_INTERVAL, CONN_REFRESH_PERIOD
33
+ from flwr.common.logger import log as logger
34
+ from flwr.proto.exec_pb2 import StreamLogsRequest # pylint: disable=E0611
35
+ from flwr.proto.exec_pb2_grpc import ExecStub
36
+
37
+ from .utils import init_channel, try_obtain_cli_auth_plugin, unauthenticated_exc_handler
38
+
39
+
40
+ def start_stream(
41
+ run_id: int, channel: grpc.Channel, refresh_period: int = CONN_REFRESH_PERIOD
42
+ ) -> None:
43
+ """Start log streaming for a given run ID."""
44
+ stub = ExecStub(channel)
45
+ after_timestamp = 0.0
46
+ try:
47
+ logger(INFO, "Starting logstream for run_id `%s`", run_id)
48
+ while True:
49
+ after_timestamp = stream_logs(run_id, stub, refresh_period, after_timestamp)
50
+ time.sleep(CONN_RECONNECT_INTERVAL)
51
+ logger(DEBUG, "Reconnecting to logstream")
52
+ except KeyboardInterrupt:
53
+ logger(INFO, "Exiting logstream")
54
+ except grpc.RpcError as e:
55
+ # pylint: disable=E1101
56
+ if e.code() == grpc.StatusCode.NOT_FOUND:
57
+ logger(ERROR, "Invalid run_id `%s`, exiting", run_id)
58
+ if e.code() == grpc.StatusCode.CANCELLED:
59
+ pass
60
+ finally:
61
+ channel.close()
62
+
63
+
64
+ def stream_logs(
65
+ run_id: int, stub: ExecStub, duration: int, after_timestamp: float
66
+ ) -> float:
67
+ """Stream logs from the beginning of a run with connection refresh.
68
+
69
+ Parameters
70
+ ----------
71
+ run_id : int
72
+ The identifier of the run.
73
+ stub : ExecStub
74
+ The gRPC stub to interact with the Exec service.
75
+ duration : int
76
+ The timeout duration for each stream connection in seconds.
77
+ after_timestamp : float
78
+ The timestamp to start streaming logs from.
79
+
80
+ Returns
81
+ -------
82
+ float
83
+ The latest timestamp from the streamed logs or the provided `after_timestamp`
84
+ if no logs are returned.
85
+ """
86
+ req = StreamLogsRequest(run_id=run_id, after_timestamp=after_timestamp)
87
+
88
+ latest_timestamp = 0.0
89
+ res = None
90
+ try:
91
+ with unauthenticated_exc_handler():
92
+ for res in stub.StreamLogs(req, timeout=duration):
93
+ print(res.log_output, end="")
94
+ except grpc.RpcError as e:
95
+ # pylint: disable=E1101
96
+ if e.code() != grpc.StatusCode.DEADLINE_EXCEEDED:
97
+ raise e
98
+ finally:
99
+ if res is not None:
100
+ latest_timestamp = cast(float, res.latest_timestamp)
101
+
102
+ return max(latest_timestamp, after_timestamp)
103
+
104
+
105
+ def print_logs(run_id: int, channel: grpc.Channel, timeout: int) -> None:
106
+ """Print logs from the beginning of a run."""
107
+ stub = ExecStub(channel)
108
+ req = StreamLogsRequest(run_id=run_id)
109
+
110
+ try:
111
+ while True:
112
+ try:
113
+ with unauthenticated_exc_handler():
114
+ # Enforce timeout for graceful exit
115
+ for res in stub.StreamLogs(req, timeout=timeout):
116
+ print(res.log_output)
117
+ except grpc.RpcError as e:
118
+ # pylint: disable=E1101
119
+ if e.code() == grpc.StatusCode.DEADLINE_EXCEEDED:
120
+ break
121
+ if e.code() == grpc.StatusCode.NOT_FOUND:
122
+ logger(ERROR, "Invalid run_id `%s`, exiting", run_id)
123
+ break
124
+ if e.code() == grpc.StatusCode.CANCELLED:
125
+ break
126
+ except KeyboardInterrupt:
127
+ logger(DEBUG, "Stream interrupted by user")
128
+ finally:
129
+ channel.close()
130
+ logger(DEBUG, "Channel closed")
131
+
132
+
133
+ def log(
134
+ run_id: Annotated[
135
+ int,
136
+ typer.Argument(help="The Flower run ID to query"),
137
+ ],
138
+ app: Annotated[
139
+ Path,
140
+ typer.Argument(help="Path of the Flower project to run"),
141
+ ] = Path("."),
142
+ federation: Annotated[
143
+ Optional[str],
144
+ typer.Argument(help="Name of the federation to run the app on"),
145
+ ] = None,
146
+ stream: Annotated[
147
+ bool,
148
+ typer.Option(
149
+ "--stream/--show",
150
+ help="Flag to stream or print logs from the Flower run",
151
+ ),
152
+ ] = True,
153
+ ) -> None:
154
+ """Get logs from a Flower project run."""
155
+ typer.secho("Loading project configuration... ", fg=typer.colors.BLUE)
156
+
157
+ pyproject_path = app / "pyproject.toml" if app else None
158
+ config, errors, warnings = load_and_validate(path=pyproject_path)
159
+ config = process_loaded_project_config(config, errors, warnings)
160
+ federation, federation_config = validate_federation_in_project_config(
161
+ federation, config
162
+ )
163
+ exit_if_no_address(federation_config, "log")
164
+
165
+ _log_with_exec_api(app, federation, federation_config, run_id, stream)
166
+
167
+
168
+ def _log_with_exec_api(
169
+ app: Path,
170
+ federation: str,
171
+ federation_config: dict[str, Any],
172
+ run_id: int,
173
+ stream: bool,
174
+ ) -> None:
175
+ auth_plugin = try_obtain_cli_auth_plugin(app, federation)
176
+ channel = init_channel(app, federation_config, auth_plugin)
177
+
178
+ if stream:
179
+ start_stream(run_id, channel, CONN_REFRESH_PERIOD)
180
+ else:
181
+ logger(INFO, "Printing logstream for run_id `%s`", run_id)
182
+ print_logs(run_id, channel, timeout=5)
@@ -1,4 +1,4 @@
1
- # Copyright 2023 Flower Labs GmbH. All Rights Reserved.
1
+ # Copyright 2024 Flower Labs GmbH. All Rights Reserved.
2
2
  #
3
3
  # Licensed under the Apache License, Version 2.0 (the "License");
4
4
  # you may not use this file except in compliance with the License.
@@ -12,17 +12,11 @@
12
12
  # See the License for the specific language governing permissions and
13
13
  # limitations under the License.
14
14
  # ==============================================================================
15
- """Flower server state."""
15
+ """Flower command line interface `login` command."""
16
16
 
17
17
 
18
- from .in_memory_state import InMemoryState as InMemoryState
19
- from .sqlite_state import SqliteState as SqliteState
20
- from .state import State as State
21
- from .state_factory import StateFactory as StateFactory
18
+ from .login import login as login
22
19
 
23
20
  __all__ = [
24
- "InMemoryState",
25
- "SqliteState",
26
- "State",
27
- "StateFactory",
21
+ "login",
28
22
  ]
@@ -0,0 +1,88 @@
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 command line interface `login` command."""
16
+
17
+
18
+ from pathlib import Path
19
+ from typing import Annotated, Optional
20
+
21
+ import typer
22
+
23
+ from flwr.cli.config_utils import (
24
+ exit_if_no_address,
25
+ load_and_validate,
26
+ process_loaded_project_config,
27
+ validate_federation_in_project_config,
28
+ )
29
+ from flwr.common.typing import UserAuthLoginDetails
30
+ from flwr.proto.exec_pb2 import ( # pylint: disable=E0611
31
+ GetLoginDetailsRequest,
32
+ GetLoginDetailsResponse,
33
+ )
34
+ from flwr.proto.exec_pb2_grpc import ExecStub
35
+
36
+ from ..utils import init_channel, try_obtain_cli_auth_plugin
37
+
38
+
39
+ def login( # pylint: disable=R0914
40
+ app: Annotated[
41
+ Path,
42
+ typer.Argument(help="Path of the Flower App to run."),
43
+ ] = Path("."),
44
+ federation: Annotated[
45
+ Optional[str],
46
+ typer.Argument(help="Name of the federation to login into."),
47
+ ] = None,
48
+ ) -> None:
49
+ """Login to Flower SuperLink."""
50
+ typer.secho("Loading project configuration... ", fg=typer.colors.BLUE)
51
+
52
+ pyproject_path = app / "pyproject.toml" if app else None
53
+ config, errors, warnings = load_and_validate(path=pyproject_path)
54
+
55
+ config = process_loaded_project_config(config, errors, warnings)
56
+ federation, federation_config = validate_federation_in_project_config(
57
+ federation, config
58
+ )
59
+ exit_if_no_address(federation_config, "login")
60
+ channel = init_channel(app, federation_config, None)
61
+ stub = ExecStub(channel)
62
+
63
+ login_request = GetLoginDetailsRequest()
64
+ login_response: GetLoginDetailsResponse = stub.GetLoginDetails(login_request)
65
+
66
+ # Get the auth plugin
67
+ auth_type = login_response.auth_type
68
+ auth_plugin = try_obtain_cli_auth_plugin(app, federation, auth_type)
69
+ if auth_plugin is None:
70
+ typer.secho(
71
+ f'❌ Authentication type "{auth_type}" not found',
72
+ fg=typer.colors.RED,
73
+ bold=True,
74
+ )
75
+ raise typer.Exit(code=1)
76
+
77
+ # Login
78
+ details = UserAuthLoginDetails(
79
+ auth_type=login_response.auth_type,
80
+ device_code=login_response.device_code,
81
+ verification_uri_complete=login_response.verification_uri_complete,
82
+ expires_in=login_response.expires_in,
83
+ interval=login_response.interval,
84
+ )
85
+ credentials = auth_plugin.login(details, stub)
86
+
87
+ # Store the tokens
88
+ auth_plugin.store_tokens(credentials)