Class: Aspera::Plugins::Orchestrator::Commands

Inherits:
Cli::Plugins::Base show all
Includes:
Cli::Plugins::BasicAuth
Defined in:
lib/aspera/plugins/orchestrator/commands.rb

Overview

Aspera Orchestrator

Constant Summary collapse

API_SCHEMA =

Key of the Orchestrator API in the schemas of the bundle (manifest)

'orchestrator'

Constants inherited from Cli::Plugins::Base

Cli::Plugins::Base::FILTER_ARGS

Instance Attribute Summary

Attributes inherited from Cli::Plugins::Base

#context, #help_path

Class Method Summary collapse

Instance Method Summary collapse

Methods included from Cli::Plugins::BasicAuth

#basic_auth_api, #basic_auth_params, included

Methods included from Cli::Option::Declarator

#declare_options, #option, #option_specs, #register_option_spec

Methods inherited from Cli::Plugins::Base

#action_for, application_name, #bulk_result, #check_argument_access, command, command_registry, commands_under, #config, #crud_api, crud_commands, declare_options, define_action_method, #dispatch_child, #dispatch_from_registry, #dispatch_leaf, #dispatch_mount, #entity_create, #entity_delete, #entity_list, #entity_modify, entity_noun, #entity_res_path, #entity_show, #execute_action, #execute_leaf, file_matcher, #formatter, #generate_help, #http_config, include_mounts, #initialize, #invoke_action, operation_description, option_sources, option_specs, #options, #persistency, #poll_result, #presets, #progress_bar, #query_read_delete, register_option_spec, #resolve_argument, #resolve_arguments, #transfer, use_options, used_option_sources, #validate_registry

Constructor Details

This class inherits a constructor from Aspera::Cli::Plugins::Base

Class Method Details

.detect(address_or_url) ⇒ Hash, NilClass

Returns:



79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
# File 'lib/aspera/plugins/orchestrator/commands.rb', line 79

