Class: Aspera::Plugins::Transferd::Service

Inherits:
Object
  • Object
show all
Defined in:
lib/aspera/plugins/transferd/service.rb

Overview

Run the transfer daemon as a system service: configuration of transferd.json and systemd unit

Defined Under Namespace

Classes: Host

Constant Summary collapse

DEFAULT_SERVICE_NAME =
'aspera-transferd'
DEFAULT_USER =
'asperadaemon'
DEFAULT_UNIT_DIR =
'/etc/systemd/system'
DEFAULT_AFTER =
['network.target'].freeze
CONFIG_FILE =

Default location of the configuration file, also the default of the daemon

Products::Transferd::SERVICE_CONFIG_FILE
DAEMON_CONFIG_SCHEMA =

Schemas of the bundle (manifest schemas): configuration file of the daemon, parameters of the service

'transferd'
SERVICE_OPTIONS =
'transferd_opts:components.schemas.ServiceOptions'
SERVICE_CONFIG =
'transferd_opts:components.schemas.TransferdServiceConfig'
ENV_OVERRIDES =

Environment variables of the daemon that override the configuration file

%w[TRANSFERD_ADDRESS TRANSFERD_PORT TRANSFERD_MGMT_ADDRESS TRANSFERD_MGMT_PORT].freeze
'current'

Class Method Summary collapse

Class Method Details

.assert_supported(host, dry_run: false) ⇒ Object

Refuse to run on a host that cannot run the service: systemd on Linux, as root. Not checked with dry_run: the actions are only shown, so that it works everywhere.

Parameters:

  • host (Host) —

    Access to the system

  • dry_run (Boolean) (defaults to: false) —

    true: change nothing, no check

Raises:

  • (Error) —

    if the host is not supported or the user is not root



331
332
333
334
335
336
# File 'lib/aspera/plugins/transferd/service.rb', line 331

def assert_supported(host, dry_run: false)
  return if dry_run
  Aspera.assert(host.os.eql?(Environment::OS_LINUX), type: EnvironmentError) { "The service requires Linux with systemd, this is: #{host.os}" }
  Aspera.assert(host.systemctl?, type: EnvironmentError) { 'The service requires systemd: command systemctl not found' }
  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' }
end

.check_version(sdk_folder, host: Host.new) ⇒ String?

Warn (never fail) if the SDK is not the version that the configuration schema matches.

Parameters:

  • sdk_folder (String) —

    Folder of the SDK, or link current of the layout

  • host (Host) (defaults to: Host.new) —

    Access to the system

Returns:

  • (String, nil) —

    The warning, or nil if versions are the same or the version is unknown



347
348
349
350
351
352
353
354
355
356
# File 'lib/aspera/plugins/transferd/service.rb', line 347

def check_version(sdk_folder, host: Host.new)
  exe = executable(sdk_folder)
  return unless File.exist?(exe)
  sdk_version = host.run(exe, 'version').first[/\d+\.\d+\.\d+/]
  return if sdk_version.nil? || sdk_version.eql?(schema_version)
  relation = Gem::Version.new(sdk_version) > Gem::Version.new(schema_version) ? 'newer' : 'older'
  message = "transferd #{sdk_version} is #{relation} than the version of the configuration schema (#{schema_version}): some settings may be unknown or refused"
  Log.log.warn(message)
  return message
end

.config(existing, overrides, sdk_folder, file: nil) ⇒ Hash

Build the content of transferd.json. Order of precedence: values computed from sdk_folder, then existing, then overrides. A key set to nil in overrides is removed.

Parameters:

  • existing (Hash, nil) —

    Content of the existing configuration file, nil or empty if none

  • overrides (Hash) —

    Values given by the user (section config of the user parameter)

  • sdk_folder (String) —

    Folder of the SDK, used for fasp_runtime

  • file (String, nil) (defaults to: nil) —

    Path of the existing file, for error messages

Returns:

  • (Hash) —

    Validated configuration, with String keys

Raises:

  • (ParameterError) —

    if the result does not conform to the schema of the daemon



157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
# File 'lib/aspera/plugins/transferd/service.rb', line 157

