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
@@ -0,0 +1,617 @@
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 '../../log'
8
+ require_relative '../../environment'
9
+ require_relative '../../yaml'
10
+ require_relative '../../secret/hider'
11
+ require_relative '../../schema/registry'
12
+ require_relative '../../schema/validator'
13
+ require_relative '../../products/transferd'
14
+ require 'json'
15
+ require 'securerandom'
16
+ require 'etc'
17
+ require 'fileutils'
18
+ require 'socket'
19
+
20
+ module Aspera
21
+ module Plugins
22
+ module Transferd
23
+ # Run the transfer daemon as a system service: configuration of `transferd.json` and systemd unit
24
+ class Service
25
+ # Number of random bytes of a generated API key
26
+ API_KEY_BYTES = 32
27
+ DEFAULT_SERVICE_NAME = 'aspera-transferd'
28
+ DEFAULT_USER = 'asperadaemon'
29
+ DEFAULT_UNIT_DIR = '/etc/systemd/system'
30
+ DEFAULT_AFTER = ['network.target'].freeze
31
+ # Default location of the configuration file, also the default of the daemon
32
+ CONFIG_FILE = Products::Transferd::SERVICE_CONFIG_FILE
33
+ # Schemas of the bundle (manifest `schemas`): configuration file of the daemon, parameters of the service
34
+ DAEMON_CONFIG_SCHEMA = 'transferd'
35
+ SERVICE_OPTIONS = 'transferd_opts:components.schemas.ServiceOptions'
36
+ SERVICE_CONFIG = 'transferd_opts:components.schemas.TransferdServiceConfig'
37
+ # Environment variables of the daemon that override the configuration file
38
+ ENV_OVERRIDES = %w[TRANSFERD_ADDRESS TRANSFERD_PORT TRANSFERD_MGMT_ADDRESS TRANSFERD_MGMT_PORT].freeze
39
+ # Mode of files that may contain a secret, and of the folder of the configuration
40
+ FILE_MODE = 0o640
41
+ DIR_MODE = 0o750
42
+ # Seconds between two checks of the port
43
+ WAIT_INTERVAL = 0.5
44
+ # Keys of `transferd.json` that contain a secret
45
+ SECRET_KEYS = %w[api_key].freeze
46
+ # Name of the link to the version in use, in the layout `<prefix>/<version>`
47
+ CURRENT_LINK = 'current'
48
+ # Name of the folder of a version in the layout
49
+ VERSION_PATTERN = /\A\d+(\.\d+)*\z/
50
+ private_constant :API_KEY_BYTES, :FILE_MODE, :DIR_MODE, :WAIT_INTERVAL, :SECRET_KEYS, :VERSION_PATTERN
51
+
52
+ # Access to the system: root folder, commands and network. Replaceable in tests.
53
+ class Host
54
+ # @return [String] Root folder: all files are written below it (`/` for a real installation)
55
+ # @return [Numeric] Seconds to wait for the daemon to listen
56
+ # @return [Symbol] Operating system, see `Environment::OS_*`
57
+ # @return [Integer] Effective user id of the process
58
+ attr_reader :root, :timeout, :os, :euid
59
+
60
+ # @param root [String] Root folder of the file system
61
+ # @param runner [#call] Receives the command words, returns `[output, success]`, default: run the command
62
+ # @param listening [#call] Receives address and port, returns `true` if a server listens, default: try to connect
63
+ # @param timeout [Numeric] Seconds to wait for the daemon to listen
64
+ # @param os [Symbol] Operating system, default: the current one
65
+ # @param euid [Integer] Effective user id, default: the one of the process
66
+ # @param systemctl [Boolean] `true` if `systemctl` is available, default: look for it in `PATH`
67
+ def initialize(root: '/', runner: nil, listening: nil, timeout: 30, os: nil, euid: nil, systemctl: nil)
68
+ @root = root
69
+ @os = os || Environment.instance.os
70
+ @euid = euid || ::Process.euid
71
+ @systemctl = systemctl.nil? ? ENV.fetch('PATH', '').split(File::PATH_SEPARATOR).any? { |dir| File.executable?(File.join(dir, 'systemctl')) } : systemctl
72
+ @runner = runner || lambda do |*cmd|
73
+ out, err, status = Environment.secure_execute(*cmd, mode: :capture, exception: false)
74
+ [out.to_s + err.to_s, status.success?]
75
+ end
76
+ @listening = listening || lambda do |address, port|
77
+ Socket.tcp(address, port, connect_timeout: 1) { true }
78
+ rescue SystemCallError, IOError
79
+ false
80
+ end
81
+ @timeout = timeout
82
+ end
83
+
84
+ # @param path [String] Absolute path in the real file system
85
+ # @return [String] Path below the root folder
86
+ def path(path)
87
+ File.join(@root, path)
88
+ end
89
+
90
+ # @param cmd [Array<String>] Command to run
91
+ # @return [Array(String, Boolean)] Output and success
92
+ def run(*cmd)
93
+ @runner.call(*cmd)
94
+ end
95
+
96
+ # @return [Boolean] `true` if a server listens on this address and port
97
+ def listening?(address, port)
98
+ @listening.call(address, port)
99
+ end
100
+
101
+ # @return [Boolean] `true` if `systemctl` is available
102
+ def systemctl?
103
+ @systemctl
104
+ end
105
+ end
106
+
107
+ class << self
108
+ # Generate the text of the systemd unit file.
109
+ # @param options [Hash] Service and execution options (from CONFIG or specific keys)
110
+ # @return [String] systemd unit file content
111
+ def unit(options = {})
112
+ Aspera.assert_type(options, Hash) { 'options' }
113
+ opts = json_hash(options)
114
+ opts = opts['service'].merge(opts) if opts['service'].is_a?(Hash)
115
+ executable = opts['executable'] || opts['exec'] || opts['bin'] ||
116
+ (opts['sdk_folder'] ? File.join(opts['sdk_folder'], 'bin', 'transferd') : '/opt/aspera/transferd/bin/transferd')
117
+ config_file = opts['config_file'] || opts['config'] || opts['config_path'] || opts['file'] || '/etc/transferd/transferd.json'
118
+ user = opts['user'] || DEFAULT_USER
119
+ group = opts['group']
120
+ after = opts['after'] || DEFAULT_AFTER
121
+ after = Array(after).join(' ')
122
+ env = opts['environment'] || {}
123
+
124
+ lines = [
125
+ '[Unit]',
126
+ "Description=#{opts['description'] || 'IBM Aspera Transfer Daemon'}",
127
+ "After=#{after}",
128
+ '',
129
+ '[Service]',
130
+ "Type=#{opts['type'] || 'simple'}",
131
+ "User=#{user}"
132
+ ]
133
+ lines << "Group=#{group}" if group && !group.empty?
134
+ lines << "ExecStart=#{executable} --config #{config_file}"
135
+ lines << "Restart=#{opts['restart'] || 'always'}"
136
+ env.keys.sort.each do |k|
137
+ lines << %Q(Environment="#{k}=#{env[k]}")
138
+ end
139
+ lines.push(
140
+ '',
141
+ '[Install]',
142
+ "WantedBy=#{opts['wanted_by'] || 'multi-user.target'}",
143
+ ''
144
+ )
145
+ lines.join("\n")
146
+ end
147
+
148
+ # Build the content of `transferd.json`.
149
+ # Order of precedence: values computed from `sdk_folder`, then `existing`, then `overrides`.
150
+ # A key set to `nil` in `overrides` is removed.
151
+ # @param existing [Hash, nil] Content of the existing configuration file, `nil` or empty if none
152
+ # @param overrides [Hash] Values given by the user (section `config` of the user parameter)
153
+ # @param sdk_folder [String] Folder of the SDK, used for `fasp_runtime`
154
+ # @param file [String,nil] Path of the existing file, for error messages
155
+ # @return [Hash] Validated configuration, with String keys
156
+ # @raise [ParameterError] if the result does not conform to the schema of the daemon
157
+ def config(existing, overrides, sdk_folder, file: nil)
158
+ Aspera.assert_type(existing, Hash, NilClass) { 'existing' }
159
+ Aspera.assert_type(overrides, Hash) { 'overrides' }
160
+ Aspera.assert_type(sdk_folder, String) { 'sdk_folder' }
161
+ existing = json_hash(existing || {})
162
+ computed = {
163
+ 'fasp_runtime' => {
164
+ 'use_embedded' => false,
165
+ 'user_defined' => {'bin' => sdk_folder, 'etc' => sdk_folder}
166
+ }
167
+ }
168
+ result = merge(merge(computed, existing), json_hash(overrides))
169
+ auth = result['authentication']
170
+ auth['api_key'] = SecureRandom.hex(API_KEY_BYTES) if auth.is_a?(Hash) && auth['enabled'].eql?(true) && !auth.key?('api_key')
171
+ errors = validate(result, existing, file)
172
+ Aspera.assert(errors.empty?, type: ParameterError) { "Invalid transferd configuration:\n#{errors.join("\n")}" }
173
+ return result
174
+ end
175
+
176
+ # Layout of versions side by side: `<prefix>/<version>` folders and the link `<prefix>/current`.
177
+ # It is used when the SDK folder is named `current`. The paths in the unit and in `transferd.json` go through the link,
178
+ # so that switching the link and restarting the service is enough to change the version.
179
+ # @param sdk_folder [String] Folder of the SDK
180
+ # @return [Boolean] `true` if the layout is used
181
+ def layout?(sdk_folder)
182
+ File.basename(sdk_folder).eql?(CURRENT_LINK)
183
+ end
184
+
185
+ # @param sdk_folder [String] Folder of the SDK
186
+ # @return [String] Folder of the version in use if the layout is used, else `sdk_folder` as is
187
+ def resolve(sdk_folder)
188
+ layout?(sdk_folder) && File.symlink?(sdk_folder) ? File.realpath(sdk_folder) : sdk_folder
189
+ end
190
+
191
+ # @param sdk_folder [String] Link `current` of the layout
192
+ # @return [Array<Hash>] Installed versions, oldest first: `version`, `folder`, `current`
193
+ def versions(sdk_folder)
194
+ assert_layout(sdk_folder)
195
+ prefix = File.dirname(sdk_folder)
196
+ current = link_target(sdk_folder)
197
+ names = Dir.exist?(prefix) ? Dir.children(prefix) : []
198
+ return names
199
+ .select { |name| name.match?(VERSION_PATTERN) && File.exist?(executable(File.join(prefix, name))) }
200
+ .sort_by { |name| Gem::Version.new(name) }
201
+ .map { |name| {'version' => name, 'folder' => File.join(prefix, name), 'current' => name.eql?(current)} }
202
+ end
203
+
204
+ # Switch the link `current` to an installed version and restart the service.
205
+ # If the restart fails, the link is set back to the previous version and the service is restarted again.
206
+ # @param user_config [Hash] `CONFIG`
207
+ # @param sdk_folder [String] Link `current` of the layout
208
+ # @param version [String] Installed version
209
+ # @return [Array<String>] Actions done, or to do with `dry_run`; empty if the version is already in use
210
+ def use(user_config, sdk_folder, version, host: Host.new, dry_run: false)
211
+ assert_layout(sdk_folder)
212
+ folder = version_folder(sdk_folder, version)
213
+ Aspera.assert(File.exist?(executable(folder)), type: ParameterError) { "Version #{version} is not installed in #{folder}" }
214
+ previous = link_target(sdk_folder)
215
+ return [] if previous.eql?(version)
216
+ opts = service_options(user_config)
217
+ steps = [["link #{sdk_folder} to #{version}", -> { switch_link(sdk_folder, version) }]]
218
+ if File.exist?(unit_path(host, opts))
219
+ config_file = host.path(CONFIG_FILE)
220
+ conf = File.exist?(config_file) ? read_config(config_file) : {}
221
+ steps << ["restart #{opts['name']}", -> { systemctl(host, 'restart', opts['name']) }]
222
+ steps.concat(wait_steps(host, opts, conf))
223
+ end
224
+ return with_rollback(sdk_folder, previous, opts, host) { run_steps(steps, dry_run) }
225
+ end
226
+
227
+ # Install the SDK if not present, then configure and start the service.
228
+ # With the layout, the SDK is installed in `<prefix>/<version>`, the link `current` is set to it, and
229
+ # it is set back to the previous version if the service cannot be started.
230
+ # @param user_config [Hash] `CONFIG`: sections `service` and `config`
231
+ # @param sdk_folder [String] Folder of the SDK, or link `current` of the layout
232
+ # @param host [Host] Access to the system
233
+ # @param dry_run [Boolean] `true`: change nothing, only return the actions
234
+ # @param install_sdk [#call] Installs the SDK, called if `transferd` is not there.
235
+ # With the layout it receives the folder of the version, else no argument.
236
+ # @param version [String] Version to install and use, mandatory with the layout, else ignored
237
+ # @return [Array<String>] Actions done, or to do with `dry_run`
238
+ def install(user_config, sdk_folder, host: Host.new, dry_run: false, install_sdk: nil, version: nil)
239
+ steps = []
240
+ previous = nil
241
+ if layout?(sdk_folder)
242
+ folder = version_folder(sdk_folder, version)
243
+ previous = link_target(sdk_folder)
244
+ unless File.exist?(executable(folder))
245
+ Aspera.assert(!install_sdk.nil?, type: ParameterError) { "SDK is not installed in #{folder}" }
246
+ steps << ["install the SDK in #{folder}", -> { install_sdk.call(folder) }]
247
+ end
248
+ steps << ["link #{sdk_folder} to #{version}", -> { switch_link(sdk_folder, version) }] unless previous.eql?(version)
249
+ elsif !File.exist?(executable(sdk_folder))
250
+ Aspera.assert(!install_sdk.nil?, type: ParameterError) { "SDK is not installed in #{sdk_folder}" }
251
+ steps << ["install the SDK in #{sdk_folder}", install_sdk]
252
+ end
253
+ steps.concat(configure_steps(user_config, sdk_folder, host, dry_run))
254
+ return run_steps(steps, dry_run) unless layout?(sdk_folder)
255
+ with_rollback(sdk_folder, previous, service_options(user_config), host) { run_steps(steps, dry_run) }
256
+ end
257
+
258
+ # Merge `CONFIG` in the configuration file, write the unit, then (re)start the service.
259
+ # @return [Array<String>] Actions done, or to do with `dry_run`
260
+ def configure(user_config, sdk_folder, host: Host.new, dry_run: false)
261
+ run_steps(configure_steps(user_config, sdk_folder, host, dry_run), dry_run)
262
+ end
263
+
264
+ # State of the service. The API key is never returned.
265
+ # @return [Hash] Version, state of the service, endpoint, and whether it listens
266
+ def status(user_config, sdk_folder, host: Host.new)
267
+ opts = service_options(user_config)
268
+ unit_file = host.path(File.join(opts['unit_dir'], "#{opts['name']}.service"))
269
+ config_file = host.path(CONFIG_FILE)
270
+ # only booleans and the endpoint are read: the API key is never copied in the result
271
+ config = File.exist?(config_file) ? read_config(config_file) : {}
272
+ env = unit_file_environment(unit_file)
273
+ address = env['TRANSFERD_ADDRESS'] || config['address'] || '127.0.0.1'
274
+ port = (env['TRANSFERD_PORT'] || config['port']).to_i
275
+ version = File.exist?(executable(sdk_folder)) ? host.run(executable(sdk_folder), 'version').first : ''
276
+ return {
277
+ 'service' => opts['name'],
278
+ 'sdk_folder' => resolve(sdk_folder),
279
+ 'installed' => File.exist?(unit_file),
280
+ 'version' => version[/\d+\.\d+\.\d+/],
281
+ 'enabled' => host.run('systemctl', 'is-enabled', opts['name']).first.strip,
282
+ 'active' => host.run('systemctl', 'is-active', opts['name']).first.strip,
283
+ 'config_file' => CONFIG_FILE,
284
+ 'address' => address,
285
+ 'port' => port,
286
+ 'listening' => port.positive? && host.listening?(connect_address(address), port),
287
+ 'authentication' => config.dig('authentication', 'enabled').eql?(true),
288
+ 'tls' => config.dig('tls', 'enabled').eql?(true),
289
+ 'environment' => env
290
+ }
291
+ end
292
+
293
+ # Stop and remove the service.
294
+ # @param purge [Boolean] Also remove the configuration file and the log folder
295
+ # @return [Array<String>] Actions done, or to do with `dry_run`
296
+ def uninstall(user_config, host: Host.new, dry_run: false, purge: false)
297
+ opts = service_options(user_config)
298
+ unit_file = host.path(File.join(opts['unit_dir'], "#{opts['name']}.service"))
299
+ steps = []
300
+ if File.exist?(unit_file)
301
+ steps << ["stop and disable #{opts['name']}", -> { systemctl(host, 'disable', '--now', opts['name'], check: false) }]
302
+ steps << ["remove #{unit_file}", -> { File.delete(unit_file) }]
303
+ steps << ['reload systemd', -> { systemctl(host, 'daemon-reload') }]
304
+ end
305
+ steps.concat(purge_steps(host)) if purge
306
+ run_steps(steps, dry_run)
307
+ end
308
+
309
+ # @param user_config [Hash] `CONFIG`
310
+ # @return [Hash] Validated `service` section with defaults, plus `config` section as `overrides`
311
+ def service_options(user_config)
312
+ Aspera.assert_type(user_config, Hash) { 'CONFIG' }
313
+ conf = json_hash(user_config)
314
+ service = conf['service'] || {}
315
+ errors = Schema::Validator.instance.errors(service, SERVICE_OPTIONS)
316
+ Aspera.assert(errors.empty?, type: ParameterError) { "Invalid service parameters:\n#{errors.join("\n")}" }
317
+ return {
318
+ 'name' => DEFAULT_SERVICE_NAME,
319
+ 'user' => DEFAULT_USER,
320
+ 'unit_dir' => DEFAULT_UNIT_DIR,
321
+ 'after' => DEFAULT_AFTER,
322
+ 'environment' => {}
323
+ }.merge(service).merge('overrides' => conf['config'] || {})
324
+ end
325
+
326
+ # Refuse to run on a host that cannot run the service: systemd on Linux, as root.
327
+ # Not checked with `dry_run`: the actions are only shown, so that it works everywhere.
328
+ # @param host [Host] Access to the system
329
+ # @param dry_run [Boolean] `true`: change nothing, no check
330
+ # @raise [Error] if the host is not supported or the user is not root
331
+ def assert_supported(host, dry_run: false)
332
+ return if dry_run
333
+ Aspera.assert(host.os.eql?(Environment::OS_LINUX), type: EnvironmentError) { "The service requires Linux with systemd, this is: #{host.os}" }
334
+ Aspera.assert(host.systemctl?, type: EnvironmentError) { 'The service requires systemd: command systemctl not found' }
335
+ Aspera.assert(host.euid.zero?, type: EnvironmentError) { 'The service must be managed as root (use sudo), or use --dry-run=yes to only see the actions' }
336
+ end
337
+
338
+ # @return [String] Version of transferd that the configuration schema matches
339
+ def schema_version
340
+ schema_hash['$comment'].to_s[/transferd (\d+\.\d+\.\d+)/, 1]
341
+ end
342
+
343
+ # Warn (never fail) if the SDK is not the version that the configuration schema matches.
344
+ # @param sdk_folder [String] Folder of the SDK, or link `current` of the layout
345
+ # @param host [Host] Access to the system
346
+ # @return [String, nil] The warning, or `nil` if versions are the same or the version is unknown
347
+ def check_version(sdk_folder, host: Host.new)
348
+ exe = executable(sdk_folder)
349
+ return unless File.exist?(exe)
350
+ sdk_version = host.run(exe, 'version').first[/\d+\.\d+\.\d+/]
351
+ return if sdk_version.nil? || sdk_version.eql?(schema_version)
352
+ relation = Gem::Version.new(sdk_version) > Gem::Version.new(schema_version) ? 'newer' : 'older'
353
+ message = "transferd #{sdk_version} is #{relation} than the version of the configuration schema (#{schema_version}): some settings may be unknown or refused"
354
+ Log.log.warn(message)
355
+ return message
356
+ end
357
+
358
+ private
359
+
360
+ def assert_layout(sdk_folder)
361
+ Aspera.assert(layout?(sdk_folder), type: ParameterError) { "The SDK folder must be named #{CURRENT_LINK} to use versions: #{sdk_folder}" }
362
+ end
363
+
364
+ # @return [String] Folder of a version, next to the link `current`
365
+ def version_folder(sdk_folder, version)
366
+ Aspera.assert(version.is_a?(String) && version.match?(VERSION_PATTERN), type: ParameterError) { "Invalid version: #{version.inspect}" }
367
+ File.join(File.dirname(sdk_folder), version)
368
+ end
369
+
370
+ # @return [String, nil] Name of the folder the link points to, or `nil` if there is no link
371
+ def link_target(link)
372
+ File.symlink?(link) ? File.basename(File.readlink(link)) : nil
373
+ end
374
+
375
+ # Atomically set the link to a version (relative target)
376
+ def switch_link(link, version)
377
+ Aspera.assert(File.symlink?(link) || !File.exist?(link), type: EnvironmentError) { "#{link} exists and is not a link" }
378
+ temporary = "#{link}.new"
379
+ FileUtils.rm_f(temporary)
380
+ File.symlink(version, temporary)
381
+ File.rename(temporary, link)
382
+ end
383
+
384
+ # @return [String] Path of the unit file
385
+ def unit_path(host, opts)
386
+ host.path(File.join(opts['unit_dir'], "#{opts['name']}.service"))
387
+ end
388
+
389
+ # Run the block, and if it fails, set back the link to the previous version and restart the service.
390
+ def with_rollback(sdk_folder, previous, opts, host)
391
+ yield
392
+ rescue StandardError
393
+ Log.log.error { "Failed, going back to version #{previous || 'none'}" }
394
+ if previous.nil?
395
+ File.delete(sdk_folder) if File.symlink?(sdk_folder)
396
+ else
397
+ switch_link(sdk_folder, previous)
398
+ systemctl(host, 'restart', opts['name'], check: false) if File.exist?(unit_path(host, opts))
399
+ end
400
+ raise
401
+ end
402
+
403
+ # @return [String] Path of `transferd` in the SDK
404
+ def executable(sdk_folder)
405
+ File.join(sdk_folder, 'transferd')
406
+ end
407
+
408
+ # @return [Hash] Content of the configuration file (JSON or YAML)
409
+ def read_config(file)
410
+ Yaml.safe_load(File.read(file)) || {}
411
+ end
412
+
413
+ # @return [Hash] Copy of the configuration without secret
414
+ def hidden(config)
415
+ Secret::Hider.instance.hidden_copy(config)
416
+ end
417
+
418
+ # @return [Hash] Environment variables of the daemon found in the unit file
419
+ def unit_file_environment(unit_file)
420
+ return {} unless File.exist?(unit_file)
421
+ File.readlines(unit_file, chomp: true).filter_map do |line|
422
+ name, value = line.match(/^Environment="([A-Z_]+)=(.*)"$/)&.captures
423
+ [name, value] if ENV_OVERRIDES.include?(name)
424
+ end.to_h
425
+ end
426
+
427
+ # @return [String] Address to connect to, to reach a server that listens on `address`
428
+ def connect_address(address)
429
+ %w[0.0.0.0 ::].include?(address) ? '127.0.0.1' : address
430
+ end
431
+
432
+ # @param host [Host]
433
+ # @param args [Array<String>] Arguments of `systemctl`
434
+ # @param check [Boolean] Fail if the command fails
435
+ # @return [String] Output
436
+ def systemctl(host, *args, check: true)
437
+ out, success = host.run('systemctl', *args)
438
+ Aspera.assert(success || !check, type: EnvironmentError) { "systemctl #{args.join(' ')} failed: #{out}" }
439
+ out
440
+ end
441
+
442
+ # @param steps [Array<Array(String, #call)>] Description and action
443
+ # @param dry_run [Boolean] `true`: do not call the actions
444
+ # @return [Array<String>] Descriptions
445
+ def run_steps(steps, dry_run)
446
+ steps.each do |description, action|
447
+ Log.log.info(description)
448
+ action.call unless dry_run
449
+ end
450
+ steps.map(&:first)
451
+ end
452
+
453
+ # @return [Array<Array(String, #call)>] Steps to write the files and (re)start the service
454
+ def configure_steps(user_config, sdk_folder, host, dry_run)
455
+ opts = service_options(user_config)
456
+ user = opts['user']
457
+ pw = account(user)
458
+ steps = []
459
+ if pw.nil?
460
+ message = "Account #{user} does not exist, create it with: useradd --system --no-create-home --shell /usr/sbin/nologin #{user}"
461
+ Aspera.assert(dry_run, type: ParameterError) { message }
462
+ steps << [message, -> {}]
463
+ end
464
+ uid = pw&.uid
465
+ gid = group_id(opts['group'], pw)
466
+ config_file = host.path(CONFIG_FILE)
467
+ conf = config(File.exist?(config_file) ? read_config(config_file) : nil, opts['overrides'], sdk_folder, file: config_file)
468
+ Secret::Hider.instance.add_secret_keys(SECRET_KEYS)
469
+ Secret::Hider.instance.add_secret_values(conf.dig('authentication', 'api_key'))
470
+ unit_file = host.path(File.join(opts['unit_dir'], "#{opts['name']}.service"))
471
+ unit_text = unit(
472
+ executable: executable(sdk_folder),
473
+ config_file: CONFIG_FILE,
474
+ user: user,
475
+ group: opts['group'],
476
+ after: opts['after'],
477
+ environment: opts['environment']
478
+ )
479
+ owner = "#{user}:#{opts['group'] || 'primary group'}"
480
+ steps << ["create folder #{File.dirname(config_file)} (mode #{DIR_MODE.to_s(8)}, owner #{owner})",
481
+ -> { write_dir(File.dirname(config_file), DIR_MODE, uid, gid) }]
482
+ log_directory = conf['log_directory']
483
+ if log_directory.is_a?(String) && log_directory.start_with?('/')
484
+ log_dir = host.path(log_directory)
485
+ steps << ["create folder #{log_dir} (owner #{owner})", -> { write_dir(log_dir, DIR_MODE, uid, gid) }]
486
+ end
487
+ steps << ["write #{config_file} (mode #{FILE_MODE.to_s(8)}, owner #{owner}):\n#{JSON.pretty_generate(hidden(conf))}",
488
+ -> { write_file(config_file, "#{JSON.pretty_generate(conf)}\n", uid, gid) }]
489
+ steps << ["write #{unit_file} (mode #{FILE_MODE.to_s(8)}):\n#{unit_text}", -> { write_file(unit_file, unit_text, nil, nil) }]
490
+ steps << ['reload systemd', -> { systemctl(host, 'daemon-reload') }]
491
+ steps << ["enable and restart #{opts['name']}", -> { %w[enable restart].each { |action| systemctl(host, action, opts['name']) } }]
492
+ steps.concat(wait_steps(host, opts, conf))
493
+ return steps
494
+ end
495
+
496
+ # @return [Array<Array(String, #call)>] Step to wait for the daemon, none if the port is dynamic
497
+ def wait_steps(host, opts, conf)
498
+ port = (opts['environment']['TRANSFERD_PORT'] || conf['port']).to_i
499
+ return [] unless port.positive?
500
+ address = connect_address(opts['environment']['TRANSFERD_ADDRESS'] || conf['address'] || '127.0.0.1')
501
+ return [["wait for #{address}:#{port}", -> { wait_listening(host, address, port, opts['name']) }]]
502
+ end
503
+
504
+ # @return [Array<Array(String, #call)>] Steps to remove the configuration file and the log folder
505
+ def purge_steps(host)
506
+ config_file = host.path(CONFIG_FILE)
507
+ steps = []
508
+ log_directory = read_config(config_file)['log_directory'] if File.exist?(config_file)
509
+ steps << ["remove #{host.path(log_directory)}", -> { FileUtils.rm_rf(host.path(log_directory)) }] if log_directory.is_a?(String) && log_directory.start_with?('/') && log_directory.length > 1
510
+ steps << ["remove #{config_file}", -> { FileUtils.rm_f(config_file) }]
511
+ steps << ["remove folder #{File.dirname(config_file)} if empty", -> { Dir.rmdir(File.dirname(config_file)) if Dir.empty?(File.dirname(config_file)) }]
512
+ return steps
513
+ end
514
+
515
+ # @return [Etc::Passwd, nil] The account, or `nil` if it does not exist
516
+ def account(user)
517
+ Etc.getpwnam(user)
518
+ rescue ArgumentError
519
+ nil
520
+ end
521
+
522
+ # @return [Integer, nil] Id of the group, or primary group of the account
523
+ def group_id(group, account)
524
+ return account&.gid if group.nil?
525
+ Etc.getgrnam(group).gid
526
+ rescue ArgumentError
527
+ raise ParameterError, "Group #{group} does not exist"
528
+ end
529
+
530
+ def write_dir(path, mode, uid, gid)
531
+ FileUtils.mkdir_p(path)
532
+ Environment.restrict_file_access(path, mode: mode)
533
+ File.chown(uid, gid, path) if uid
534
+ end
535
+
536
+ def write_file(path, content, uid, gid)
537
+ FileUtils.mkdir_p(File.dirname(path))
538
+ Environment.write_file_restricted(path, force: true, mode: FILE_MODE) { content }
539
+ File.chown(uid, gid, path) if uid
540
+ end
541
+
542
+ def wait_listening(host, address, port, name)
543
+ deadline = ::Process.clock_gettime(::Process::CLOCK_MONOTONIC) + host.timeout
544
+ until host.listening?(address, port)
545
+ Aspera.assert(::Process.clock_gettime(::Process::CLOCK_MONOTONIC) < deadline, type: EnvironmentError) do
546
+ "Service #{name} does not listen on #{address}:#{port} after #{host.timeout} seconds, see: journalctl -u #{name}"
547
+ end
548
+ sleep(WAIT_INTERVAL)
549
+ end
550
+ end
551
+
552
+ # @param value [Object] Value with Symbol or String keys
553
+ # @return [Object] JSON view of value: String keys
554
+ def json_hash(value)
555
+ JSON.parse(JSON.generate(value))
556
+ end
557
+
558
+ # Deep merge, entries set to `nil` in `over` are removed
559
+ # @param base [Hash] Initial values
560
+ # @param over [Hash] Values to apply
561
+ # @return [Hash] New Hash
562
+ def merge(base, over)
563
+ over.each_with_object(base.dup) do |(key, value), result|
564
+ if value.nil?
565
+ result.delete(key)
566
+ elsif value.is_a?(Hash)
567
+ result[key] = merge(result[key].is_a?(Hash) ? result[key] : {}, value)
568
+ else
569
+ result[key] = value
570
+ end
571
+ end
572
+ end
573
+
574
+ # @return [JSONSchemer::Schema] compiled schema of `transferd.json`
575
+ def schema
576
+ @schema ||=
577
+ begin
578
+ require 'json_schemer'
579
+ JSONSchemer.schema(schema_hash)
580
+ end
581
+ end
582
+
583
+ # @return [Hash] Schema of `transferd.json`
584
+ def schema_hash
585
+ # the registry asserts that the schema is known
586
+ @schema_hash ||= Schema::Registry.instance.reader(DAEMON_CONFIG_SCHEMA).current
587
+ end
588
+
589
+ # @param config [Hash] Configuration to validate
590
+ # @param existing [Hash] Content of the existing file
591
+ # @param file [String, nil] Path of the existing file
592
+ # @return [Array<String>] error messages, empty if valid
593
+ def validate(config, existing, file)
594
+ schema.validate(config).map do |error|
595
+ # tell the user when the faulty value comes from a file that was not written by this call
596
+ path = error['data_pointer'].to_s.split('/').drop(1)
597
+ origin = file && in_hash?(existing, path) ? " (existing file: #{file})" : ''
598
+ "#{error['error']}#{origin}"
599
+ end
600
+ end
601
+
602
+ # @param hash [Hash] Hash to look into
603
+ # @param path [Array] Keys of nested Hashes
604
+ # @return [Boolean] `true` if the path exists in hash
605
+ def in_hash?(hash, path)
606
+ return false if path.empty?
607
+ path.reduce(hash) do |node, key|
608
+ return false unless node.is_a?(Hash) && node.key?(key)
609
+ node[key]
610
+ end
611
+ true
612
+ end
613
+ end
614
+ end
615
+ end
616
+ end
617
+ end