Class: Aspera::Cli::Runner

Inherits:
Object
  • Object
show all
Defined in:
lib/aspera/cli/runner.rb

Overview

The main CLI class

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(argv, main_folder: nil, config_file: nil, vault: nil, vault_password: nil) ⇒ nil

Minimum initialization, no exception raised

Parameters:

  • argv (Array<String>) —

    command line arguments

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

    main folder set by the program (not by the arguments), e.g. the one of the MCP server; nil: option home

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

    configuration file set by the program (not by the arguments), e.g. the one of the MCP server; nil: option config_file

  • vault (Hash, nil) (defaults to: nil) —

    option vault set by the program (not by the arguments), e.g. the one of the MCP server; nil: option vault

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

    option vault_password set by the program (not by the arguments); nil: option vault_password



46
47
48
49
50
51
52
53
54
55
56
# File 'lib/aspera/cli/runner.rb', line 46

def initialize(argv, main_folder: nil, config_file: nil, vault: nil, vault_password: nil)
  @main_folder = main_folder
  @config_file = config_file
  @vault = vault
  @vault_password = vault_password
  # Dumped (trace2) with secrets hidden by `CommandLine`
  @argv = argv
  @option_help = false
  @option_show_config = false
  @context = Context.new
end

Instance Attribute Details

#context ⇒ Object (readonly)

Returns the value of attribute context.



58
59
60
# File 'lib/aspera/cli/runner.rb', line 58

def context
  @context
end

Instance Method Details

#option_log=(value) ⇒ Object

on_set callback of the log option (dot-notation sub-properties): level, type, format, secrets

Parameters:

  • value (Hash) —

    sub-properties to set



244
245
246
247
248
249
250
251
252
253
254
255
# File 'lib/aspera/cli/runner.rb', line 244

def option_log=(value)
  Aspera.assert_type(value, Hash)
  value.each do |k, v|
    case k.to_sym
    when :level   then Log.instance.level = v.to_sym
    when :type    then Log.instance.logger_type = v.to_sym
    when :format  then Log.instance.formatter = v
    when :secrets then Secret::Hider.instance.log_secrets = Parser.get_from_list(v.to_s, 'log secrets', BoolValue::ALL)
    else Aspera.error_unexpected_value(k) { 'log sub-option (level, type, format, secrets)' }
    end
  end
end

#option_temp=(value) ⇒ Object

on_set callback of the temp option (dot-notation sub-properties): folder, clean, expiry A plain value is the folder. Values are validated against schema TempOptions.

Parameters:

  • value (Hash) —

    sub-properties to set



260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
# File 'lib/aspera/cli/runner.rb', line 260

def option_temp=(value)
  Aspera.assert_type(value, Hash)
  value.each do |k, v|
    case k.to_sym
    when :folder then TempFileManager.instance.global_temp = v
    when :clean  then TempFileManager.instance.cleanup_on_exit = Parser.get_from_list(v.to_s, 'temp clean', BoolValue::ALL)
    when :expiry
      TempFileManager.instance.expiry_sec =
        case v
        when nil, false then nil
        when Numeric then v
        else Units::Duration.new(v).to_unit('s')
        end
    else Aspera.error_unexpected_value(k) { 'temp sub-option (folder, clean, expiry)' }
    end
  end
rescue ParameterError => e
  raise BadArgument, "Option temp: #{e.message}"
end

#option_ui=(value) ⇒ Object

on_set callback of the ui option (dot-notation sub-properties): mode, web_auth, hidden_silent, command A plain value is the mode. Values are validated against schema UiOptions.

Parameters:

  • value (Hash) —

    sub-properties to set



218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
# File 'lib/aspera/cli/runner.rb', line 218

def option_ui=(value)
  Aspera.assert_type(value, Hash)
  value.each do |k, v|
    case k.to_sym
    when :mode
      Environment.instance.url_method =
        case v.to_s
        when 'auto' then Environment.instance.default_gui_mode
        when 'terminal', 'text' then :text
        when 'browser', 'graphical' then :graphical
        else Aspera.error_unexpected_value(v, type: BadArgument) { 'ui.mode' }
        end
    when :web_auth
      Aspera.assert_values(v.to_s, %w[port paste], type: BadArgument) { 'ui.web_auth' }
      Environment.instance.web_auth = v.to_sym
    when :hidden_silent
      Environment.instance.hidden_silent = BoolValue.true?(Parser.get_from_list(v.to_s, 'ui hidden_silent', BoolValue::ALL))
    when :command
      Environment.instance.browser_command = v.nil? || v.empty? ? nil : v.map(&:to_s)
    else Aspera.error_unexpected_value(k, type: BadArgument) { 'ui sub-option (mode, web_auth, hidden_silent, command)' }
    end
  end