def detect(address_or_url)
  address_or_url = "https://#{address_or_url}" unless address_or_url.match?(%r{^[a-z]{1,6}://})
  urls = [address_or_url]
  urls.push("#{address_or_url}#{STANDARD_PATH}") unless address_or_url.end_with?(STANDARD_PATH)
  error = nil
  urls.each do |base_url|
    next unless base_url.match?(%r{^https?://})
    api = Rest::Client.new(base_url: base_url)
    data, http = api.read(TEST_ENDPOINT, query: {format: :json}, ret: :both)
    next unless data['remote_orchestrator_info']
    url = http.uri.to_s
    return {
      version: data['remote_orchestrator_info']['orchestrator-version'],
      url:     url[0..url.index(TEST_ENDPOINT) - 2]
    }
  rescue StandardError => e
    error = e
    Log.log.debug { "detect error: #{e}" }
  end
  raise error if error
  return
end

Instance Method Details

#action_health ⇒ Object



500
501
502
503
504
505
506
507
508
509
510
# File 'lib/aspera/plugins/orchestrator/commands.rb', line 500

def action_health(**)
  nagios = Nagios.new
  begin
    info = call_ao('remote_node_ping', accept: Mime::XML, xml_opts: {'ForceArray' => false})
    nagios.add_ok('api', 'accessible')
    nagios.check_product_version('api', 'orchestrator', info['orchestrator-version'])
  rescue StandardError => e
    nagios.add_critical('node api', e.to_s)
  end
  Cli::Result::ObjectList.new(nagios.status_list)
end

#action_journal_files(book:) ⇒ Object

Files of the packages, and files without package, with the name of their package



525
526
527
528
529
# File 'lib/aspera/plugins/orchestrator/commands.rb', line 525

def action_journal_files(book:, **)
  report = call_ao("journal_files/#{URI.encode_uri_component(book)}")
  files = Array(report['Packages']).flat_map { |package| Array(package['files']).map { |file| {'package' => package['name']}.merge(file) } }
  Cli::Result::ObjectList.new(files + Array(report['Files']))
end

#action_monitors_list(type:) ⇒ Object

Monitors of work orders are wrapped in monitor-workorder



519
520
521
522
# File 'lib/aspera/plugins/orchestrator/commands.rb', line 519

def action_monitors_list(type:, **)
  monitors = call_ao("list_monitors/#{ANY_ID}", query: {monitor_type: type})
  Cli::Result::ObjectList.new(monitors.map { |monitor| monitor.is_a?(Hash) && monitor.size.eql?(1) && monitor.key?('monitor-workorder') ? monitor['monitor-workorder'] : monitor })
end

#action_workflows_check_import(file_path:) ⇒ Result

The argument file_path is a local path read by the command (access: :read): checked against the security level when it is read.

Parameters:

  • file_path (String) —

    Workflow file

Returns:

  • (Result) —

    The issues found, or a status if none



661
662
663
664
665
# File 'lib/aspera/plugins/orchestrator/commands.rb', line 661

def action_workflows_check_import(file_path:, **)
  response = check_workflow(File.basename(file_path), File.binread(file_path))
  return Cli::Result::Status.new('no problem found') if response['issues'].empty?
  Cli::Result::ObjectList.new(response['issues'], fields: %w[severity code file path message])
end

#action_workflows_export(workflow_id:, export:) ⇒ Object

Without dependencies, the workflow file (YAML) is displayed. With dependencies, the package (binary) is saved in the destination folder.



610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
# File 'lib/aspera/plugins/orchestrator/commands.rb', line 610

def action_workflows_export(workflow_id:, export:, **)
  dependencies = export.transform_keys(&:to_s)['dependencies'].eql?(true)
  # Orchestrator exports dependencies for any value of the parameter
  begin
    resp = call_ao("export_workflow/#{workflow_id}", accept: nil, query: dependencies ? {export_with_dependencies: true} : nil, http: true)
  rescue Rest::CallError
    # Orchestrator 4.1.6 fails to build the package of some workflows (it is written in the folder it packs)
    Log.log.warn('Export with dependencies failed: export the workflow and each sub-workflow without dependencies instead') if dependencies
    raise
  end
  return Cli::Result::Text.new(resp.body) unless dependencies
  disposition = resp['Content-Disposition']
  file_name = disposition && Rest.parse_header(disposition)[:parameters][:filename]
  file_path = File.join(transfer.destination_folder(Aspera::Transfer::Spec::DIRECTION_RECEIVE), File.basename(file_name || "Workflow_#{workflow_id}.wkf"))
  File.binwrite(file_path, resp.body)
  Cli::Result::Status.new("Saved to: #{file_path}")
end

#action_workflows_find_constraints(filename:, add_as_revision: nil) ⇒ Object



684
685
686
687
688
689
690
691
692
693
694
# File 'lib/aspera/plugins/orchestrator/commands.rb', line 684

def action_workflows_find_constraints(filename:, add_as_revision: nil, **)
  found = server_constraints(filename, add_as_revision)
  rows = CONSTRAINT_KEYS.flat_map do |api_key, key|
    (found[api_key] || {}).map { |name, choices| {'type' => key, 'name' => name, 'choices' => choices} }
  end
  Array(found['missing plugins']).each do |name|
    rows.push({'type' => 'missing_plugins', 'name' => name, 'choices' => 'auto_enable_missing_plugins: true'})
  end
  return Cli::Result::Status.new('no conflict found (Orchestrator gives the same answer if the file does not exist)') if rows.empty?
  Cli::Result::ObjectList.new(rows, fields: %w[type name choices])
end

#action_workflows_import(file_path:, import: {}) ⇒ Object

The file is read by the command and uploaded as a multipart form: the argument file_path is a local path (access: :read), checked against the security level when it is read (ascli reads the file, so it is restricted like any local read, not like a transfer).

Parameters:

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

    Options: folder_id, publish, link_to_subworkflows



717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
# File 'lib/aspera/plugins/orchestrator/commands.rb', line 717

def action_workflows_import(file_path:, import: {}, **)
  import = import.transform_keys(&:to_s)
  file_name = File.basename(file_path)
  content = File.binread(file_path)
  check_workflow(file_name, content)['issues'].each do |issue|
    Log.log.warn { "#{issue['severity']}: #{[issue['file'], issue['path']].compact.join(' ')}: #{issue['message']} (#{issue['code']})" }
  end
  form = [
    ['import_file', content, {filename: file_name}],
    ['import_file_name', file_name]
  ]
  form.push(['folder_id', import['folder_id'].to_s]) if import.key?('folder_id')
  # `false` overrides the server option `publish_api_imported_workflow`
  form.push(['publish_workflow', import['publish'].to_s]) if import.key?('publish')
  # Orchestrator takes any value as true
  form.push(%w[link_to_subworkflows true]) if import['link_to_subworkflows'].eql?(true)
  result = call_ao('import_workflow', body: form, content_type: Mime::MULTIPART)
  # Other responses: nothing was imported
  if result.key?('plugins')
    raise Cli::Error, "Plugins could not be enabled: #{Array(result['plugins']).join(', ')}" \
      "#{" (missing dependencies: #{Array(result['missing_deps']).join(', ')})" unless Array(result['missing_deps']).empty?}"
  end
  if result.key?('dependencies')
    dependencies = result['dependencies'].values.flatten.filter_map { |d| "#{d['entity']} #{d['id_value']}" if d.is_a?(Hash) }
    raise Cli::Error, "Workflow dependencies are not included in the file (export with dependencies to a .wkf file): #{dependencies.uniq.join(', ')}"
  end
  Cli::Result::SingleObject.new(result['workflow'])
end

#action_workflows_import_with_constraints(payload:) ⇒ Object

The API expects an array of single-key objects, in a fixed order



758
759
760
761
762
763
# File 'lib/aspera/plugins/orchestrator/commands.rb', line 758

def action_workflows_import_with_constraints(payload:, **)
  payload = payload.transform_keys(&:to_s)
  check_import_constraints(payload)
  body = IMPORT_CONSTRAINT_ITEMS.map { |key, api_key| {api_key => payload.fetch(key) { key.end_with?('_constraints') ? {} : nil }} }
  Cli::Result::SingleObject.new(call_ao('import_with_constraints', body: body)['workflow'])
end

#action_workflows_list ⇒ Object

2.1/2.2 Initiate a workorder (async / synchronous)



548
549
550
551
552
553
# File 'lib/aspera/plugins/orchestrator/commands.rb', line 548

def action_workflows_list(**)
  Cli::Result::ObjectList.new(
    call_ao('workflows_list')['workflows']['workflow'],
    fields: %w[id portable_id name folder_id published_status published_revision_id latest_revision_id last_modification]
  )
end

#action_workflows_start(workflow_id:, parameters:, execution:) ⇒ Object



769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
# File 'lib/aspera/plugins/orchestrator/commands.rb', line 769

def action_workflows_start(workflow_id:, parameters:, execution:, **)
  execution = execution.transform_keys(&:to_s)
  unknown = execution.keys - WORKFLOW_START_KEYS
  Aspera.assert(unknown.empty?, type: Cli::BadArgument) { "Unknown keys in execution: #{unknown.join(', ')}, expected: #{WORKFLOW_START_KEYS.join(', ')}" }
  # Deprecated options, used when key not provided
  execution['synchronous'] = options.get_option(:synchronous) unless execution.key?('synchronous')
  result_location = options.get_option(:result)
  unless result_location.nil? || execution.key?('step') || execution.key?('variable')
    fields = result_location.split(':')
    Aspera.assert(fields.length == 2, type: Cli::BadArgument) { "Expects: work_step:result_name : #{result_location}" }
    execution['step'], execution['variable'] = fields
  end
  # POST /api/initiate with JSON body {workflow_id:, external_parameters:}
  json_body = {workflow_id: workflow_id.to_i, external_parameters: parameters}
  # control params passed as query string (not part of the spec requestBody)
  query_params = {}
  Aspera.assert_type(execution['synchronous'], NilClass, *Cli::BoolValue::TYPES, type: Cli::BadArgument) { 'synchronous' }
  query_params[:synchronous] = true if execution['synchronous'].eql?(true)
  # expected result for synchro call ?
  if execution.key?('step') || execution.key?('variable')
    Aspera.assert(execution['step'].is_a?(String) && execution['variable'].is_a?(String), type: Cli::BadArgument) { 'Both step and variable are required' }
    query_params[:explicit_output_step] = execution['step']
    query_params[:explicit_output_variable] = execution['variable']
    # implicitly, call is synchronous
    query_params[:synchronous] = true
  end
  # Work order information, or value of the explicit output (any JSON value)
  Cli::Result.auto(call_ao('initiate', body: json_body, query: query_params.empty? ? nil : query_params))
end

#action_workorders_worksteps(workorder_id:) ⇒ Object

Work steps of a work order, without the fields that are YAML dumps (see action_worksteps_status). Empty until the work order has created its steps.



541
542
543
544
545
# File 'lib/aspera/plugins/orchestrator/commands.rb', line 541

def action_workorders_worksteps(workorder_id:, **)
  steps = Array(call_ao("work_order_status/#{workorder_id}")['work_steps'])
  steps.each { |step| step.reject! { |_name, value| value.is_a?(String) && value.match?(YAML_DUMP) } }
  Cli::Result::ObjectList.new(steps)
end

#action_worksteps_status(workstep_id:) ⇒ Object

Fields of the work step that Orchestrator returns as YAML dumps of its Ruby objects (prerequisites, work_outputs...) are removed: they are not readable, and the inputs and outputs are also given as inputs and outputs.



533
534
535
536
537
# File 'lib/aspera/plugins/orchestrator/commands.rb', line 533

def action_worksteps_status(workstep_id:, **)
  status = call_ao("work_step_status/#{workstep_id}")
  status['work_step']&.reject! { |_name, value| value.is_a?(String) && value.match?(YAML_DUMP) }
  Cli::Result::SingleObject.new(status)
end

#api_orch ⇒ Rest::Client

Orchestrator REST API, built from CLI options on first use.

Returns:



462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
# File 'lib/aspera/plugins/orchestrator/commands.rb', line 462

def api_orch
  return @api_orch if @api_orch
  base_url = options.get_option(:url, mandatory: true)
  style = options.get_option(:auth_style, mandatory: true)
  apikey = options.get_option(:apikey)
  username = options.get_option(:username)
  password = options.get_option(:password)
  Aspera.assert(apikey.nil? || password.nil?, type: Cli::BadArgument) { 'apikey and password are mutually exclusive' }
  Aspera.assert(!username.nil? && !(apikey.nil? && password.nil?), type: Cli::BadArgument) { 'provide username with either password or apikey' }

  auth_params =
    case style
    when :basic
      Aspera.assert(apikey.nil?, type: Cli::BadArgument) { 'basic auth style cannot be used with apikey, use token or query' }
      {
        type:     :basic,
        username: username,
        password: password
      }
    when :query
      {type: :url, url_query: {'login' => username}.merge(apikey ? {'api_key' => apikey} : {'password' => password})} # HashiCorpIgnore
    when :token
      {
        type:         :oauth2,
        grant_method: :json_credentials,
        base_url:     base_url,
        path_token:   'api/login',
        token_field:  'token',
        json:         {username: username}.merge(apikey ? {api_key: apikey} : {password: password}) # HashiCorpIgnore
      }
    else Aspera.error_unexpected_value(style)
    end
  @api_orch = Rest::Client.new(
    base_url: base_url,
    auth:     auth_params
  )
end

#check_import_constraints(payload) ⇒ Object

Orchestrator fails or decides silently in these cases, which the web interface prevents:

  • plugins to enable but auto_enable_missing_plugins not true: the import fails with an internal error
  • resolution given for some conflicts only: the others are imported as copies, without error

Parameters:

  • payload (Hash) —

    Argument of import_with_constraints, with string keys

Raises:



700
701
702
703
704
705
706
707
708
709
710
711
712
# File 'lib/aspera/plugins/orchestrator/commands.rb', line 700

def check_import_constraints(payload)
  found = server_constraints(payload['filename'], payload['add_as_revision'])
  problems = []
  missing = Array(found['missing plugins'])
  problems.push("plugins are not enabled: #{missing.join(', ')}, set auto_enable_missing_plugins to true") unless missing.empty? || payload['auto_enable_missing_plugins'].eql?(true)
  CONSTRAINT_KEYS.each do |api_key, key|
    chosen = payload[key]
    next if chosen.nil? || chosen.empty?
    unresolved = (found[api_key] || {}).keys - chosen.keys.map(&:to_s)
    problems.push("#{key} not resolved for: #{unresolved.join(', ')} (see `workflows find_constraints`)") unless unresolved.empty?
  end
  raise Cli::BadArgument, "Import refused: #{problems.join('; ')}" unless problems.empty?
end

#check_workflow(file_name, content) ⇒ Hash

Check of a workflow file, for problems that Orchestrator does not detect on import: it imports an invalid workflow, which then fails to publish or to run. This is the only place that knows how the check is done: it is done locally, because Orchestrator has no such API. When it has one (same request as import_workflow), replace the body by a call, e.g. call_ao('check_workflow', body: [['import_file', content, {filename: file_name}], ['import_file_name', file_name]], content_type: Mime::MULTIPART) The response is a Hash, see WorkflowChecker. Templates and inputs of steps are checked with the specifications of plugins (see plugins spec show), when they can be read.

Parameters:

  • file_name (String) —

    Name of the workflow file (.yml or .wkf)

  • content (String) —

    Bytes of the file

Returns:

  • (Hash) —

    valid (Boolean), file_name, issues (list of Hash: severity, code, file, path, message)



637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
# File 'lib/aspera/plugins/orchestrator/commands.rb', line 637

def check_workflow(file_name, content)
  require_relative 'workflow_checker'
  specs = nil
  specs_error = nil
  begin
    specs = plugin_specs
  rescue StandardError => e
    specs_error = e.message
  end
  response = WorkflowChecker.check(file_name: file_name, content: content, specs: specs)
  unless specs_error.nil?
    response['issues'].push({
      'severity' => 'warning',
      'code'     => 'plugins.specs_unavailable',
      'path'     => 'templates',
      'message'  => "plugin specifications not read (#{specs_error}): templates and inputs of steps are not checked"
    })
  end
  response
end

#development_document(document) ⇒ String

The documents of workflows development are read from GitHub: does not require access to Orchestrator

Parameters:

  • document (Symbol) —

    One of DOC_URLS keys

Returns:



558
559
560
561
562
563
564
# File 'lib/aspera/plugins/orchestrator/commands.rb', line 558

def development_document(document)
  require_relative '../../uri_reader'
  UriReader.read_first(DOC_URLS[document], what: "document #{document}") do |text|
    Aspera.assert(!HTML_PAGE.match?(text), type: Cli::Error) { 'HTML page instead of Markdown' }
    text
  end
end

#development_section(document, anchor) ⇒ Object

Parameters:

  • anchor (String) —

    Anchor of the section, see toc



573
574
575
576
577
578
# File 'lib/aspera/plugins/orchestrator/commands.rb', line 573

def development_section(document, anchor)
  require_relative '../../markdown'
  text = Markdown.extract_section(development_document(document), anchor)
  Aspera.assert(!text.nil?, type: Cli::Error) { "Section not found: #{anchor}, use `toc` to list anchors" }
  Cli::Result::Text.new(text)
end

#development_toc(document, level) ⇒ Object

Parameters:

  • level (Integer, nil) —

    Maximum level of headings of the table of contents (default per document)



567
568
569
570
# File 'lib/aspera/plugins/orchestrator/commands.rb', line 567

def development_toc(document, level)
  require_relative '../../markdown'
  Cli::Result::ObjectList.new(Markdown.toc(development_document(document), max_level: level || DOC_TOC_LEVELS[document]), fields: %w[level title anchor])
end

#plugin_spec_show(plugin, section) ⇒ Object

Parameters:

  • plugin (String) —

    Class name of the plugin (case insensitive)

  • section (Symbol, nil) —

    One of SPEC_SECTIONS, or nil for the whole specification



597
598
599
600
601
602
603
604
605
606
# File 'lib/aspera/plugins/orchestrator/commands.rb', line 597

def plugin_spec_show(plugin, section)
  specs = plugin_specs
  name = specs.keys.find { |key| key.casecmp?(plugin) }
  if name.nil?
    similar = specs.keys.select { |key| key.downcase.include?(plugin.downcase) }
    raise Cli::BadArgument, "Unknown plugin: #{plugin}#{", similar: #{similar.join(', ')}" unless similar.empty?}, use `plugins spec toc` to list plugins"
  end
  return Cli::Result::SingleObject.new({'name' => name}.merge(specs[name])) if section.nil?
  Cli::Result::ObjectList.new(specs[name][section.to_s].map { |key, value| {'name' => key}.merge(value) })
end

#plugin_spec_toc ⇒ Object



591
592
593
# File 'lib/aspera/plugins/orchestrator/commands.rb', line 591

def plugin_spec_toc
  Cli::Result::ObjectList.new(plugin_specs.map { |name, spec| {'name' => name}.merge(spec.except(*SPEC_SECTIONS.map(&:to_s), 'notes')) }, fields: SPEC_LIST_FIELDS)
end

#plugin_specs ⇒ Hash

Specifications of action plugins, read from GitHub, or from option plugin_specs: does not require access to Orchestrator

Returns:

  • (Hash) —

    Class name of plugin => attributes, inputs, outputs



582
583
584
585
586
587
588
589
# File 'lib/aspera/plugins/orchestrator/commands.rb', line 582

def plugin_specs
  return @plugin_specs if @plugin_specs
  require_relative '../../uri_reader'
  require_relative '../../yaml'
  specs = Yaml.safe_load(UriReader.read(options.get_option(:plugin_specs, mandatory: true)))
  Aspera.assert_type(specs, Hash, type: Cli::Error) { 'plugin specifications' }
  @plugin_specs = specs
end

#processes_result(status) ⇒ Object

Processes of all nodes

Parameters:

  • status (Hash) —

    Response of processes_status or control_process (XML)



514
515
516
# File 'lib/aspera/plugins/orchestrator/commands.rb', line 514

def processes_result(status)
  Cli::Result::ObjectList.new(status['node'].flat_map { |node| node['process'] })
end

#server_constraints(filename, add_as_revision = nil) ⇒ Hash{String=>Object}

Conflicts and missing plugins found by Orchestrator, as one row per name to resolve. Orchestrator does not check that the file exists: for a wrong path, it returns the same empty result as for a file without conflict.

Returns:

  • (Hash{String=>Object}) —

    Items returned by Orchestrator, by name (subwf constraints, missing plugins...)



670
671
672
673
674
# File 'lib/aspera/plugins/orchestrator/commands.rb', line 670

def server_constraints(filename, add_as_revision = nil)
  list = call_ao('find_constraints', query: {file: filename, wf_id: add_as_revision}.compact)
  Aspera.assert_type(list, Array, type: Cli::Error) { 'response of find_constraints' }
  list.grep(Hash).reduce({}, :merge)
end

#statistics_result(stats) ⇒ Object

Statistics are a list, or a message in text/plain when there is none

Parameters:



454
455
456
# File 'lib/aspera/plugins/orchestrator/commands.rb', line 454

def statistics_result(stats)
  stats.is_a?(String) ? Cli::Result::Status.new(stats) : Cli::Result::ObjectList.new(stats)
end

#wizard(wizard, app_url) ⇒ Hash

Returns :preset_value, :test_args.

Parameters:

  • wizard (Wizard) —

    The wizard object

  • app_url (String) —

    Tested URL

Returns:

  • (Hash) —

    :preset_value, :test_args



106
107
108
109
110
111
112
113
114
115
116
117
# File 'lib/aspera/plugins/orchestrator/commands.rb', line 106

def wizard(wizard, app_url)
  username = options.get_option(:username, mandatory: true)
  return {
    preset_ids:   [username],
    preset_value: {
      url:      app_url,
      username: username,
      password: options.get_option(:password, mandatory: true)
    },
    test_args:    'workflows list'
  }
end