aspera-cli 4.29.1 → 4.30.0

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.
Files changed (264) hide show
  1. checksums.yaml +4 -4
  2. checksums.yaml.gz.sig +4 -4
  3. data/CHANGELOG.md +119 -0
  4. data/CONTRIBUTING.md +8 -1
  5. data/README.md +2 -0
  6. data/TODO.md +4 -5
  7. data/bin/asession +2 -2
  8. data/docs/README.md +616 -86
  9. data/docs/test-mcp-with-ai.md +4 -0
  10. data/lib/aspera/agent/base.rb +62 -6
  11. data/lib/aspera/agent/factory.rb +127 -20
  12. data/lib/aspera/ascp/data_repository.rb +71 -0
  13. data/lib/aspera/ascp/installation.rb +16 -11
  14. data/lib/aspera/ascp/log_analyzer/lines.rb +4 -4
  15. data/lib/aspera/ascp/log_analyzer/log_file.rb +5 -3
  16. data/lib/aspera/ascp/log_analyzer/records.rb +11 -6
  17. data/lib/aspera/ascp/log_analyzer.rb +43 -18
  18. data/lib/aspera/ascp/log_locations.rb +2 -2
  19. data/lib/aspera/assert.rb +8 -0
  20. data/lib/aspera/bundle_registry.rb +528 -0
  21. data/lib/aspera/cli/argument.rb +110 -0
  22. data/lib/aspera/cli/bool_value.rb +41 -0
  23. data/lib/aspera/cli/bootstrapper.rb +31 -24
  24. data/lib/aspera/cli/command/mount.rb +53 -0
  25. data/lib/aspera/cli/command/registry.rb +434 -0
  26. data/lib/aspera/cli/command.rb +95 -0
  27. data/lib/aspera/cli/command_line.rb +91 -91
  28. data/lib/aspera/cli/complete.rb +22 -0
  29. data/lib/aspera/cli/completion_actions.rb +28 -26
  30. data/lib/aspera/cli/context.rb +29 -6
  31. data/lib/aspera/cli/error.rb +39 -0
  32. data/lib/aspera/cli/extended_value.rb +25 -4
  33. data/lib/aspera/cli/formatter.rb +8 -8
  34. data/lib/aspera/cli/hints.rb +17 -52
  35. data/lib/aspera/cli/http.rb +17 -12
  36. data/lib/aspera/cli/mailer.rb +7 -24
  37. data/lib/aspera/cli/mcp/tool.rb +10 -2
  38. data/lib/aspera/cli/option/declarator.rb +80 -0
  39. data/lib/aspera/cli/option/registry.rb +74 -0
  40. data/lib/aspera/cli/option/source.rb +38 -0
  41. data/lib/aspera/cli/option/type.rb +37 -0
  42. data/lib/aspera/cli/option/value.rb +376 -0
  43. data/lib/aspera/cli/option.rb +78 -0
  44. data/lib/aspera/cli/options.schema.yaml +28 -783
  45. data/lib/aspera/cli/parser.rb +73 -41
  46. data/lib/aspera/cli/plugins/base.rb +122 -42
  47. data/lib/aspera/cli/plugins/basic_auth.rb +13 -2
  48. data/lib/aspera/cli/plugins/config.rb +101 -167
  49. data/lib/aspera/cli/plugins/factory.rb +139 -43
  50. data/lib/aspera/cli/plugins/mcp.rb +61 -54
  51. data/lib/aspera/cli/plugins/oauth.rb +19 -6
  52. data/lib/aspera/cli/poll.rb +14 -20
  53. data/lib/aspera/cli/preset_actions.rb +11 -3
  54. data/lib/aspera/cli/preset_manager.rb +16 -6
  55. data/lib/aspera/cli/result.rb +2 -2
  56. data/lib/aspera/cli/runner.rb +71 -99
  57. data/lib/aspera/cli/secret_finder.rb +1 -1
  58. data/lib/aspera/cli/security.rb +102 -4
  59. data/lib/aspera/{preview/terminal.rb → cli/terminal_image.rb} +93 -94
  60. data/lib/aspera/cli/vault_manager.rb +3 -3
  61. data/lib/aspera/cli/version.rb +1 -1
  62. data/lib/aspera/cli/wizard.rb +9 -3
  63. data/lib/aspera/coverage.rb +1 -2
  64. data/lib/aspera/line_logger.rb +35 -6
  65. data/lib/aspera/log.rb +3 -2
  66. data/lib/aspera/oauth/client/base.rb +19 -1
  67. data/lib/aspera/oauth/client/factory.rb +1 -7
  68. data/lib/aspera/plugin.schema.yaml +178 -0
  69. data/lib/aspera/plugins/alee/api.rb +25 -0
  70. data/lib/aspera/{cli/plugins/alee.rb → plugins/alee/commands.rb} +10 -8
  71. data/lib/aspera/plugins/alee/plugin.yaml +3 -0
  72. data/lib/aspera/plugins/aoc/admin_resources.rb +148 -0
  73. data/lib/aspera/plugins/aoc/api.rb +783 -0
  74. data/lib/aspera/{cli/plugins/aoc.rb → plugins/aoc/commands.rb} +404 -330
  75. data/lib/aspera/plugins/aoc/graphql.rb +45 -0
  76. data/lib/aspera/plugins/aoc/plugin.yaml +31 -0
  77. data/lib/aspera/{schema → plugins/aoc/schemas}/IBM Aspera on Cloud API-0.2.6-enhanced.yaml +15042 -7076
  78. data/lib/aspera/plugins/aoc/schemas/options.yaml +47 -0
  79. data/lib/aspera/plugins/ats/api.rb +51 -0
  80. data/lib/aspera/{cli/plugins/ats.rb → plugins/ats/commands.rb} +33 -33
  81. data/lib/aspera/plugins/ats/plugin.yaml +6 -0
  82. data/lib/aspera/plugins/connect/agent.rb +199 -0
  83. data/lib/aspera/plugins/connect/plugin.yaml +11 -0
  84. data/lib/aspera/plugins/connect/schemas/agent_options.yaml +6 -0
  85. data/lib/aspera/{cli/plugins/console.rb → plugins/console/commands.rb} +41 -33
  86. data/lib/aspera/plugins/console/plugin.yaml +8 -0
  87. data/lib/aspera/plugins/cos/api.rb +114 -0
  88. data/lib/aspera/{cli/plugins/cos.rb → plugins/cos/commands.rb} +19 -16
  89. data/lib/aspera/plugins/cos/plugin.yaml +9 -0
  90. data/lib/aspera/plugins/cos/schemas/options.yaml +30 -0
  91. data/lib/aspera/plugins/desktop/agent.rb +165 -0
  92. data/lib/aspera/plugins/desktop/plugin.yaml +11 -0
  93. data/lib/aspera/plugins/desktop/schemas/agent_options.yaml +6 -0
  94. data/lib/aspera/plugins/direct/agent.rb +518 -0
  95. data/lib/aspera/plugins/direct/plugin.yaml +11 -0
  96. data/lib/aspera/plugins/direct/schemas/agent_options.yaml +86 -0
  97. data/lib/aspera/plugins/faspex4/gateway_options.rb +18 -0
  98. data/lib/aspera/plugins/faspex4/gw_servlet.rb +122 -0
  99. data/lib/aspera/plugins/faspex4/plugin.yaml +7 -0
  100. data/lib/aspera/plugins/faspex4/schemas/options.yaml +57 -0
  101. data/lib/aspera/plugins/faspex5/api.rb +269 -0
  102. data/lib/aspera/{cli/plugins/faspex5.rb → plugins/faspex5/commands.rb} +152 -114
  103. data/lib/aspera/plugins/faspex5/faspex4_post_proc_servlet.rb +241 -0
  104. data/lib/aspera/plugins/faspex5/plugin.yaml +14 -0
  105. data/lib/aspera/{schema → plugins/faspex5/schemas}/IBM Aspera Faspex API-5.0-enhanced.yaml +279 -76
  106. data/lib/aspera/plugins/faspex5/schemas/options.yaml +87 -0
  107. data/lib/aspera/{cli/plugins/faspio.rb → plugins/faspio/commands.rb} +11 -7
  108. data/lib/aspera/plugins/faspio/plugin.yaml +8 -0
  109. data/lib/aspera/{schema → plugins/faspio/schemas}/IBM Aspera faspio Gateway API-1.0.0-enhanced.yaml +4 -2
  110. data/lib/aspera/plugins/httpgw/agent.rb +126 -0
  111. data/lib/aspera/plugins/httpgw/api.rb +411 -0
  112. data/lib/aspera/{cli/plugins/httpgw.rb → plugins/httpgw/commands.rb} +9 -9
  113. data/lib/aspera/plugins/httpgw/plugin.yaml +12 -0
  114. data/lib/aspera/plugins/httpgw/schemas/agent_options.yaml +24 -0
  115. data/lib/aspera/plugins/node/agent.rb +184 -0
  116. data/lib/aspera/plugins/node/api.rb +699 -0
  117. data/lib/aspera/{cli/plugins/node.rb → plugins/node/commands.rb} +166 -141
  118. data/lib/aspera/plugins/node/emulator.rb +774 -0
  119. data/lib/aspera/plugins/node/plugin.yaml +20 -0
  120. data/lib/aspera/plugins/node/schemas/agent_options.yaml +20 -0
  121. data/lib/aspera/plugins/node/schemas/options.yaml +190 -0
  122. data/lib/aspera/{cli/plugins/orchestrator.rb → plugins/orchestrator/commands.rb} +139 -110
  123. data/lib/aspera/plugins/orchestrator/plugin.yaml +34 -0
  124. data/lib/aspera/{schema → plugins/orchestrator/schemas}/IBM Aspera Orchestrator API-v1-enhanced.yaml +486 -16
  125. data/lib/aspera/plugins/orchestrator/schemas/options.yaml +143 -0
  126. data/lib/aspera/plugins/orchestrator/workflow_checker.rb +692 -0
  127. data/lib/aspera/{cli/plugins/preview.rb → plugins/preview/commands.rb} +53 -51
  128. data/lib/aspera/plugins/preview/file_types.rb +121 -0
  129. data/lib/aspera/plugins/preview/generator.rb +350 -0
  130. data/lib/aspera/plugins/preview/plugin.yaml +12 -0
  131. data/lib/aspera/{preview/options.schema.yaml → plugins/preview/schemas/options.yaml} +1 -1
  132. data/lib/aspera/plugins/preview/utils.rb +213 -0
  133. data/lib/aspera/plugins/server/ascmd.rb +374 -0
  134. data/lib/aspera/{cli/plugins/server.rb → plugins/server/commands.rb} +48 -32
  135. data/lib/aspera/plugins/server/plugin.yaml +9 -0
  136. data/lib/aspera/plugins/server/schemas/options.yaml +30 -0
  137. data/lib/aspera/{cli/plugins/shares.rb → plugins/shares/commands.rb} +29 -21
  138. data/lib/aspera/plugins/shares/plugin.yaml +10 -0
  139. data/lib/aspera/plugins/shares/shares_web.rb +97 -0
  140. data/lib/aspera/plugins/transferd/agent.rb +258 -0
  141. data/lib/aspera/plugins/transferd/api.rb +180 -0
  142. data/lib/aspera/plugins/transferd/client.rb +67 -0
  143. data/lib/aspera/{cli/plugins/transferd.rb → plugins/transferd/commands.rb} +43 -42
  144. data/lib/aspera/plugins/transferd/config_commands.rb +38 -0
  145. data/lib/aspera/plugins/transferd/plugin.yaml +27 -0
  146. data/lib/aspera/plugins/transferd/product.rb +146 -0
  147. data/lib/aspera/plugins/transferd/schemas/agent_options.yaml +31 -0
  148. data/lib/aspera/plugins/transferd/schemas/options.yaml +80 -0
  149. data/lib/aspera/plugins/transferd/service.rb +617 -0
  150. data/lib/aspera/plugins/xfer/ascp_actions.rb +131 -0
  151. data/lib/aspera/plugins/xfer/ascp_logs_actions.rb +198 -0
  152. data/lib/aspera/plugins/xfer/async_transfer_store.rb +131 -0
  153. data/lib/aspera/plugins/xfer/config_commands.rb +119 -0
  154. data/lib/aspera/plugins/xfer/helper.rb +19 -0
  155. data/lib/aspera/plugins/xfer/plugin.yaml +42 -0
  156. data/lib/aspera/plugins/xfer/schemas/agent_extension.schema.yaml +26 -0
  157. data/lib/aspera/plugins/xfer/schemas/options.yaml +125 -0
  158. data/lib/aspera/plugins/xfer/sync_actions.rb +253 -0
  159. data/lib/aspera/plugins/xfer/transfer_actions.rb +176 -0
  160. data/lib/aspera/plugins/xfer/transfer_agent.rb +505 -0
  161. data/lib/aspera/products/cli_v3.rb +34 -0
  162. data/lib/aspera/products/connect.rb +1 -1
  163. data/lib/aspera/products/drive.rb +29 -0
  164. data/lib/aspera/products/hsts.rb +34 -0
  165. data/lib/aspera/products/transferd.rb +25 -3
  166. data/lib/aspera/products.rb +54 -0
  167. data/lib/aspera/prompt.rb +184 -0
  168. data/lib/aspera/proxy_auto_config.rb +3 -3
  169. data/lib/aspera/rest/aspera_errors.rb +4 -38
  170. data/lib/aspera/rest/error_analyzer.rb +6 -2
  171. data/lib/aspera/rest/list.rb +4 -5
  172. data/lib/aspera/schema/reader.rb +15 -0
  173. data/lib/aspera/schema/registry.rb +239 -45
  174. data/lib/aspera/schema/validator.rb +63 -17
  175. data/lib/aspera/sealed_hash.rb +4 -0
  176. data/lib/aspera/secret/hider.rb +159 -24
  177. data/lib/aspera/secret/reference.rb +8 -0
  178. data/lib/aspera/secret/resolver.rb +8 -4
  179. data/lib/aspera/secret/store/base.rb +10 -9
  180. data/lib/aspera/secret/store/encrypted_hash.rb +6 -6
  181. data/lib/aspera/secret/store/hashicorp_vault.rb +3 -3
  182. data/lib/aspera/secret/store/keeper.rb +2 -2
  183. data/lib/aspera/secret/store/macos_security.rb +2 -3
  184. data/lib/aspera/secret/store/one_password_api.rb +2 -2
  185. data/lib/aspera/secret/store/one_password_cli.rb +3 -3
  186. data/lib/aspera/secret/store/secret_service.rb +2 -2
  187. data/lib/aspera/ssl.rb +3 -3
  188. data/lib/aspera/standard_input.rb +20 -0
  189. data/lib/aspera/{schema → sync}/async_tables.yaml +1 -1
  190. data/lib/aspera/sync/database.rb +7 -0
  191. data/lib/aspera/sync/log_parser.rb +138 -0
  192. data/lib/aspera/sync/operations.rb +59 -34
  193. data/lib/aspera/transfer/command_line_builder.rb +248 -0
  194. data/lib/aspera/transfer/command_line_converter.rb +37 -0
  195. data/lib/aspera/transfer/faux_file.rb +2 -2
  196. data/lib/aspera/transfer/parameters.rb +9 -10
  197. data/lib/aspera/transfer/spec.rb +28 -1
  198. data/lib/aspera/transfer/spec.schema.yaml +30 -5
  199. data/lib/aspera/units/decimal.rb +1 -1
  200. data/lib/aspera/units/timestamp.rb +84 -0
  201. data/lib/aspera/uri_reader.rb +2 -2
  202. data/lib/aspera/web_auth/paste.rb +2 -2
  203. data/lib/aspera/web_server_simple.rb +10 -4
  204. data.tar.gz.sig +0 -0
  205. metadata +137 -80
  206. metadata.gz.sig +0 -0
  207. data/lib/aspera/agent/connect.rb +0 -188
  208. data/lib/aspera/agent/desktop.rb +0 -154
  209. data/lib/aspera/agent/direct.rb +0 -496
  210. data/lib/aspera/agent/httpgw.rb +0 -100
  211. data/lib/aspera/agent/node.rb +0 -166
  212. data/lib/aspera/agent/transferd.rb +0 -341
  213. data/lib/aspera/api/alee.rb +0 -19
  214. data/lib/aspera/api/aoc.rb +0 -776
  215. data/lib/aspera/api/ats.rb +0 -49
  216. data/lib/aspera/api/cos_node.rb +0 -107
  217. data/lib/aspera/api/faspex.rb +0 -258
  218. data/lib/aspera/api/httpgw.rb +0 -409
  219. data/lib/aspera/api/node.rb +0 -684
  220. data/lib/aspera/ascmd.rb +0 -248
  221. data/lib/aspera/cli/ascp_actions.rb +0 -113
  222. data/lib/aspera/cli/ascp_logs_actions.rb +0 -188
  223. data/lib/aspera/cli/async_transfer_store.rb +0 -129
  224. data/lib/aspera/cli/command_registry.rb +0 -371
  225. data/lib/aspera/cli/command_spec.rb +0 -273
  226. data/lib/aspera/cli/option_declarator.rb +0 -74
  227. data/lib/aspera/cli/option_registry.rb +0 -72
  228. data/lib/aspera/cli/option_types.rb +0 -120
  229. data/lib/aspera/cli/option_value.rb +0 -345
  230. data/lib/aspera/cli/prompt.rb +0 -186
  231. data/lib/aspera/cli/sync_actions.rb +0 -181
  232. data/lib/aspera/cli/transfer_actions.rb +0 -98
  233. data/lib/aspera/cli/transfer_agent.rb +0 -348
  234. data/lib/aspera/command_line_builder.rb +0 -244
  235. data/lib/aspera/command_line_converter.rb +0 -35
  236. data/lib/aspera/data_repository.rb +0 -69
  237. data/lib/aspera/faspex_gw.rb +0 -172
  238. data/lib/aspera/faspex_postproc.rb +0 -237
  239. data/lib/aspera/graphql.rb +0 -41
  240. data/lib/aspera/node_emulator.rb +0 -758
  241. data/lib/aspera/oauth/client/shares_web.rb +0 -94
  242. data/lib/aspera/orchestrator_workflow_checker.rb +0 -688
  243. data/lib/aspera/preview/file_types.rb +0 -119
  244. data/lib/aspera/preview/generator.rb +0 -345
  245. data/lib/aspera/preview/utils.rb +0 -211
  246. data/lib/aspera/products/other.rb +0 -92
  247. data/lib/aspera/products/transferd_service.rb +0 -610
  248. /data/lib/aspera/{data → ascp/data}/1 +0 -0
  249. /data/lib/aspera/{data → ascp/data}/2 +0 -0
  250. /data/lib/aspera/{data → ascp/data}/3 +0 -0
  251. /data/lib/aspera/{data → ascp/data}/4 +0 -0
  252. /data/lib/aspera/{data → ascp/data}/5 +0 -0
  253. /data/lib/aspera/{data → ascp/data}/6 +0 -0
  254. /data/lib/aspera/{api → plugins/aoc}/queries/bss_subscription_account.graphql +0 -0
  255. /data/lib/aspera/{api → plugins/aoc}/queries/bss_subscription_usage.graphql +0 -0
  256. /data/lib/aspera/{schema → plugins/aoc/schemas}/IBM Aspera on Cloud Automation API-1.0.5-enhanced.yaml +0 -0
  257. /data/lib/aspera/{schema → plugins/console/schemas}/IBM Aspera Console-enhanced.yaml +0 -0
  258. /data/lib/aspera/{schema → plugins/node/schemas}/IBM Aspera Node API-4.4.6.yaml +0 -0
  259. /data/lib/aspera/{preview → plugins/preview}/image_error.png +0 -0
  260. /data/lib/aspera/{preview → plugins/preview}/video_error.png +0 -0
  261. /data/lib/aspera/{schema → plugins/shares/schemas}/IBM_Aspera_Shares.yaml +0 -0
  262. /data/lib/{transferd_pb.rb → aspera/plugins/transferd/grpc/transferd_pb.rb} +0 -0
  263. /data/lib/{transferd_services_pb.rb → aspera/plugins/transferd/grpc/transferd_services_pb.rb} +0 -0
  264. /data/lib/aspera/{schema → plugins/transferd/schemas}/transferd-config.schema.json +0 -0