end

#result_usage(plugin: nil) ⇒ Result::Text

Return usage as a Result::Text (used by run_with_result, no display, no exit).

Parameters:

  • plugin (Plugins::Base, nil) (defaults to: nil) —

    plugin instance to show subcommands for

Returns:



211
212
213
# File 'lib/aspera/cli/runner.rb', line 211

def result_usage(plugin: nil)
  Result::Text.new(usage_text(plugin: plugin))
end

#run ⇒ nil

Main entry point: execute the command, display results, exit on error.

Returns:

  • (nil)


138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
# File 'lib/aspera/cli/runner.rb', line 138

def run
  exception_info = nil
  begin
    result = run_with_result
    @context.formatter.display_results(result) if result
  rescue Net::SSH::AuthenticationFailed => e;    exception_info = {e: e, t: 'SSH', security: true, exit: ExitCode::AUTH}
  rescue OpenSSL::SSL::SSLError => e;            exception_info = {e: e, t: 'SSL', exit: ExitCode::NETWORK}
  rescue Cli::BadArgument, ParameterError => e;  exception_info = {e: e, t: 'Argument', usage: true, exit: ExitCode::USAGE}
  rescue Cli::MissingArgument => e;              exception_info = {e: e, t: 'Missing', exit: ExitCode::USAGE}
  rescue Cli::BadIdentifier, EntityNotFound, Aspera::Secret::NotFound => e
    exception_info = {e: e, t: 'Identifier', exit: ExitCode::NOT_FOUND}
  rescue AuthenticationError, Aspera::Secret::AuthenticationError => e
    exception_info = {e: e, t: 'Authentication', exit: ExitCode::AUTH}
  rescue Cli::SchemaRequest => e;                exception_info = {e: e, t: 'Schema', exit: ExitCode::SUCCESS}
  rescue Cli::PollConditionNotMet => e;          exception_info = {e: e, t: 'Poll', exit: ExitCode::ERROR}
  rescue Cli::Error => e;                        exception_info = {e: e, t: 'Tool', usage: true, exit: ExitCode::ERROR}
  rescue EnvironmentError => e;                  exception_info = {e: e, t: 'Environment', exit: ExitCode::ERROR}
  # Label `Vault`, as the option: with `Secret`, the log would hide a message of one word, as a secret value
  rescue Aspera::Secret::Error => e;             exception_info = {e: e, t: 'Vault', exit: ExitCode::ERROR}
  rescue Aspera::Ssh::Error => e;                exception_info = {e: e, t: 'SSH', exit: ExitCode::ERROR}
  rescue Rest::CallError => e;                   exception_info = {e: e, t: 'Rest', exit: ExitCode.for_call_error(e)}
  rescue *NETWORK_ERRORS => e;                   exception_info = {e: e, t: 'Network', exit: ExitCode::NETWORK}
  rescue StandardError => e;                     exception_info = other_error_info(e)
  rescue Interrupt => e;                         exception_info = {e: e, t: 'Interruption', debug: true, exit: ExitCode::INTERRUPTED}
  end
  # 1- processing of error condition
  unless exception_info.nil?
    Log.log.warn(exception_info[:e].message) if Log.instance.logger_type.eql?(:syslog) && exception_info[:security]
    Log.log.error { "#{exception_info[:t]}: #{exception_info[:e].message}" } unless exception_info[:e].is_a?(Cli::SchemaRequest)
    Log.log.info { "Location: #{plugin_location(exception_info[:e])}" } if exception_info[:debug] && plugin_location(exception_info[:e])
    Log.log.debug { (['Backtrace:'] + exception_info[:e].backtrace).join("\n") } if exception_info[:debug]
    @context.formatter.display_message(:error, 'Use option -h to get help.') if exception_info[:usage]
    Hints.hint_for(exception_info[:e], @context.formatter)
    if exception_info[:e].is_a?(Cli::SchemaRequest)
      Log.log.info { "#{exception_info[:t]}: #{exception_info[:e].message}" }
      display_schema(exception_info[:e].path)
    end
  end
  # 2- processing of unprocessed arguments (skip when help was displayed: sub-commands are not consumed)
  # With `show_config`, the command is not executed: its arguments are not consumed, but unknown options are reported
  unless @option_help
    @context.options&.final_errors(after_error: !exception_info.nil? || @option_show_config)&.each do |msg|
      Log.log.error { "Argument: #{msg}" }
      exception_info = {e: Exception.new(msg), t: 'UnusedArg', exit: ExitCode::USAGE} if exception_info.nil?
    end
  end
  # 3- exit on error
  unless exception_info.nil?
    if Log.log.debug?
      # Same display as an uncaught exception, but keeps the exit code
      $stderr.puts(exception_info[:e].full_message) # rubocop:disable Style/StderrPuts
    elsif exception_info[:debug]
      @context.formatter.display_message(:error, 'Use --log-level=debug to get more details.')
    end
    exit_code = exception_info[:exit]
    # Nagios plugins report the failure of the check itself as UNKNOWN
    exit_code = Nagios::UNKNOWN if !exit_code.eql?(ExitCode::SUCCESS) && @context.formatter&.format_type.eql?(:nagios)
    ::Process.exit(exit_code)
  end
  return
