class Morpheus::Cli::Tasks

Public Instance Methods

_get(id, options) click to toggle source
# File lib/morpheus/cli/commands/tasks.rb, line 97
def _get(id, options)
  task_name = id
  begin
    @tasks_interface.setopts(options)
    if options[:dry_run]
      if task_name.to_s =~ /\A\d{1,}\Z/
        print_dry_run @tasks_interface.dry.get(task_name.to_i)
      else
        print_dry_run @tasks_interface.dry.get({name: task_name})
      end
      return
    end
    task = find_task_by_name_or_id(task_name)
    exit 1 if task.nil?
    # refetch it
    json_response = {'task' => task}
    unless task_name.to_s =~ /\A\d{1,}\Z/
      json_response = @tasks_interface.get(task['id'])
    end
    if options[:json]
      puts as_json(json_response, options, "task")
      return 0
    elsif options[:yaml]
      puts as_yaml(json_response, options, "task")
      return 0
    elsif options[:csv]
      puts records_as_csv([json_response['task']], options)
      return 0
    else
      # load task type to know which options to display
      task_type = task['taskType'] ? find_task_type_by_name(task['taskType']['name']) : nil
      #print "\n", cyan, "Task #{task['name']} - #{task['taskType']['name']}\n\n"
      print_h1 "Task Details"
      print cyan
      description_cols = {
        "ID" => 'id',
        "Name" => 'name',
        "Code" => 'code',
        "Type" => lambda {|it| it['taskType']['name'] },
        "Labels" => lambda {|it| format_list(it['labels'], '', 3) rescue '' },
        "Visibility" => 'visibility',
        "Execute Target" => lambda {|it| 
          if it['executeTarget'] == 'local'
            git_info = []
            if it['taskOptions']
              if it['taskOptions']['localScriptGitId']
                git_info << "Git Repo: #{it['taskOptions']['localScriptGitId']}"
              end
              if it['taskOptions']['localScriptGitRef']
                git_info << "Git Ref: #{it['taskOptions']['localScriptGitRef']}"
              end
            end
            "Local #{git_info.join(', ')}"
          elsif it['executeTarget'] == 'remote'
            remote_url = ""
            if it['taskOptions']
              remote_url = "#{it['taskOptions']['username']}@#{it['taskOptions']['host']}:#{it['taskOptions']['port']}"
            end
            "Remote #{remote_url}"
          elsif it['executeTarget'] == 'resource'
            "Resource"
          else
            it['executeTarget']
          end
        },
        "Result Type" => 'resultType',
        "Retryable" => lambda {|it| 
          if it['retryable']
            format_boolean(it['retryable']).to_s + " Count: #{it['retryCount']}, Delay: #{it['retryDelaySeconds']}" 
          else
            format_boolean(it['retryable'])
          end
        },
        "Allow Custom Config" => lambda {|it| format_boolean(it['allowCustomConfig']) },
        "Created" => lambda {|it| format_local_dt(it['dateCreated']) },
        "Updated" => lambda {|it| format_local_dt(it['lastUpdated']) }
      }
      print_description_list(description_cols, task)
      
      # JD: uhh, the api should NOT be returning passwords!!
      if task_type
        # task_type['optionTypes'].sort { |x,y| x['displayOrder'].to_i <=> y['displayOrder'].to_i }.each do |optionType|
        #   if optionType['fieldLabel'].to_s.downcase == 'script'
        #     if task['taskOptions'][optionType['fieldName']]
        #       print_h2 "Script"
        #       print reset,"#{task['taskOptions'][optionType['fieldName']]}","\n",reset
        #     end
        #   else
        #     print cyan,("#{optionType['fieldLabel']} : " + (optionType['type'] == 'password' ? "#{task['taskOptions'][optionType['fieldName']] ? '************' : ''}" : "#{task['taskOptions'][optionType['fieldName']] || optionType['defaultValue']}")),"\n"
        #   end
        # end
        script_content = nil
        task_option_types = []
        task_option_config = {}
        task_option_columns = []
        task_type['optionTypes'].sort { |x,y| x['displayOrder'].to_i <=> y['displayOrder'].to_i }.each do |optionType|
          if optionType['code'] == 'script'
            script_content = task['taskOptions'][optionType['fieldName']]
          elsif optionType['fieldName'] == 'httpHeaders' || optionType['fieldName'] == 'webHeaders'
            http_headers = task['taskOptions']['httpHeaders'] || task['taskOptions']['webHeaders']
            begin
              if http_headers.is_a?(String)
                http_headers = JSON.parse(http_headers)
              end
              # API has mismatch on fieldName httpHeaders vs webHeaders, we want to format this in a particular way though anyhow..
              task_option_columns << {(optionType['fieldLabel']) => lambda {|it| http_headers.collect {|h| "#{h['key']}: #{h['value']}"}.join(", ") } }
            rescue => ex
              Morpheus::Logging::DarkPrinter.puts("Failed to parse httpHeaders task option as JSON") if Morpheus::Logging.debug?
            end
          else
            task_option_types << optionType
            task_option_columns << {(optionType['fieldLabel']) => lambda {|it| 
              value = task['taskOptions'][optionType['code']] || task['taskOptions'][optionType['fieldName']] || optionType['defaultValue']
              if optionType['type'] == 'checkbox'
                value.to_s.empty? ? 'off' : value.to_s
              else
                value.to_s
              end
            } }
          end
        end
      else
        print yellow,"Task type not found.",reset,"\n"
      end
      if !task_option_columns.empty?
        print_h2 "Task Options"
        print_description_list(task_option_columns, task["taskOptions"])
      end
      if script_content
        print_h2 "Script"
        print reset,script_content,"\n",reset
      end
      # some task types have a file (file-content) instead of taskOptions.script
      file_content = task['file']
      if file_content && options[:no_content] != true
        print_h2 "Script Content"
        if file_content['sourceType'] == 'local'
          puts file_content['content']
        elsif file_content['sourceType'] == 'url'
          puts "URL: #{file_content['contentPath']}"
        elsif file_content['sourceType'] == 'repository'
          puts "Repository: #{file_content['repository']['name'] rescue 'n/a'}"
          puts "Path: #{file_content['contentPath']}"
          if file_content['contentRef']
            puts "Ref: #{file_content['contentRef']}"
          end
        else
          puts "Source: #{file_content['sourceType']}"
          puts "Path: #{file_content['contentPath']}"
        end
      end

      print reset,"\n"
      return 0
    end
  rescue RestClient::Exception => e
    print_rest_exception(e, options)
    exit 1
  end