def config(existing, overrides, sdk_folder, file: nil)
  Aspera.assert_type(existing, Hash, NilClass) { 'existing' }
  Aspera.assert_type(overrides, Hash) { 'overrides' }
  Aspera.assert_type(sdk_folder, String) { 'sdk_folder' }
  existing = json_hash(existing || {})
  computed = {
    'fasp_runtime' => {
      'use_embedded' => false,
      'user_defined' => {'bin' => sdk_folder, 'etc' => sdk_folder}
    }
  }
  result = merge(merge(computed, existing), json_hash(overrides))
  auth = result['authentication']
  auth['api_key'] = SecureRandom.hex(API_KEY_BYTES) if auth.is_a?(Hash) && auth['enabled'].eql?(true) && !auth.key?('api_key')
  errors = validate(result, existing, file)
  Aspera.assert(errors.empty?, type: ParameterError) { "Invalid transferd configuration:\n#{errors.join("\n")}" }
  return result
end

.configure(user_config, sdk_folder, host: Host.new, dry_run: false) ⇒ Array<String>

Merge CONFIG in the configuration file, write the unit, then (re)start the service.

Returns:

  • (Array<String>) —

    Actions done, or to do with dry_run



260
261
262
# File 'lib/aspera/plugins/transferd/service.rb', line 260

def configure(user_config, sdk_folder, host: Host.new, dry_run: false)
  run_steps(configure_steps(user_config, sdk_folder, host, dry_run), dry_run)
end

.install(user_config, sdk_folder, host: Host.new, dry_run: false, install_sdk: nil, version: nil) ⇒ Array<String>

Install the SDK if not present, then configure and start the service. With the layout, the SDK is installed in <prefix>/<version>, the link current is set to it, and it is set back to the previous version if the service cannot be started.

