flwr-nightly 1.8.0.dev20240314__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.dev20240314.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.dev20240314.dist-info/RECORD +0 -211
  309. flwr_nightly-1.8.0.dev20240314.dist-info/entry_points.txt +0 -9
  310. {flwr_nightly-1.8.0.dev20240314.dist-info → flwr_nightly-1.15.0.dev20250114.dist-info}/LICENSE +0 -0
  311. {flwr_nightly-1.8.0.dev20240314.dist-info → flwr_nightly-1.15.0.dev20250114.dist-info}/WHEEL +0 -0
flwr/cli/app.py CHANGED
@@ -14,11 +14,18 @@
14
14
  # ==============================================================================
15
15
  """Flower command line interface."""
16
16
 
17
+
17
18
  import typer
19
+ from typer.main import get_command
18
20
 
19
- from .example import example
21
+ from .build import build
22
+ from .install import install
23
+ from .log import log
24
+ from .login import login
25
+ from .ls import ls
20
26
  from .new import new
21
27
  from .run import run
28
+ from .stop import stop
22
29
 
23
30
  app = typer.Typer(
24
31
  help=typer.style(
@@ -30,8 +37,15 @@ app = typer.Typer(
30
37
  )
31
38
 
32
39
  app.command()(new)
33
- app.command()(example)
34
40
  app.command()(run)
41
+ app.command()(build)
42
+ app.command()(install)
43
+ app.command()(log)
44
+ app.command()(ls)
45
+ app.command()(stop)
46
+ app.command()(login)
47
+
48
+ typer_click_object = get_command(app)
35
49
 
36
50
  if __name__ == "__main__":
37
51
  app()
flwr/cli/build.py ADDED
@@ -0,0 +1,181 @@
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 `build` command."""
16
+
17
+
18
+ import hashlib
19
+ import os
20
+ import shutil
21
+ import tempfile
22
+ import zipfile
23
+ from pathlib import Path
24
+ from typing import Annotated, Any, Optional, Union
25
+
26
+ import pathspec
27
+ import tomli_w
28
+ import typer
29
+
30
+ from flwr.common.constant import FAB_ALLOWED_EXTENSIONS, FAB_DATE, FAB_HASH_TRUNCATION
31
+
32
+ from .config_utils import load_and_validate
33
+ from .utils import is_valid_project_name
34
+
35
+
36
+ def write_to_zip(
37
+ zipfile_obj: zipfile.ZipFile, filename: str, contents: Union[bytes, str]
38
+ ) -> zipfile.ZipFile:
39
+ """Set a fixed date and write contents to a zip file."""
40
+ zip_info = zipfile.ZipInfo(filename)
41
+ zip_info.date_time = FAB_DATE
42
+ zipfile_obj.writestr(zip_info, contents)
43
+ return zipfile_obj
44
+
45
+
46
+ def get_fab_filename(conf: dict[str, Any], fab_hash: str) -> str:
47
+ """Get the FAB filename based on the given config and FAB hash."""
48
+ publisher = conf["tool"]["flwr"]["app"]["publisher"]
49
+ name = conf["project"]["name"]
50
+ version = conf["project"]["version"].replace(".", "-")
51
+ fab_hash_truncated = fab_hash[:FAB_HASH_TRUNCATION]
52
+ return f"{publisher}.{name}.{version}.{fab_hash_truncated}.fab"
53
+
54
+
55
+ # pylint: disable=too-many-locals, too-many-statements
56
+ def build(
57
+ app: Annotated[
58
+ Optional[Path],
59
+ typer.Option(help="Path of the Flower App to bundle into a FAB"),
60
+ ] = None,
61
+ ) -> tuple[str, str]:
62
+ """Build a Flower App into a Flower App Bundle (FAB).
63
+
64
+ You can run ``flwr build`` without any arguments to bundle the app located in the
65
+ current directory. Alternatively, you can you can specify a path using the ``--app``
66
+ option to bundle an app located at the provided path. For example:
67
+
68
+ ``flwr build --app ./apps/flower-hello-world``.
69
+ """
70
+ if app is None:
71
+ app = Path.cwd()
72
+
73
+ app = app.resolve()
74
+ if not app.is_dir():
75
+ typer.secho(
76
+ f"❌ The path {app} is not a valid path to a Flower app.",
77
+ fg=typer.colors.RED,
78
+ bold=True,
79
+ )
80
+ raise typer.Exit(code=1)
81
+
82
+ if not is_valid_project_name(app.name):
83
+ typer.secho(
84
+ f"❌ The project name {app.name} is invalid, "
85
+ "a valid project name must start with a letter, "
86
+ "and can only contain letters, digits, and hyphens.",
87
+ fg=typer.colors.RED,
88
+ bold=True,
89
+ )
90
+ raise typer.Exit(code=1)
91
+
92
+ conf, errors, warnings = load_and_validate(app / "pyproject.toml")
93
+ if conf is None:
94
+ typer.secho(
95
+ "Project configuration could not be loaded.\npyproject.toml is invalid:\n"
96
+ + "\n".join([f"- {line}" for line in errors]),
97
+ fg=typer.colors.RED,
98
+ bold=True,
99
+ )
100
+ raise typer.Exit(code=1)
101
+
102
+ if warnings:
103
+ typer.secho(
104
+ "Project configuration is missing the following "
105
+ "recommended properties:\n" + "\n".join([f"- {line}" for line in warnings]),
106
+ fg=typer.colors.RED,
107
+ bold=True,
108
+ )
109
+
110
+ # Load .gitignore rules if present
111
+ ignore_spec = _load_gitignore(app)
112
+
113
+ list_file_content = ""
114
+
115
+ # Remove the 'federations' field from 'tool.flwr' if it exists
116
+ if (
117
+ "tool" in conf
118
+ and "flwr" in conf["tool"]
119
+ and "federations" in conf["tool"]["flwr"]
120
+ ):
121
+ del conf["tool"]["flwr"]["federations"]
122
+
123
+ toml_contents = tomli_w.dumps(conf)
124
+
125
+ with tempfile.NamedTemporaryFile(suffix=".zip", delete=False) as temp_file:
126
+ temp_filename = temp_file.name
127
+
128
+ with zipfile.ZipFile(temp_filename, "w", zipfile.ZIP_DEFLATED) as fab_file:
129
+ write_to_zip(fab_file, "pyproject.toml", toml_contents)
130
+
131
+ # Continue with adding other files
132
+ all_files = [
133
+ f
134
+ for f in app.rglob("*")
135
+ if not ignore_spec.match_file(f)
136
+ and f.name != temp_filename
137
+ and f.suffix in FAB_ALLOWED_EXTENSIONS
138
+ and f.name != "pyproject.toml" # Exclude the original pyproject.toml
139
+ ]
140
+
141
+ for file_path in all_files:
142
+ # Read the file content manually
143
+ with open(file_path, "rb") as f:
144
+ file_contents = f.read()
145
+
146
+ archive_path = file_path.relative_to(app)
147
+ write_to_zip(fab_file, str(archive_path), file_contents)
148
+
149
+ # Calculate file info
150
+ sha256_hash = hashlib.sha256(file_contents).hexdigest()
151
+ file_size_bits = os.path.getsize(file_path) * 8 # size in bits
152
+ list_file_content += f"{archive_path},{sha256_hash},{file_size_bits}\n"
153
+
154
+ # Add CONTENT and CONTENT.jwt to the zip file
155
+ write_to_zip(fab_file, ".info/CONTENT", list_file_content)
156
+
157
+ # Get hash of FAB file
158
+ content = Path(temp_filename).read_bytes()
159
+ fab_hash = hashlib.sha256(content).hexdigest()
160
+
161
+ # Set the name of the zip file
162
+ fab_filename = get_fab_filename(conf, fab_hash)
163
+
164
+ # Once the temporary zip file is created, rename it to the final filename
165
+ shutil.move(temp_filename, fab_filename)
166
+
167
+ typer.secho(
168
+ f"🎊 Successfully built {fab_filename}", fg=typer.colors.GREEN, bold=True
169
+ )
170
+
171
+ return fab_filename, fab_hash
172
+
173
+
174
+ def _load_gitignore(app: Path) -> pathspec.PathSpec:
175
+ """Load and parse .gitignore file, returning a pathspec."""
176
+ gitignore_path = app / ".gitignore"
177
+ patterns = ["__pycache__/"] # Default pattern
178
+ if gitignore_path.exists():
179
+ with open(gitignore_path, encoding="UTF-8") as file:
180
+ patterns.extend(file.readlines())
181
+ return pathspec.PathSpec.from_lines("gitwildmatch", patterns)
@@ -0,0 +1,90 @@
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 run interceptor."""
16
+
17
+
18
+ from typing import Any, Callable, Union
19
+
20
+ import grpc
21
+
22
+ from flwr.common.auth_plugin import CliAuthPlugin
23
+ from flwr.proto.exec_pb2 import ( # pylint: disable=E0611
24
+ StartRunRequest,
25
+ StreamLogsRequest,
26
+ )
27
+
28
+ Request = Union[
29
+ StartRunRequest,
30
+ StreamLogsRequest,
31
+ ]
32
+
33
+
34
+ class CliUserAuthInterceptor(
35
+ grpc.UnaryUnaryClientInterceptor, grpc.UnaryStreamClientInterceptor # type: ignore
36
+ ):
37
+ """CLI interceptor for user authentication."""
38
+
39
+ def __init__(self, auth_plugin: CliAuthPlugin):
40
+ self.auth_plugin = auth_plugin
41
+
42
+ def _authenticated_call(
43
+ self,
44
+ continuation: Callable[[Any, Any], Any],
45
+ client_call_details: grpc.ClientCallDetails,
46
+ request: Request,
47
+ ) -> grpc.Call:
48
+ """Send and receive tokens via metadata."""
49
+ new_metadata = self.auth_plugin.write_tokens_to_metadata(
50
+ client_call_details.metadata or []
51
+ )
52
+
53
+ details = client_call_details._replace(metadata=new_metadata)
54
+
55
+ response = continuation(details, request)
56
+ if response.initial_metadata():
57
+ credentials = self.auth_plugin.read_tokens_from_metadata(
58
+ response.initial_metadata()
59
+ )
60
+ # The metadata contains tokens only if they have been refreshed
61
+ if credentials is not None:
62
+ self.auth_plugin.store_tokens(credentials)
63
+
64
+ return response
65
+
66
+ def intercept_unary_unary(
67
+ self,
68
+ continuation: Callable[[Any, Any], Any],
69
+ client_call_details: grpc.ClientCallDetails,
70
+ request: Request,
71
+ ) -> grpc.Call:
72
+ """Intercept a unary-unary call for user authentication.
73
+
74
+ This method intercepts a unary-unary RPC call initiated from the CLI and adds
75
+ the required authentication tokens to the RPC metadata.
76
+ """
77
+ return self._authenticated_call(continuation, client_call_details, request)
78
+
79
+ def intercept_unary_stream(
80
+ self,
81
+ continuation: Callable[[Any, Any], Any],
82
+ client_call_details: grpc.ClientCallDetails,
83
+ request: Request,
84
+ ) -> grpc.Call:
85
+ """Intercept a unary-stream call for user authentication.
86
+
87
+ This method intercepts a unary-stream RPC call initiated from the CLI and adds
88
+ the required authentication tokens to the RPC metadata.
89
+ """
90
+ return self._authenticated_call(continuation, client_call_details, request)
@@ -0,0 +1,343 @@
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
+ """Utility to validate the `pyproject.toml` file."""
16
+
17
+
18
+ import zipfile
19
+ from io import BytesIO
20
+ from pathlib import Path
21
+ from typing import IO, Any, Optional, Union, get_args
22
+
23
+ import tomli
24
+ import typer
25
+
26
+ from flwr.common import object_ref
27
+ from flwr.common.typing import UserConfigValue
28
+
29
+
30
+ def get_fab_config(fab_file: Union[Path, bytes]) -> dict[str, Any]:
31
+ """Extract the config from a FAB file or path.
32
+
33
+ Parameters
34
+ ----------
35
+ fab_file : Union[Path, bytes]
36
+ The Flower App Bundle file to validate and extract the metadata from.
37
+ It can either be a path to the file or the file itself as bytes.
38
+
39
+ Returns
40
+ -------
41
+ Dict[str, Any]
42
+ The `config` of the given Flower App Bundle.
43
+ """
44
+ fab_file_archive: Union[Path, IO[bytes]]
45
+ if isinstance(fab_file, bytes):
46
+ fab_file_archive = BytesIO(fab_file)
47
+ elif isinstance(fab_file, Path):
48
+ fab_file_archive = fab_file
49
+ else:
50
+ raise ValueError("fab_file must be either a Path or bytes")
51
+
52
+ with zipfile.ZipFile(fab_file_archive, "r") as zipf:
53
+ with zipf.open("pyproject.toml") as file:
54
+ toml_content = file.read().decode("utf-8")
55
+
56
+ conf = load_from_string(toml_content)
57
+ if conf is None:
58
+ raise ValueError("Invalid TOML content in pyproject.toml")
59
+
60
+ is_valid, errors, _ = validate(conf, check_module=False)
61
+ if not is_valid:
62
+ raise ValueError(errors)
63
+
64
+ return conf
65
+
66
+
67
+ def get_fab_metadata(fab_file: Union[Path, bytes]) -> tuple[str, str]:
68
+ """Extract the fab_id and the fab_version from a FAB file or path.
69
+
70
+ Parameters
71
+ ----------
72
+ fab_file : Union[Path, bytes]
73
+ The Flower App Bundle file to validate and extract the metadata from.
74
+ It can either be a path to the file or the file itself as bytes.
75
+
76
+ Returns
77
+ -------
78
+ Tuple[str, str]
79
+ The `fab_id` and `fab_version` of the given Flower App Bundle.
80
+ """
81
+ conf = get_fab_config(fab_file)
82
+
83
+ return (
84
+ f"{conf['tool']['flwr']['app']['publisher']}/{conf['project']['name']}",
85
+ conf["project"]["version"],
86
+ )
87
+
88
+
89
+ def load_and_validate(
90
+ path: Optional[Path] = None,
91
+ check_module: bool = True,
92
+ ) -> tuple[Optional[dict[str, Any]], list[str], list[str]]:
93
+ """Load and validate pyproject.toml as dict.
94
+
95
+ Parameters
96
+ ----------
97
+ path : Optional[Path] (default: None)
98
+ The path of the Flower App config file to load. By default it
99
+ will try to use `pyproject.toml` inside the current directory.
100
+ check_module: bool (default: True)
101
+ Whether the validity of the Python module should be checked.
102
+ This requires the project to be installed in the currently
103
+ running environment. True by default.
104
+
105
+ Returns
106
+ -------
107
+ Tuple[Optional[config], List[str], List[str]]
108
+ A tuple with the optional config in case it exists and is valid
109
+ and associated errors and warnings.
110
+ """
111
+ if path is None:
112
+ path = Path.cwd() / "pyproject.toml"
113
+
114
+ config = load(path)
115
+
116
+ if config is None:
117
+ errors = [
118
+ "Project configuration could not be loaded. "
119
+ "`pyproject.toml` does not exist."
120
+ ]
121
+ return (None, errors, [])
122
+
123
+ is_valid, errors, warnings = validate(config, check_module, path.parent)
124
+
125
+ if not is_valid:
126
+ return (None, errors, warnings)
127
+
128
+ return (config, errors, warnings)
129
+
130
+
131
+ def load(toml_path: Path) -> Optional[dict[str, Any]]:
132
+ """Load pyproject.toml and return as dict."""
133
+ if not toml_path.is_file():
134
+ return None
135
+
136
+ with toml_path.open(encoding="utf-8") as toml_file:
137
+ return load_from_string(toml_file.read())
138
+
139
+
140
+ def _validate_run_config(config_dict: dict[str, Any], errors: list[str]) -> None:
141
+ for key, value in config_dict.items():
142
+ if isinstance(value, dict):
143
+ _validate_run_config(config_dict[key], errors)
144
+ elif not isinstance(value, get_args(UserConfigValue)):
145
+ raise ValueError(
146
+ f"The value for key {key} needs to be of type `int`, `float`, "
147
+ "`bool, `str`, or a `dict` of those.",
148
+ )
149
+
150
+
151
+ # pylint: disable=too-many-branches
152
+ def validate_fields(config: dict[str, Any]) -> tuple[bool, list[str], list[str]]:
153
+ """Validate pyproject.toml fields."""
154
+ errors = []
155
+ warnings = []
156
+
157
+ if "project" not in config:
158
+ errors.append("Missing [project] section")
159
+ else:
160
+ if "name" not in config["project"]:
161
+ errors.append('Property "name" missing in [project]')
162
+ if "version" not in config["project"]:
163
+ errors.append('Property "version" missing in [project]')
164
+ if "description" not in config["project"]:
165
+ warnings.append('Recommended property "description" missing in [project]')
166
+ if "license" not in config["project"]:
167
+ warnings.append('Recommended property "license" missing in [project]')
168
+ if "authors" not in config["project"]:
169
+ warnings.append('Recommended property "authors" missing in [project]')
170
+
171
+ if (
172
+ "tool" not in config
173
+ or "flwr" not in config["tool"]
174
+ or "app" not in config["tool"]["flwr"]
175
+ ):
176
+ errors.append("Missing [tool.flwr.app] section")
177
+ else:
178
+ if "publisher" not in config["tool"]["flwr"]["app"]:
179
+ errors.append('Property "publisher" missing in [tool.flwr.app]')
180
+ if "config" in config["tool"]["flwr"]["app"]:
181
+ _validate_run_config(config["tool"]["flwr"]["app"]["config"], errors)
182
+ if "components" not in config["tool"]["flwr"]["app"]:
183
+ errors.append("Missing [tool.flwr.app.components] section")
184
+ else:
185
+ if "serverapp" not in config["tool"]["flwr"]["app"]["components"]:
186
+ errors.append(
187
+ 'Property "serverapp" missing in [tool.flwr.app.components]'
188
+ )
189
+ if "clientapp" not in config["tool"]["flwr"]["app"]["components"]:
190
+ errors.append(
191
+ 'Property "clientapp" missing in [tool.flwr.app.components]'
192
+ )
193
+
194
+ return len(errors) == 0, errors, warnings
195
+
196
+
197
+ def validate(
198
+ config: dict[str, Any],
199
+ check_module: bool = True,
200
+ project_dir: Optional[Union[str, Path]] = None,
201
+ ) -> tuple[bool, list[str], list[str]]:
202
+ """Validate pyproject.toml."""
203
+ is_valid, errors, warnings = validate_fields(config)
204
+
205
+ if not is_valid:
206
+ return False, errors, warnings
207
+
208
+ # Validate serverapp
209
+ serverapp_ref = config["tool"]["flwr"]["app"]["components"]["serverapp"]
210
+ is_valid, reason = object_ref.validate(serverapp_ref, check_module, project_dir)
211
+
212
+ if not is_valid and isinstance(reason, str):
213
+ return False, [reason], []
214
+
215
+ # Validate clientapp
216
+ clientapp_ref = config["tool"]["flwr"]["app"]["components"]["clientapp"]
217
+ is_valid, reason = object_ref.validate(clientapp_ref, check_module, project_dir)
218
+
219
+ if not is_valid and isinstance(reason, str):
220
+ return False, [reason], []
221
+
222
+ return True, [], []
223
+
224
+
225
+ def load_from_string(toml_content: str) -> Optional[dict[str, Any]]:
226
+ """Load TOML content from a string and return as dict."""
227
+ try:
228
+ data = tomli.loads(toml_content)
229
+ return data
230
+ except tomli.TOMLDecodeError:
231
+ return None
232
+
233
+
234
+ def process_loaded_project_config(
235
+ config: Union[dict[str, Any], None], errors: list[str], warnings: list[str]
236
+ ) -> dict[str, Any]:
237
+ """Process and return the loaded project configuration.
238
+
239
+ This function handles errors and warnings from the `load_and_validate` function,
240
+ exits on critical issues, and returns the validated configuration.
241
+ """
242
+ if config is None:
243
+ typer.secho(
244
+ "Project configuration could not be loaded.\n"
245
+ "pyproject.toml is invalid:\n"
246
+ + "\n".join([f"- {line}" for line in errors]),
247
+ fg=typer.colors.RED,
248
+ bold=True,
249
+ )
250
+ raise typer.Exit(code=1)
251
+
252
+ if warnings:
253
+ typer.secho(
254
+ "Project configuration is missing the following "
255
+ "recommended properties:\n" + "\n".join([f"- {line}" for line in warnings]),
256
+ fg=typer.colors.RED,
257
+ bold=True,
258
+ )
259
+
260
+ typer.secho("Success", fg=typer.colors.GREEN)
261
+
262
+ return config
263
+
264
+
265
+ def validate_federation_in_project_config(
266
+ federation: Optional[str], config: dict[str, Any]
267
+ ) -> tuple[str, dict[str, Any]]:
268
+ """Validate the federation name in the Flower project configuration."""
269
+ federation = federation or config["tool"]["flwr"]["federations"].get("default")
270
+
271
+ if federation is None:
272
+ typer.secho(
273
+ "❌ No federation name was provided and the project's `pyproject.toml` "
274
+ "doesn't declare a default federation (with an Exec API address or an "
275
+ "`options.num-supernodes` value).",
276
+ fg=typer.colors.RED,
277
+ bold=True,
278
+ )
279
+ raise typer.Exit(code=1)
280
+
281
+ # Validate the federation exists in the configuration
282
+ federation_config = config["tool"]["flwr"]["federations"].get(federation)
283
+ if federation_config is None:
284
+ available_feds = {
285
+ fed for fed in config["tool"]["flwr"]["federations"] if fed != "default"
286
+ }
287
+ typer.secho(
288
+ f"❌ There is no `{federation}` federation declared in the "
289
+ "`pyproject.toml`.\n The following federations were found:\n\n"
290
+ + "\n".join(available_feds),
291
+ fg=typer.colors.RED,
292
+ bold=True,
293
+ )
294
+ raise typer.Exit(code=1)
295
+
296
+ return federation, federation_config
297
+
298
+
299
+ def validate_certificate_in_federation_config(
300
+ app: Path, federation_config: dict[str, Any]
301
+ ) -> tuple[bool, Optional[bytes]]:
302
+ """Validate the certificates in the Flower project configuration."""
303
+ insecure_str = federation_config.get("insecure")
304
+ if root_certificates := federation_config.get("root-certificates"):
305
+ root_certificates_bytes = (app / root_certificates).read_bytes()
306
+ if insecure := bool(insecure_str):
307
+ typer.secho(
308
+ "❌ `root_certificates` were provided but the `insecure` parameter "
309
+ "is set to `True`.",
310
+ fg=typer.colors.RED,
311
+ bold=True,
312
+ )
313
+ raise typer.Exit(code=1)
314
+ else:
315
+ root_certificates_bytes = None
316
+ if insecure_str is None:
317
+ typer.secho(
318
+ "❌ To disable TLS, set `insecure = true` in `pyproject.toml`.",
319
+ fg=typer.colors.RED,
320
+ bold=True,
321
+ )
322
+ raise typer.Exit(code=1)
323
+ if not (insecure := bool(insecure_str)):
324
+ typer.secho(
325
+ "❌ No certificate were given yet `insecure` is set to `False`.",
326
+ fg=typer.colors.RED,
327
+ bold=True,
328
+ )
329
+ raise typer.Exit(code=1)
330
+
331
+ return insecure, root_certificates_bytes
332
+
333
+
334
+ def exit_if_no_address(federation_config: dict[str, Any], cmd: str) -> None:
335
+ """Exit if the provided federation_config has no "address" key."""
336
+ if "address" not in federation_config:
337
+ typer.secho(
338
+ f"❌ `flwr {cmd}` currently works with a SuperLink. Ensure that the correct"
339
+ "SuperLink (Exec API) address is provided in `pyproject.toml`.",
340
+ fg=typer.colors.RED,
341
+ bold=True,
342
+ )
343
+ raise typer.Exit(code=1)
flwr/cli/example.py CHANGED
@@ -14,6 +14,7 @@
14
14
  # ==============================================================================
15
15
  """Flower command line interface `example` command."""
16
16
 
17
+
17
18
  import json
18
19
  import os
19
20
  import subprocess
@@ -39,7 +40,9 @@ def example() -> None:
39
40
  with urllib.request.urlopen(examples_directory_url) as res:
40
41
  data = json.load(res)
41
42
  example_names = [
42
- item["path"] for item in data["tree"] if item["path"] not in [".gitignore"]
43
+ item["path"]
44
+ for item in data["tree"]
45
+ if item["path"] not in [".gitignore", "doc"]
43
46
  ]
44
47
 
45
48
  example_name = prompt_options(