connect(opts) click to toggle source
# File lib/morpheus/cli/commands/tasks.rb, line 11
def connect(opts)
  @api_client = establish_remote_appliance_connection(opts)
  @tasks_interface = @api_client.tasks
  @task_sets_interface = @api_client.task_sets
  @instances_interface = @api_client.instances
  @servers_interface = @api_client.servers
end
get(args) click to toggle source
# File lib/morpheus/cli/commands/tasks.rb, line 77
def get(args)
  options = {}
  optparse = Morpheus::Cli::OptionParser.new do |opts|
    opts.banner = subcommand_usage("[workflow]")
    opts.on('--no-content', "Do not display script content." ) do
      options[:no_content] = true
    end
    build_common_options(opts, options, [:json, :yaml, :csv, :fields, :dry_run, :remote])
  end
  optparse.parse!(args)
  if args.count < 1
    raise_command_error "wrong number of arguments, expected 1-N and got (#{args.count}) #{args.join(' ')}\n#{optparse}"
  end
  connect(options)
  id_list = parse_id_list(args)
  return run_command_for_each_arg(id_list) do |arg|
    _get(arg, options)
  end
end
handle(args) click to toggle source
# File lib/morpheus/cli/commands/tasks.rb, line 19
def handle(args)
  handle_subcommand(args)
end
list(args) click to toggle source
# File lib/morpheus/cli/commands/tasks.rb, line 23
def list(args)
  params = {}
  options = {}
  optparse = Morpheus::Cli::OptionParser.new do |opts|
    opts.banner = subcommand_usage("[search]")
    opts.on('-t', '--type x,y,z', Array, "Filter by task type code(s)") do |val|
      params['taskTypeCodes'] = val
    end

    opts.on('-l', '--labels LABEL', String, "Filter by labels, can match any of the values") do |val|
      add_query_parameter(params, 'labels', parse_labels(val))
    end
    opts.on('--all-labels LABEL', String, "Filter by labels, must match all of the values") do |val|
      add_query_parameter(params, 'allLabels', parse_labels(val))
    end

    build_standard_list_options(opts, options)
    opts.footer = "List tasks."
  end
  optparse.parse!(args)
  connect(options)
  if args.count > 0
    options[:phrase] = args.join(" ")
  end
  params.merge!(parse_list_options(options))
  @tasks_interface.setopts(options)
  if options[:dry_run]
    print_dry_run @tasks_interface.dry.list(params)
    return
  end
  json_response = @tasks_interface.list(params)
  tasks = json_response['tasks']
  render_response(json_response, options, 'tasks') do
    title = "Morpheus Tasks"
    subtitles = []
    subtitles += parse_list_subtitles(options)
    print_h1 title, subtitles
    if tasks.empty?
      print cyan,"No tasks found.",reset,"\n"
    else
      print cyan
      print_tasks_table(tasks, options)
      print_results_pagination(json_response)
    end
    print reset,"\n"
  end
  if tasks.empty?
    return 1, "no tasks found"
  else
    return 0, nil
  end
  
end