Parameters:

  • user_config (Hash) —

    CONFIG: sections service and config

  • sdk_folder (String) —

    Folder of the SDK, or link current of the layout

  • host (Host) (defaults to: Host.new) —

    Access to the system

  • dry_run (Boolean) (defaults to: false) —

    true: change nothing, only return the actions

  • install_sdk (#call) (defaults to: nil) —

    Installs the SDK, called if transferd is not there. With the layout it receives the folder of the version, else no argument.

  • version (String) (defaults to: nil) —

    Version to install and use, mandatory with the layout, else ignored

Returns:

  • (Array<String>) —

    Actions done, or to do with dry_run



238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
# File 'lib/aspera/plugins/transferd/service.rb', line 238

def install(user_config, sdk_folder, host: Host.new, dry_run: false, install_sdk: nil, version: nil)
  steps = []
  previous = nil
  if layout?(sdk_folder)
    folder = version_folder(sdk_folder, version)
    previous = link_target(sdk_folder)
    unless File.exist?(executable(folder))
      Aspera.assert(!install_sdk.nil?, type: ParameterError) { "SDK is not installed in #{folder}" }
      steps << ["install the SDK in #{folder}", -> { install_sdk.call(folder) }]
    end
    steps << ["link #{sdk_folder} to #{version}", -> { switch_link(sdk_folder, version) }] unless previous.eql?(version)
  elsif !File.exist?(executable(sdk_folder))
    Aspera.assert(!install_sdk.nil?, type: ParameterError) { "SDK is not installed in #{sdk_folder}" }
    steps << ["install the SDK in #{sdk_folder}", install_sdk]
  end
  steps.concat(configure_steps(user_config, sdk_folder, host, dry_run))
  return run_steps(steps, dry_run) unless layout?(sdk_folder)
  with_rollback(sdk_folder, previous, service_options(user_config), host) { run_steps(steps, dry_run) }
end

.layout?(sdk_folder) ⇒ Boolean

Layout of versions side by side: <prefix>/<version> folders and the link <prefix>/current. It is used when the SDK folder is named current. The paths in the unit and in transferd.json go through the link, so that switching the link and restarting the service is enough to change the version.

Parameters:

  • sdk_folder (String) —

    Folder of the SDK

Returns:

  • (Boolean) —

    true if the layout is used



181
182
183
# File 'lib/aspera/plugins/transferd/service.rb', line 181

def layout?(sdk_folder)
  File.basename(sdk_folder).eql?(CURRENT_LINK)
end

.resolve(sdk_folder) ⇒ String

Returns Folder of the version in use if the layout is used, else sdk_folder as is.

Parameters:

  • sdk_folder (String) —

    Folder of the SDK

Returns:

  • (String) —

    Folder of the version in use if the layout is used, else sdk_folder as is



187
188
189
# File 'lib/aspera/plugins/transferd/service.rb', line 187

def resolve(sdk_folder)
  layout?(sdk_folder) && File.symlink?(sdk_folder) ? File.realpath(sdk_folder) : sdk_folder
end

.schema_version ⇒ String

Returns Version of transferd that the configuration schema matches.

Returns:

  • (String) —

    Version of transferd that the configuration schema matches



339
340
341
# File 'lib/aspera/plugins/transferd/service.rb', line 339

def schema_version
  schema_hash['$comment'].to_s[/transferd (\d+\.\d+\.\d+)/, 1]
end

.service_options(user_config) ⇒ Hash

Returns Validated service section with defaults, plus config section as overrides.

Parameters:

  • user_config (Hash) —

    CONFIG

Returns:

  • (Hash) —

    Validated service section with defaults, plus config section as overrides



311
312
313
314
315
316
317
318
319
320
321
322
323
324
# File 'lib/aspera/plugins/transferd/service.rb', line 311

def service_options(user_config)
  Aspera.assert_type(user_config, Hash) { 'CONFIG' }
  conf = json_hash(user_config)
  service = conf['service'] || {}
  errors = Schema::Validator.instance.errors(service, SERVICE_OPTIONS)
  Aspera.assert(errors.empty?, type: ParameterError) { "Invalid service parameters:\n#{errors.join("\n")}" }
  return {
    'name'        => DEFAULT_SERVICE_NAME,
    'user'        => DEFAULT_USER,
    'unit_dir'    => DEFAULT_UNIT_DIR,
    'after'       => DEFAULT_AFTER,
    'environment' => {}
  }.merge(service).merge('overrides' => conf['config'] || {})
end

.status(user_config, sdk_folder, host: Host.new) ⇒ Hash

State of the service. The API key is never returned.

Returns:

  • (Hash) —

    Version, state of the service, endpoint, and whether it listens



266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
# File 'lib/aspera/plugins/transferd/service.rb', line 266

def status(user_config, sdk_folder, host: Host.new)
  opts = service_options(user_config)
  unit_file = host.path(File.join(opts['unit_dir'], "#{opts['name']}.service"))
  config_file = host.path(CONFIG_FILE)
  # only booleans and the endpoint are read: the API key is never copied in the result
  config = File.exist?(config_file) ? read_config(config_file) : {}
  env = unit_file_environment(unit_file)
  address = env['TRANSFERD_ADDRESS'] || config['address'] || '127.0.0.1'
  port = (env['TRANSFERD_PORT'] || config['port']).to_i
  version = File.exist?(executable(sdk_folder)) ? host.run(executable(sdk_folder), 'version').first : ''
  return {
    'service'        => opts['name'],
    'sdk_folder'     => resolve(sdk_folder),
    'installed'      => File.exist?(unit_file),
    'version'        => version[/\d+\.\d+\.\d+/],
    'enabled'        => host.run('systemctl', 'is-enabled', opts['name']).first.strip,
    'active'         => host.run('systemctl', 'is-active', opts['name']).first.strip,
    'config_file'    => CONFIG_FILE,
    'address'        => address,
    'port'           => port,
    'listening'      => port.positive? && host.listening?(connect_address(address), port),
    'authentication' => config.dig('authentication', 'enabled').eql?(true),
    'tls'            => config.dig('tls', 'enabled').eql?(true),
    'environment'    => env
  }
end

.uninstall(user_config, host: Host.new, dry_run: false, purge: false) ⇒ Array<String>

Stop and remove the service.

Parameters:

  • purge (Boolean) (defaults to: false) —

    Also remove the configuration file and the log folder

Returns:

  • (Array<String>) —

    Actions done, or to do with dry_run



296
297
298
299
300
301
302
303
304
305
306
307
# File 'lib/aspera/plugins/transferd/service.rb', line 296

def uninstall(user_config, host: Host.new, dry_run: false, purge: false)
  opts = service_options(user_config)
  unit_file = host.path(File.join(opts['unit_dir'], "#{opts['name']}.service"))
  steps = []
  if File.exist?(unit_file)
    steps << ["stop and disable #{opts['name']}", -> { systemctl(host, 'disable', '--now', opts['name'], check: false) }]
    steps << ["remove #{unit_file}", -> { File.delete(unit_file) }]
    steps << ['reload systemd', -> { systemctl(host, 'daemon-reload') }]
  end
  steps.concat(purge_steps(host)) if purge
  run_steps(steps, dry_run)
end

.unit(options = {}) ⇒ String

Generate the text of the systemd unit file.

Parameters:

  • options (Hash) (defaults to: {}) —

    Service and execution options (from CONFIG or specific keys)

Returns:

  • (String) —

    systemd unit file content



111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
# File 'lib/aspera/plugins/transferd/service.rb', line 111

def unit(options = {})
  Aspera.assert_type(options, Hash) { 'options' }
  opts = json_hash(options)
  opts = opts['service'].merge(opts) if opts['service'].is_a?(Hash)
  executable = opts['executable'] || opts['exec'] || opts['bin'] ||
    (opts['sdk_folder'] ? File.join(opts['sdk_folder'], 'bin', 'transferd') : '/opt/aspera/transferd/bin/transferd')
  config_file = opts['config_file'] || opts['config'] || opts['config_path'] || opts['file'] || '/etc/transferd/transferd.json'
  user = opts['user'] || DEFAULT_USER
  group = opts['group']
  after = opts['after'] || DEFAULT_AFTER
  after = Array(after).join(' ')
  env = opts['environment'] || {}

  lines = [
    '[Unit]',
    "Description=#{opts['description'] || 'IBM Aspera Transfer Daemon'}",
    "After=#{after}",
    '',
    '[Service]',
    "Type=#{opts['type'] || 'simple'}",
    "User=#{user}"
  ]
  lines << "Group=#{group}" if group && !group.empty?
  lines << "ExecStart=#{executable} --config #{config_file}"
  lines << "Restart=#{opts['restart'] || 'always'}"
  env.keys.sort.each do |k|
    lines << %Q(Environment="#{k}=#{env[k]}")
  end
  lines.push(
    '',
    '[Install]',
    "WantedBy=#{opts['wanted_by'] || 'multi-user.target'}",
    ''
  )
  lines.join("\n")
end

.use(user_config, sdk_folder, version, host: Host.new, dry_run: false) ⇒ Array<String>

Switch the link current to an installed version and restart the service. If the restart fails, the link is set back to the previous version and the service is restarted again.

Parameters:

  • user_config (Hash) —

    CONFIG

  • sdk_folder (String) —

    Link current of the layout

  • version (String) —

    Installed version

Returns:

  • (Array<String>) —

    Actions done, or to do with dry_run; empty if the version is already in use



210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
# File 'lib/aspera/plugins/transferd/service.rb', line 210

def use(user_config, sdk_folder, version, host: Host.new, dry_run: false)
  assert_layout(sdk_folder)
  folder = version_folder(sdk_folder, version)
  Aspera.assert(File.exist?(executable(folder)), type: ParameterError) { "Version #{version} is not installed in #{folder}" }
  previous = link_target(sdk_folder)
  return [] if previous.eql?(version)
  opts = service_options(user_config)
  steps = [["link #{sdk_folder} to #{version}", -> { switch_link(sdk_folder, version) }]]
  if File.exist?(unit_path(host, opts))
    config_file = host.path(CONFIG_FILE)
    conf = File.exist?(config_file) ? read_config(config_file) : {}
    steps << ["restart #{opts['name']}", -> { systemctl(host, 'restart', opts['name']) }]
    steps.concat(wait_steps(host, opts, conf))
  end
  return with_rollback(sdk_folder, previous, opts, host) { run_steps(steps, dry_run) }
end

.versions(sdk_folder) ⇒ Array<Hash>

Returns Installed versions, oldest first: version, folder, current.

Parameters:

  • sdk_folder (String) —

    Link current of the layout

Returns:

  • (Array<Hash>) —

    Installed versions, oldest first: version, folder, current



193
194
195
196
197
198
199
200
201
202
# File 'lib/aspera/plugins/transferd/service.rb', line 193

def versions(sdk_folder)
  assert_layout(sdk_folder)
  prefix = File.dirname(sdk_folder)
  current = link_target(sdk_folder)
  names = Dir.exist?(prefix) ? Dir.children(prefix) : []
  return names
      .select { |name| name.match?(VERSION_PATTERN) && File.exist?(executable(File.join(prefix, name))) }
      .sort_by { |name| Gem::Version.new(name) }
      .map { |name| {'version' => name, 'folder' => File.join(prefix, name), 'current' => name.eql?(current)} }
end