end

#run_with_result ⇒ Result?

Execute the command and return the raw Result object. Pure computation: no display, no Process.exit - raises on any error.

Returns:

  • (Result, nil) —

    the result of the command, or nil if nothing to execute



63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
# File 'lib/aspera/cli/runner.rb', line 63

def run_with_result
  init_agents_and_options
  @context.config.add_plugin_lookup_folders
  Plugins::Factory.instance.add_plugins_from_lookup_folders
  # Config is created before the plugin folders are added: modules mounted on config by their bundles, with their options
  Plugins::Config.include_mounts(Plugins::Factory.instance.registry)
  Plugins::Config.declare_options(@context.options, target: @context.config, parse: true)
  # The service `transfer` declares its options (after those of config), and parses option `transfer`: agents of the bundles of the plugin folders are known
  @context.transfer
  # Help requested without command? Show global options + plugin list
  return result_usage if @option_help && @context.options.command_or_arg_empty?
  # Shell completion is executed on each `Tab`: no network access
  @context.config.periodic_check_newer_gem_version unless @context.options.next_arguments?(COMPLETION_COMMAND)
  # A plugin that cannot be loaded is not in the list of commands: give the reason, not an unknown command
  Plugins::Factory.instance.unavailable_plugins.each do |name, reason|
    raise Cli::Error, reason if @context.options.next_arguments?([name.to_s])
  end
  command_sym =
    if @option_show_config && @context.options.command_or_arg_empty?
      COMMAND_CONFIG
    else
      @context.options.get_next_command(Plugins::Factory.instance.plugin_list.unshift(COMMAND_HELP))
    end
  @context.options.fail_on_missing_mandatory = false if @option_help || @option_show_config
  case command_sym
  when COMMAND_HELP
    return result_usage
  when COMMAND_CONFIG
    command_plugin = @context.config
  else
    command_plugin = get_plugin_instance_with_options(command_sym)
    @context.options.parse_options!
  end
  # --help after a plugin name: if no positional args remain, show plugin-level help now.
  # If args remain (e.g. `ascli aoc files -h`), let the dispatch consume them and
  # intercept --help at the right depth via Cli::HelpRequest.
  return result_usage(plugin: command_plugin) if @option_help && @context.options.command_or_arg_empty?
  if @option_show_config
    result = Result::SingleObject.new(@context.options.known_options(only_defined: true).stringify_keys)
    @context.presets.save_if_needed
    @context.transfer.shutdown
    TempFileManager.instance.cleanup
    return result
  end
  execute_command = true
  lock_port = @context.options.get_option(:lock_port)
  if !lock_port.nil?
    begin
      Log.log.debug { "Opening lock port #{lock_port}" }
      @tcp_server = TCPServer.new('127.0.0.1', lock_port)
    rescue StandardError => e
      execute_command = false
      Log.log.warn { "Another instance is already running (#{e.message})." }
    end
  end
  pid_file = @context.options.get_option(:pid_file)
  if !pid_file.nil?
    File.write(pid_file, ::Process.pid)
    Log.log.debug { "Wrote pid #{::Process.pid} to #{pid_file}" }
    at_exit { File.delete(pid_file) }
  end
  begin
    result = command_plugin.execute_action if execute_command
  rescue Cli::HelpRequest => e
    return result_usage(plugin: e.plugin)
  ensure
    @context.presets.save_if_needed
    @context.transfer.shutdown
    TempFileManager.instance.cleanup
  end
  return result
end

#show_usage(plugin: nil) ⇒ nil

Display usage information and exit (used by the interactive CLI).

Parameters:

  • plugin (Plugins::Base, nil) (defaults to: nil) —

    plugin instance to show subcommands for

Returns:

  • (nil)


203
204
205
206
# File 'lib/aspera/cli/runner.rb', line 203

def show_usage(plugin: nil)
  @context.formatter.display_message(:error, usage_text(plugin: plugin))
  ::Process.exit(0)
end