@@ -1,758 +0,0 @@
1
- # frozen_string_literal: true
2
-
3
- # SPDX-FileCopyrightText: IBM Corp.
4
- # SPDX-License-Identifier: Apache-2.0
5
-
6
- require_relative 'assert'
7
- require_relative 'ascp/installation'
8
- require_relative 'agent/transferd'
9
- require_relative 'transfer/spec'
10
- require_relative 'transfer/error'
11
- require_relative 'secret/hider'
12
- require_relative 'string_ext'
13
- require_relative 'log'
14
- require_relative 'servlet_helpers'
15
- require 'webrick'
16
- require 'etc'
17
- require 'securerandom'
18
- require 'json'
19
- require 'time'
20
-
21
- module Aspera
22
- # Node API transfers executed by transferd.
23
- # Only transfers started through the emulator are known (kept in memory).
24
- class NodeEmulator
25
- # transferd status → Node API transfer status
26
- STATUS = {
27
- UNKNOWN_STATUS: 'waiting',
28
- QUEUED: 'waiting',
29
- RUNNING: 'running',
30
- COMPLETED: 'completed',
31
- FAILED: 'failed',
32
- ORPHANED: 'failed',
33
- CANCELED: 'canceled',
34
- PAUSED: 'paused'
35
- }.freeze
36
- # transferd statuses after which no event is received
37
- TERMINAL = %i[COMPLETED FAILED CANCELED ORPHANED].freeze
38
- # Node API statuses of active transfers and sessions
39
- ACTIVE = %w[waiting running].freeze
40
- # transferd session status (lowercase) → Node API, others are only lowercased
41
- SESSION_STATUS = {'draft' => 'waiting'}.freeze
42
- # transferd file status (lowercase) → Node API, others are only lowercased
43
- FILE_STATUS = {'transferring' => 'running', 'finished' => 'completed'}.freeze
44
- # transferd field → Node API field, when not the snake case of it (`nil`: ignored)
45
- TRANSFER_OVERRIDES = {'averageRateKbps' => 'avg_rate_kbps', 'errorDescription' => 'error_desc'}.freeze
46
- SESSION_OVERRIDES = {'id' => nil, 'sessionId' => 'id'}.freeze
47
- FILE_OVERRIDES = {'fileId' => 'id', 'errorDescription' => 'error_desc', 'fileType' => 'type', 'fileChecksumType' => 'checksum_type'}.freeze
48
- # Node API fields taken as is from transferd (after renaming)
49
- TRANSFER_FIELDS = %w[bytes_transferred bytes_written bytes_lost avg_rate_kbps files_completed directories_completed elapsed_usec].freeze
50
- SESSION_FIELDS = %w[
51
- id client_node_id server_node_id client_ip_address server_ip_address start_time_usec end_time_usec elapsed_usec
52
- bytes_transferred bytes_written bytes_lost files_completed directories_completed
53
- target_rate_kbps min_rate_kbps calc_rate_kbps network_delay_usec error_code error_desc
54
- ].freeze
55
- FILE_FIELDS = %w[id path start_time_usec elapsed_usec error_code error_desc size type checksum_type checksum start_byte bytes_written session_id].freeze
56
- # Node API session `source_statistics` field → transferd session field
57
- SOURCE_STATISTICS = {
58
- 'args_scan_attempted' => 'arg_scans_attempted',
59
- 'args_scan_completed' => 'arg_scans_completed',
60
- 'paths_scan_attempted' => 'source_paths_scan_attempted',
61
- 'paths_scan_failed' => 'source_paths_scan_failed',
62
- 'paths_scan_excluded' => 'source_paths_scan_excluded',
63
- 'files_scan_completed' => 'source_paths_scan_completed',
64
- 'dirs_scan_completed' => 'dir_scans_completed',
65
- 'dirs_xfer_attempted' => 'dir_creates_attempted',
66
- 'dirs_xfer_fail' => 'dir_creates_failed',
67
- 'files_xfer_attempted' => 'transfers_attempted',
68
- 'files_xfer_fail' => 'transfers_failed',
69
- 'files_xfer_noxfer' => 'transfers_skipped'
70
- }.freeze
71
- # Node API `precalc` field → transferd session field
72
- PRECALC = {
73
- 'bytes_expected' => 'pre_transfer_bytes',
74
- 'files_expected' => 'pre_transfer_files',
75
- 'directories_expected' => 'pre_transfer_dirs',
76
- 'files_special' => 'pre_transfer_special'
77
- }.freeze
78
- # transferd fills fields `*TimeUsec` (except `elapsedUsec`) with milliseconds: values below are not microseconds
79
- MAX_MSEC = 10**14
80
- # Max wait for the first event of a new transfer
81
- START_TIMEOUT_SEC = 10
82
- # `File.ftype` → Node API item type, others are unchanged
83
- FILE_TYPES = {'link' => 'symbolic_link'}.freeze
84
- # Node API node information not provided by transferd
85
- # The emulator has no access key, AEJ, watch folder, sync, file id API (gen4), `files/page` or file operations
86
- INFO_STATIC = {
87
- 'aej_status' => 'disconnected',
88
- 'async_reporting' => 'no',
89
- 'transfer_activity_reporting' => 'no',
90
- 'acls' => [],
91
- 'access_key_configuration_capabilities' => {'transfer' => [], 'server' => []},
92
- 'capabilities' => [
93
- {'name' => 'sync', 'value' => false},
94
- {'name' => 'watchfolder', 'value' => false},
95
- {'name' => 'symbolic_links', 'value' => false},
96
- {'name' => 'move_file', 'value' => false},
97
- {'name' => 'move_directory', 'value' => false},
98
- {'name' => 'filelock', 'value' => false},
99
- {'name' => 'ssh_fingerprint', 'value' => false},
100
- {'name' => 'page', 'value' => false},
101
- {'name' => 'auto_delete', 'value' => false}
102
- ],
103
- 'settings' => [
104
- {'name' => 'content_protection_required', 'value' => false},
105
- {'name' => 'content_protection_strong_pass_required', 'value' => false},
106
- {'name' => 'filelock_restriction', 'value' => 'none'},
107
- {'name' => 'ssh_fingerprint', 'value' => nil},
108
- {'name' => 'wss_enabled', 'value' => false},
109
- {'name' => 'wss_port', 'value' => 443}
110
- ]
111
- }.freeze
112
- private_constant :STATUS, :TERMINAL, :ACTIVE, :SESSION_STATUS, :FILE_STATUS,
113
- :TRANSFER_OVERRIDES, :SESSION_OVERRIDES, :FILE_OVERRIDES, :TRANSFER_FIELDS, :SESSION_FIELDS, :FILE_FIELDS,
114
- :SOURCE_STATISTICS, :PRECALC, :MAX_MSEC, :START_TIMEOUT_SEC, :FILE_TYPES, :INFO_STATIC
115
-
116
- class << self
117
- # Convert a transferd transfer status to a Node API status
118
- # @param status [Symbol] transferd `TransferStatus`
119
- # @return [String] Node API transfer status
120
- def node_status(status)
121
- STATUS.fetch(status, 'waiting')
122
- end
123
-
124
- # Convert a transferd message to a hash with Node API field names
125
- # @param message [Google::Protobuf::AbstractMessage] transferd message
126
- # @param overrides [Hash] field name → Node API name (`nil`: ignored)
127
- # @return [Hash] all fields (including default values), keys in snake case, time stamps in microseconds
128
- def message_to_hash(message, overrides)
129
- message.class.descriptor.each_with_object({}) do |field, hash|
130
- key = overrides.fetch(field.name) { field.name.capital_to_snake }
131
- next if key.nil?
132
- value = message[field.name]
133
- value *= 1000 if key.end_with?('_time_usec') && value.positive? && value < MAX_MSEC
134
- hash[key] = value
135
- end
136
- end
137
-
138
- # Update a store entry with a transferd event
139
- # @param entry [Hash] store entry
140
- # @param response [Transferd::Api::TransferResponse] transferd event
141
- def update_entry(entry, response)
142
- entry[:status] = response.status
143
- entry[:info] = response.transferInfo unless response.transferInfo.nil?
144
- session = response.sessionInfo
145
- entry[:sessions][session.sessionId] = session unless session.nil? || session.sessionId.empty?
146
- # event ARG_STOP has a file without id
147
- file = response.fileInfo
148
- entry[:files][file.fileId] = file unless file.nil? || file.fileId.empty?
149
- entry[:error] = response.error.description unless response.error.nil? || response.error.description.empty?
150
- # session information keeps the initial rates, the ascp management message has the current ones
151
- entry[:rates][session.sessionId] = management_rates(response.message) if response.transferEvent.eql?(:RATE_MODIFICATION) && entry[:sessions].key?(session&.sessionId)
152
- end
153
-
154
- # Build a Node API transfer from a store entry
155
- # @param id [String] transfer id
156
- # @param entry [Hash] store entry
157
- # @param node_id [String] node id of the emulator
158
- # @return [Hash] Node API transfer (`transferResponseSessionSpec`)
159
- def transfer_to_node(id, entry, node_id: '')
160
- info = message_to_hash(entry[:info] || ::Transferd::Api::TransferInfo.new, TRANSFER_OVERRIDES)
161
- terminal = TERMINAL.include?(entry[:status])
162
- retry_timeout = xfer_retry(entry[:start_spec])
163
- sessions = entry[:sessions].map { |session_id, session| session_to_node(session, retry_timeout: retry_timeout, node_id: node_id).merge(entry[:rates].fetch(session_id, {})) }
164
- error_desc = info['error_desc'].strip
165
- error_desc = entry[:error].to_s if error_desc.empty?
166
- precalc = PRECALC.keys.to_h { |field| [field, sessions.sum { |session| session['precalc'][field] }] }
167
- info.slice(*TRANSFER_FIELDS).merge(
168
- 'id' => id,
169
- 'status' => node_status(entry[:status]),
170
- 'start_spec' => entry[:start_spec],
171
- 'sessions' => sessions,
172
- # transferd does not provide the start time of the transfer
173
- 'start_time_usec' => sessions.map { |session| session['start_time_usec'] }.select(&:positive?).min || 0,
174
- 'end_time_usec' => terminal ? info['end_time_usec'] : 0,
175
- 'error_code' => info['error_code'].to_i,
176
- 'error_desc' => error_desc,
177
- 'precalc' => precalc.merge(
178
- 'enabled' => sessions.any? { |session| session['precalc']['enabled'] },
179
- 'status' => precalc_status(precalc['bytes_expected'], terminal)
180
- ),
181
- 'files' => entry[:files].values.map { |file| file_to_node(file) }
182
- )
183
- end
184
-
185
- # Convert a transferd session to a Node API session
186
- # @param session [Transferd::Api::SessionTransferInformation]
187
- # @param retry_timeout [Integer] from the transfer spec
188
- # @param node_id [String] node id of the emulator
189
- # @return [Hash] Node API session (`transferResponseSessions`)
190
- def session_to_node(session, retry_timeout: 0, node_id: '')
191
- source = message_to_hash(session, SESSION_OVERRIDES)
192
- status = session.status.downcase
193
- status = SESSION_STATUS.fetch(status, status)
194
- result = source.slice(*SESSION_FIELDS)
195
- # transferd provides the address of the remote side only: the server
196
- result['server_ip_address'] = source['remote_address'] if result['server_ip_address'].empty?
197
- # transferd provides the node id of the remote side only: the local side is the emulator
198
- result['client_node_id'] = node_id if result['client_node_id'].empty?
199
- precalc = PRECALC.transform_values { |field| source[field] }
200
- result.merge(
201
- 'status' => status,
202
- 'retry_count' => 0,
203
- 'retry_timeout' => retry_timeout,
204
- 'stalled' => false,
205
- 'avg_rate_kbps' => source['elapsed_usec'].positive? ? (source['bytes_transferred'] * 8000.0 / source['elapsed_usec']).round(2) : 0,
206
- 'source_statistics' => SOURCE_STATISTICS.transform_values { |field| source[field] },
207
- 'precalc' => precalc.merge(
208
- 'enabled' => session.precalc.casecmp?('yes'),
209
- 'status' => precalc_status(precalc['bytes_expected'], !ACTIVE.include?(status))
210
- )
211
- )
212
- end
213
-
214
- # Convert a transferd file to a Node API file
215
- # @param file [Transferd::Api::FileTransferInformation]
216
- # @return [Hash] Node API file (`fileMetadata`)
217
- def file_to_node(file)
218
- result = message_to_hash(file, FILE_OVERRIDES).slice(*FILE_FIELDS)
219
- status = file.status.downcase
220
- result['status'] = FILE_STATUS.fetch(status, status)
221
- terminal = !result['status'].eql?('running') && result['start_time_usec'].positive?
222
- result['end_time_usec'] = terminal ? result['start_time_usec'] + result['elapsed_usec'] : 0
223
- result
224
- end
225
-
226
- # Build Node API node information from transferd instance information
227
- # @param info [Transferd::Api::InstanceInfo]
228
- # @param node_id [String] node id of the emulator
229
- # @param cluster_id [String] cluster id of the emulator
230
- # @param docroot [String] real path of the docroot
231
- # @param transfer_user [String] system user executing transfers
232
- # @return [Hash] Node API node information (`info-get-200`)
233
- def info_to_node(info, node_id:, cluster_id:, docroot:, transfer_user:)
234
- ascp = info.asperaInfo.find { |binary| binary.asperaBinary.eql?('ascp') } || ::Transferd::Api::AsperaInfo.new
235
- license = info.licenseInfo || ::Transferd::Api::LicenseInfo.new
236
- {
237
- 'application' => 'node',
238
- # without build id
239
- 'version' => ascp.asperaVersion.sub(/ .*$/, ''),
240
- 'current_time' => Time.now.utc.iso8601(0),
241
- 'license_expiration_date' => license.license[%r{<expiration_date>([^<]*)</expiration_date>}, 1].to_s,
242
- 'license_max_rate' => license.maxRate,
243
- 'os' => ascp.operatingSystem,
244
- 'node_id' => node_id,
245
- 'cluster_id' => cluster_id,
246
- 'transfer_user' => transfer_user,
247
- 'docroot' => "file:///#{docroot}"
248
- }.merge(INFO_STATIC)
249
- end
250
-
251
- private
252
-
253
- # Extract the current rates from an ascp management message
254
- # @param message [String] ascp management message of event `RATE_MODIFICATION` (JSON)
255
- # @return [Hash] Node API session rates found in the message
256
- def management_rates(message)
257
- management = JSON.parse(message)
258
- {'target_rate_kbps' => management['Rate'], 'min_rate_kbps' => management['MinRate']}.compact.transform_values(&:to_i)
259
- rescue JSON::ParserError
260
- {}
261
- end
262
-
263
- # Compute the status of the pre-calculation of the transfer size
264
- # @param bytes_expected [Integer] size of the transfer, 0 if not known yet
265
- # @param terminal [Boolean] `true` if the transfer or session has ended
266
- # @return [String] `ready` when the size is known, else `pending`
267
- def precalc_status(bytes_expected, terminal)
268
- bytes_expected.positive? || terminal ? 'ready' : 'pending'
269
- end
270
-
271
- # Get the retry timeout from the tags of the transfer spec
272
- # @param start_spec [Hash] transfer spec
273
- # @return [Integer] retry timeout set by `Agent::Node`, or 0
274
- def xfer_retry(start_spec)
275
- reserved = start_spec['tags'][Transfer::Spec::TAG_RESERVED] if start_spec['tags'].is_a?(Hash)
276
- reserved.is_a?(Hash) ? reserved['xfer_retry'].to_i : 0
277
- end
278
- end
279
-
280
- # Create an emulator, start a transferd daemon if no client is given
281
- # @param docroot [String, nil] folder of the node files, default: current folder
282
- # @param transfer_client [Transferd::Api::TransferService::Stub, nil] gRPC client, default: start a transferd daemon
283
- # @param retention_sec [Integer] time a transfer is kept after it ended (CLI default in schema)
284
- def initialize(retention_sec:, docroot: nil, transfer_client: nil)
285
- Aspera.assert(retention_sec.is_a?(Integer) && retention_sec.positive?) { "retention_sec must be a positive integer: #{retention_sec.inspect}" }
286
- # paths of browse and local paths of transfers are relative to it
287
- @docroot = File.realpath(docroot || Dir.pwd)
288
- # the daemon is stopped at exit by the agent
289
- @transfer_client = transfer_client || Agent::Transferd.new.transfer_client
290
- @retention_sec = retention_sec
291
- # transfer id → store entry: `start_spec` (secrets hidden), last `status`, last `info`, `sessions` by id, `files` by id, current `rates` by session id, `error`,
292
- # `ended` (monotonic time of the end), accessed with `store`
293
- @transfers = {}
294
- # WEBrick serves each request in a thread, monitoring runs in threads
295
- @mutex = Mutex.new
296
- # identifiers of the simulated node, in node information and in sessions
297
- @node_id = SecureRandom.uuid
298
- @cluster_id = SecureRandom.uuid
299
- # transferd runs as the user of the emulator
300
- @transfer_user = Etc.getpwuid(::Process.euid)&.name || Etc.getlogin.to_s
301
- end
302
-
303
- # Get the node information
304
- # @return [Hash] Node API node information, from transferd
305
- def info
306
- response = @transfer_client.get_info(::Transferd::Api::InstanceInfoRequest.new)
307
- Log.dump(:get_info_response, response.to_h, level: :trace2)
308
- Aspera.assert(response.error.nil? || response.error.description.empty?, type: RuntimeError) { response.error.description }
309
- self.class.info_to_node(response.info || ::Transferd::Api::InstanceInfo.new, node_id: @node_id, cluster_id: @cluster_id, docroot: @docroot, transfer_user: @transfer_user)
310
- end
311
-
312
- # List a folder of the docroot
313
- # @param path [String] folder to list, relative to the docroot
314
- # @param skip [Integer] number of items to skip (paging)
315
- # @param count [Integer] max number of items returned (paging)
316
- # @return [Hash] Node API folder content, paths relative to the docroot
317
- def browse(path, skip: 0, count: nil)
318
- folder_path = real_path(path)
319
- # symbolic links shall not lead out of the docroot
320
- Aspera.assert(in_docroot?(File.realpath(folder_path))) { "Path outside docroot: #{path}" }
321
- Aspera.assert(File.directory?(folder_path)) { "Not a folder: #{path}" }
322
- folder_virtual = virtual_path(folder_path)
323
- # stable order for paging: only the items of the page are read
324
- names = Dir.children(folder_path).sort
325
- items = names.drop(skip).first(count || names.length).map do |name|
326
- item_path = File.join(folder_path, name)
327
- # a symbolic link is not followed
328
- item = item_info(item_path, File.join(folder_virtual, name), File.lstat(item_path))
329
- case item['type']
330
- when 'file' then item['partial_file'] = false
331
- when 'symbolic_link' then item['target'] = link_target(item_path)
332
- when 'unknown' then item['note'] = 'File type could not be determined'
333
- end
334
- item
335
- end
336
- {
337
- 'self' => item_info(folder_path, folder_virtual, File.stat(folder_path)),
338
- 'items' => items,
339
- 'item_count' => items.length,
340
- 'total_count' => names.length
341
- }
342
- end
343
-
344
- # Start a transfer, and monitor it in a thread until terminated
345
- # @param transfer_spec [Hash] transfer spec, local paths relative to the docroot (modified)
346
- # @return [String] transfer id
347
- def start(transfer_spec)
348
- Transfer::Spec.fix_transferd_resume_policy(transfer_spec)
349
- # copy without secrets, returned in transfer `start_spec`
350
- start_spec = Secret::Hider.instance.hidden_copy(transfer_spec)
351
- Log.dump(:start_spec, start_spec)
352
- request = ::Transferd::Api::TransferRequest.new(
353
- transferType: ::Transferd::Api::TransferType::FILE_REGULAR,
354
- config: ::Transferd::Api::TransferConfig.new,
355
- transferSpec: apply_docroot(transfer_spec).to_json
356
- )
357
- first_event = Thread::Queue.new
358
- Thread.new { monitor(request, start_spec, first_event) }
359
- result = first_event.pop(timeout: START_TIMEOUT_SEC)
360
- raise Transfer::Error, "No event from transferd after #{START_TIMEOUT_SEC}s" if result.nil?
361
- raise result if result.is_a?(Exception)
362
- return result
363
- end
364
-
365
- # Get a transfer started by the emulator
366
- # @param id [String] transfer id
367
- # @return [Hash, nil] Node API transfer, `nil` if unknown
368
- def transfer(id)
369
- entry = store do |transfers|
370
- found = transfers[id]
371
- found&.merge(sessions: found[:sessions].dup, files: found[:files].dup, rates: found[:rates].dup)
372
- end
373
- return if entry.nil?
374
- result = self.class.transfer_to_node(id, entry, node_id: @node_id)
375
- # transferd gives real paths of local files
376
- result['files'].each { |file| file['path'] = virtual_path(file['path']) if in_docroot?(file['path']) }
377
- result
378
- end
379
-
380
- # List the transfers started by the emulator
381
- # @param active_only [Boolean, nil] `true`: only waiting or running, `false`: only terminated, `nil`: all
382
- # @param direction [String, nil] `send` or `receive`
383
- # @param count [Integer, nil] max number of transfers, oldest first
384
- # @return [Array<Hash>] Node API transfers
385
- def transfers(active_only: nil, direction: nil, count: nil)
386
- # a transfer may expire between the two calls
387
- result = store(&:keys).filter_map { |id| transfer(id) }
388
- result.select! { |transfer| ACTIVE.include?(transfer['status']).eql?(active_only) } unless active_only.nil?
389
- result.select! { |transfer| transfer['start_spec']['direction'].eql?(direction) } unless direction.nil?
390
- count.nil? ? result : result.first(count)
391
- end
392
-
393
- # Stop a transfer: its status becomes `canceled` when transferd notifies it
394
- # @param id [String] transfer id
395
- # @return [Boolean] `false` if unknown
396
- def cancel(id)
397
- return false unless known?(id)
398
- response = @transfer_client.stop_transfer(::Transferd::Api::StopTransferRequest.new(transferId: [id]))
399
- Log.dump(:stop_response, response.to_h, level: :trace2)
400
- result = response.stopResult.find { |info| info.transferId.eql?(id) }
401
- Aspera.assert(result&.stopped, type: Transfer::Error) { result&.error&.description || 'Transfer not stopped by transferd' }
402
- true
403
- end
404
-
405
- # Modify the rates or the policy of a transfer
406
- # @param id [String] transfer id
407
- # @param changes [Hash] new values of transfer spec fields: `target_rate_kbps`, `min_rate_kbps`, `rate_policy`
408
- # @return [Boolean] `false` if unknown
409
- def modify(id, changes)
410
- return false unless known?(id)
411
- response = @transfer_client.modify_transfer(::Transferd::Api::TransferModificationRequest.new(transferId: id, transferSpec: changes.to_json))
412
- Log.dump(:modify_response, response.to_h, level: :trace2)
413
- Aspera.assert(response.error.nil? || response.error.description.empty?, type: Transfer::Error) { response.error.description }
414
- true
415
- end
416
-
417
- private
418
-
419
- # Check if a transfer is known
420
- # @param id [String] transfer id
421
- # @return [Boolean] `true` if the transfer was started by the emulator
422
- def known?(id)
423
- store { |transfers| transfers.key?(id) }
424
- end
425
-
426
- # Lock the store, and remove the transfers ended for longer than the retention time
427
- # @yieldparam transfers [Hash] transfer id → store entry
428
- # @return [Object] result of the block
429
- def store
430
- @mutex.synchronize do
431
- now = monotonic_time
432
- @transfers.delete_if { |_, entry| entry.key?(:ended) && now - entry[:ended] >= @retention_sec }
433
- yield(@transfers)
434
- end
435
- end
436
-
437
- # @return [Float] current time in seconds, for durations
438
- def monotonic_time
439
- ::Process.clock_gettime(::Process::CLOCK_MONOTONIC)
440
- end
441
-
442
- # Convert a Node API path to a real path
443
- # @param path [String] path relative to the docroot, leading `/` optional
444
- # @return [String] real path, within the docroot
445
- def real_path(path)
446
- # `./` prevents expansion of `~`
447
- real = File.expand_path("./#{path.to_s.sub(%r{\A/+}, '')}", @docroot)
448
- # symbolic links shall not lead out of the docroot
449
- resolved = resolved_path(real) if in_docroot?(real)
450
- Aspera.assert(!resolved.nil? && in_docroot?(resolved)) { "Path outside docroot: #{path}" }
451
- real
452
- end
453
-
454
- # Resolve symbolic links of the existing part of a path: a destination may not exist yet
455
- # @param real [String] absolute path, without `..`, within the docroot
456
- # @return [String, nil] real path of the longest existing part of `real`, `nil` if it is a dangling symbolic link
457
- def resolved_path(real)
458
- # stops at the docroot, which exists
459
- real = File.dirname(real) until File.exist?(real) || File.symlink?(real)
460
- File.realpath(real)
461
- rescue Errno::ENOENT, Errno::ELOOP
462
- nil
463
- end
464
-
465
- # Convert a real path to a Node API path
466
- # @param real [String] real path within the docroot
467
- # @return [String] path relative to the docroot, with leading `/`
468
- def virtual_path(real)
469
- "/#{real.delete_prefix(@docroot).delete_prefix('/')}"
470
- end
471
-
472
- # Check if a real path is within the docroot
473
- # @param real [String] real path
474
- # @return [Boolean] `true` if the path is the docroot or inside it
475
- def in_docroot?(real)
476
- real.eql?(@docroot) || real.start_with?(@docroot.end_with?('/') ? @docroot : "#{@docroot}/")
477
- end
478
-
479
- # Get the Node API fields of a folder or of an item of a folder
480
- # @param real [String] real path within the docroot
481
- # @param virtual [String] Node API path
482
- # @param stat [File::Stat] information on the item
483
- # @return [Hash] Node API fields common to a folder and its items
484
- def item_info(real, virtual, stat)
485
- {
486
- 'path' => virtual,
487
- 'basename' => File.basename(real),
488
- 'type' => FILE_TYPES.fetch(stat.ftype, stat.ftype),
489
- # Node API reports 0 for folders
490
- 'size' => stat.directory? ? 0 : stat.size,
491
- 'mtime' => stat.mtime.utc.iso8601,
492
- 'permissions' => permissions(real)
493
- }
494
- end
495
-
496
- # Get the Node API permissions of an item
497
- # @param real [String] real path within the docroot
498
- # @return [Array<Hash>] Node API permissions, from the access of the emulator on the item
499
- def permissions(real)
500
- names = []
501
- names.push('view') if File.readable?(real)
502
- names.push('edit') if File.writable?(real)
503
- # the docroot itself cannot be deleted
504
- names.push('delete') if !real.eql?(@docroot) && File.writable?(File.dirname(real))
505
- names.map { |name| {'name' => name} }
506
- end
507
-
508
- # Get the Node API target of a symbolic link
509
- # @param link [String] real path of a symbolic link within the docroot
510
- # @return [Hash] Node API target of the link: only the content of the link if it is dangling or leads out of the docroot
511
- def link_target(link)
512
- target = File.realpath(link) rescue nil
513
- unless target && in_docroot?(target)
514
- content = File.readlink(link)
515
- return {'path' => content, 'basename' => File.basename(content)}
516
- end
517
- stat = File.stat(target)
518
- {
519
- 'path' => virtual_path(target),
520
- 'basename' => File.basename(target),
521
- 'type' => File.ftype(target),
522
- 'size' => stat.directory? ? 0 : stat.size
523
- }
524
- end
525
-
526
- # Local paths of the transfer spec (sources for `send`, destination for `receive`) are relative to the docroot
527
- # @param transfer_spec [Hash] modified: local paths are replaced with real paths
528
- # @return [Hash] the transfer spec
529
- def apply_docroot(transfer_spec)
530
- receive = transfer_spec['direction'].eql?(Transfer::Spec::DIRECTION_RECEIVE)
531
- root_field, path_field = receive ? %w[destination_root destination] : %w[source_root source]
532
- # a download without destination goes to the docroot
533
- root = transfer_spec[root_field] || ('/' if receive)
534
- if root.nil?
535
- transfer_spec['paths']&.each { |item| item[path_field] = real_path(item[path_field]) if item.key?(path_field) }
536
- else
537
- transfer_spec[root_field] = real_path(root)
538
- # paths are relative to the root: they shall not lead out of the docroot
539
- transfer_spec['paths']&.each { |item| real_path(File.join(root, item[path_field])) if item.key?(path_field) }
540
- end
541
- transfer_spec
542
- end
543
-
544
- # Start the transfer and update the store with its events, until terminated.
545
- # Runs in a thread.
546
- # @param request [Transferd::Api::TransferRequest]
547
- # @param start_spec [Hash] transfer spec without secrets
548
- # @param first_event [Thread::Queue] receives the transfer id, or the exception if the transfer could not start
549
- def monitor(request, start_spec, first_event)
550
- id = nil
551
- @transfer_client.start_transfer_with_monitor(request) do |response|
552
- Log.dump(:transferd_event, response.to_h, level: :trace2)
553
- new_transfer = id.nil?
554
- if new_transfer
555
- Aspera.assert(!response.transferId.empty?, type: Transfer::Error) { response.error&.description || 'No transfer id from transferd' }
556
- id = response.transferId
557
- end
558
- store do |transfers|
559
- entry = (transfers[id] ||= {start_spec: start_spec, sessions: {}, files: {}, rates: {}})
560
- self.class.update_entry(entry, response)
561
- # no more event, and so no more retry: retention starts
562
- entry[:ended] = monotonic_time if TERMINAL.include?(entry[:status])
563
- end
564
- first_event.push(id) if new_transfer
565
- break if TERMINAL.include?(response.status)
566
- end
567
- first_event.push(Transfer::Error.new('transferd closed the stream without event')) if id.nil?
568
- rescue StandardError => e
569
- if id.nil?
570
- first_event.push(e)
571
- else
572
- Log.log.error { "Transfer #{id}: #{e.message}" }
573
- store { |transfers| transfers[id].merge!(status: :FAILED, error: e.message, ended: monotonic_time) }
574
- end
575
- end
576
- end
577
-
578
- # Answers a subset of the Node API, transfers are delegated to a NodeEmulator
579
- # a new instance is created for each request
580
- class NodeEmulatorServlet < WEBrick::HTTPServlet::AbstractServlet
581
- include ServletHelpers
582
-
583
- PATH_TRANSFERS = '/ops/transfers'
584
- PATH_ONE_TRANSFER = %r{/ops/transfers/(.+)$}
585
- PATH_BROWSE = '/files/browse'
586
- REALM = 'Aspera Node Emulator'
587
- # `PUT` values of `status` that cancel the transfer (pause and resume are not supported)
588
- CANCEL_STATUSES = %w[canceled cancelled stopped].freeze
589
- # `PUT` fields modified by transferd
590
- MODIFIABLE = %w[target_rate_kbps min_rate_kbps rate_policy].freeze
591
- # HTTP methods with a JSON body
592
- JSON_METHODS = %w[POST PUT].freeze
593
- # Create the servlet, with optional Basic authentication
594
- # @param server [WEBrick::HTTPServer]
595
- # @param config [Hash] `username` and `password` (Basic authentication expected from clients, optional)
596
- # @param simulator [NodeEmulator]
597
- def initialize(server, config, simulator)
598
- super(server)
599
- @simulator = simulator
600
- @expected_auth = "#{config[:username]}:#{config[:password]}" unless config[:username].nil?
601
- end
602
-
603
- # Refuse requests of web pages, check authentication, dispatch to `do_<verb>`, and send errors in Node API format
604
- # @param request [WEBrick::HTTPRequest]
605
- # @param response [WEBrick::HTTPResponse]
606
- def service(request, response)
607
- check_request(request, json: JSON_METHODS.include?(request.request_method))
608
- return set_error(request, response, 401, 'Invalid or missing credentials', headers: {'WWW-Authenticate' => %Q(Basic realm="#{REALM}")}) unless authorized?(request)
609
- super
610
- rescue WEBrick::HTTPStatus::Error => e
611
- set_error(request, response, e.code, e.message)
612
- rescue JSON::ParserError, AssertError, Transfer::Error => e
613
- set_error(request, response, 400, e.message)
614
- rescue Errno::ENOENT => e
615
- set_error(request, response, 404, e.message)
616
- rescue StandardError => e
617
- Log.log.error { "#{request.request_method} #{request.path}: #{e.class}: #{e.message}" }
618
- set_error(request, response, 500, e.message)
619
- end
620
-
621
- # Start a transfer, or list a folder
622
- # @param request [WEBrick::HTTPRequest]
623
- # @param response [WEBrick::HTTPResponse]
624
- def do_POST(request, response)
625
- json =
626
- case request.path
627
- when PATH_TRANSFERS
628
- @simulator.transfer(@simulator.start(JSON.parse(request.body.to_s)))
629
- when PATH_BROWSE
630
- req = JSON.parse(request.body.to_s)
631
- @simulator.browse(req['path'] || '/', skip: req['skip'].to_i, count: req['count']&.to_i)
632
- else raise WEBrick::HTTPStatus::NotFound, "Unknown path: #{request.path}"
633
- end
634
- set_json_response(request, response, json)
635
- end
636
-
637
- # Get the node information, the list of transfers, or one transfer
638
- # @param request [WEBrick::HTTPRequest]
639
- # @param response [WEBrick::HTTPResponse]
640
- def do_GET(request, response)
641
- json =
642
- case request.path
643
- when '/info' then @simulator.info
644
- when PATH_TRANSFERS
645
- @simulator.transfers(
646
- active_only: query_boolean(request, 'active_only'),
647
- direction: request.query['direction']&.to_s,
648
- count: query_positive(request, 'count')
649
- )
650
- when PATH_ONE_TRANSFER then known_transfer(@simulator.transfer(transfer_id(request)))
651
- else raise WEBrick::HTTPStatus::NotFound, "Unknown path: #{request.path}"
652
- end
653
- set_json_response(request, response, json)
654
- end
655
-
656
- # Modify a transfer, or cancel it with `status`
657
- # @param request [WEBrick::HTTPRequest]
658
- # @param response [WEBrick::HTTPResponse]
659
- def do_PUT(request, response)
660
- id = transfer_id(request)
661
- changes = JSON.parse(request.body.to_s)
662
- raise WEBrick::HTTPStatus::BadRequest, 'Body must be a JSON object' unless changes.is_a?(Hash)
663
- status = changes.delete('status')
664
- if status.nil?
665
- unsupported = changes.keys - MODIFIABLE
666
- raise WEBrick::HTTPStatus::BadRequest, "Cannot modify: #{unsupported.join(', ')}" unless unsupported.empty?
667
- raise WEBrick::HTTPStatus::BadRequest, 'Nothing to modify' if changes.empty?
668
- found = @simulator.modify(id, changes)
669
- else
670
- raise WEBrick::HTTPStatus::BadRequest, "Unsupported status: #{status}" unless CANCEL_STATUSES.include?(status)
671
- found = @simulator.cancel(id)
672
- end
673
- known_transfer(found)
674
- set_json_response(request, response, @simulator.transfer(id))
675
- end
676
-
677
- # Node API cancels a transfer with HTTP verb `CANCEL`
678
- # @param request [WEBrick::HTTPRequest]
679
- # @param response [WEBrick::HTTPResponse]
680
- def do_CANCEL(request, response)
681
- known_transfer(@simulator.cancel(transfer_id(request)))
682
- response.status = 204
683
- end
684
-
685
- private
686
-
687
- # Extract the transfer id from the path of the request
688
- # @param request [WEBrick::HTTPRequest]
689
- # @return [String] transfer id
690
- # @raise [WEBrick::HTTPStatus::NotFound] if the path is not the one of a transfer
691
- def transfer_id(request)
692
- match = request.path.match(PATH_ONE_TRANSFER)
693
- raise WEBrick::HTTPStatus::NotFound, "Unknown path: #{request.path}" if match.nil?
694
- match[1]
695
- end
696
-
697
- # @param found [Object] Result of the emulator for a transfer: `nil` or `false` if unknown
698
- # @return [Object] found
699
- # @raise [WEBrick::HTTPStatus::NotFound] if the transfer is unknown
700
- def known_transfer(found)
701
- raise WEBrick::HTTPStatus::NotFound, 'Unknown transfer' unless found
702
- found
703
- end
704
-
705
- # Read a boolean query parameter
706
- # @param request [WEBrick::HTTPRequest]
707
- # @param name [String] name of the query parameter
708
- # @return [Boolean, nil] value, `nil` if absent
709
- # @raise [WEBrick::HTTPStatus::BadRequest] if the value is not `true` or `false`
710
- def query_boolean(request, name)
711
- value = request.query[name]&.to_s
712
- return if value.nil?
713
- raise WEBrick::HTTPStatus::BadRequest, "Query #{name} must be true or false: #{value}" unless %w[true false].include?(value)
714
- value.eql?('true')
715
- end
716
-
717
- # Read a positive integer query parameter
718
- # @param request [WEBrick::HTTPRequest]
719
- # @param name [String] name of the query parameter
720
- # @return [Integer, nil] value, `nil` if absent
721
- # @raise [WEBrick::HTTPStatus::BadRequest] if the value is not a positive integer
722
- def query_positive(request, name)
723
- value = request.query[name]&.to_s
724
- return if value.nil?
725
- number = Integer(value, exception: false)
726
- raise WEBrick::HTTPStatus::BadRequest, "Query #{name} must be a positive integer: #{value}" unless number&.positive?
727
- number
728
- end
729
-
730
- # Set error body in Node API format
731
- # @param request [WEBrick::HTTPRequest]
732
- # @param response [WEBrick::HTTPResponse]
733
- # @param code [Integer] HTTP status code
734
- # @param message [String] message for the user
735
- # @param headers [Hash{String => String}] Other headers of the response
736
- def set_error(request, response, code, message, headers: {})
737
- set_json_response(request, response, {error: {code: code, reason: WEBrick::HTTPStatus.reason_phrase(code), user_message: message}}, code: code, headers: headers)
738
- end
739
-
740
- # Check the Basic credentials of the request
741
- # @param request [WEBrick::HTTPRequest]
742
- # @return [Boolean] `true` if the request has the expected Basic credentials, or if none are expected
743
- def authorized?(request)
744
- @expected_auth.nil? || basic_authorized?(request, @expected_auth)
745
- end
746
-
747
- # Set the status and the JSON body of the response
748
- # @param request [WEBrick::HTTPRequest] for the log
749
- # @param response [WEBrick::HTTPResponse]
750
- # @param json [Hash, Array] body of the response
751
- # @param code [Integer] HTTP status code
752
- # @param headers [Hash{String => String}] Other headers of the response
753
- def set_json_response(request, response, json, code: 200, headers: {})
754
- json_response(response, code, json, headers: headers)
755
- Log.dump("response for #{request.request_method} #{request.path}", json, level: :trace1)
756
- end
757
- end
758
- end