Class: Morpheus::Cli::CurlCommand

Inherits:
Object
  • Object
show all
Includes:
CliCommand
Defined in:
lib/morpheus/cli/commands/standard/curl_command.rb

Instance Attribute Summary

Attributes included from CliCommand

#no_prompt

Instance Method Summary collapse

Methods included from CliCommand

#apply_options, #build_common_options, #build_option_type_options, #build_standard_add_options, #build_standard_delete_options, #build_standard_get_options, #build_standard_list_options, #build_standard_post_options, #build_standard_put_options, #build_standard_remove_options, #build_standard_update_options, #command_description, #command_name, #default_refresh_interval, #default_sigdig, #default_subcommand, #establish_remote_appliance_connection, #full_command_usage, #get_subcommand_description, #handle_subcommand, included, #interactive?, #my_help_command, #my_terminal, #my_terminal=, #parse_bytes_param, #parse_id_list, #parse_list_options, #parse_list_subtitles, #parse_passed_options, #parse_payload, #parse_query_options, #print, #print_error, #println, #prog_name, #puts, #puts_error, #raise_args_error, #raise_command_error, #render_response, #run_command_for_each_arg, #subcommand_aliases, #subcommand_description, #subcommand_usage, #subcommands, #usage, #validate_outfile, #verify_args!, #visible_subcommands

Instance Method Details

#command_available?(cmd) ⇒ Boolean

Returns:

  • (Boolean)


162
163
164
165
166
167
168
169
170
171
# File 'lib/morpheus/cli/commands/standard/curl_command.rb', line 162

def command_available?(cmd)
  has_it = false
  begin
    system("which #{cmd} > /dev/null 2>&1")
    has_it = $?.success?
  rescue => e
    raise e
  end
  return has_it
end

#handle(args) ⇒ Object



11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
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
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
# File 'lib/morpheus/cli/commands/standard/curl_command.rb', line 11

def handle(args)
  # support syntax for arbitrary curl args after " -- " 
  # eg. curl /api/instances -- -ksv
  split_index = args.index("--")
  curl_args = []
  if split_index
    if args.length > (split_index + 1)
      curl_args = args[(split_index + 1)..-1]
    end
    args = args[0..(split_index - 1)]
  end
  curl_method = nil
  curl_data = nil
  curl_verbsose = false
  show_progress = false
  options = {}
  optparse = Morpheus::Cli::OptionParser.new do|opts|
    opts.banner = "Usage: morpheus curl [path] -- [*args]"
    opts.on( '-p', '--pretty', "Print result as parsed JSON." ) do
      options[:pretty] = true
    end
    opts.on( '-X', '--request METHOD', "HTTP request method. Default is GET" ) do |val|
      curl_method = val
    end
    opts.on( '-v', '--verbose', "Print verbose output." ) do
      curl_verbsose = true
    end
    opts.on( '--data DATA', String, "HTTP request body for use with POST and PUT, typically JSON." ) do |val|
      curl_data = val
    end
    opts.on( '--progress', '--progress', "Display progress output by excluding the -s option." ) do
      show_progress = true
    end
    build_common_options(opts, options, [:dry_run, :json, :remote])
    opts.add_hidden_option('--curl')
    #opts.add_hidden_option('--scrub')
    opts.footer = <<-EOT
This invokes the `curl` command with url "appliance_url/$0
and includes the authorization header -H "Authorization: Bearer access_token"
Arguments for the curl command should be passed after ' -- '
Example: morpheus curl "/api/servers/1" -- -XGET -sv

EOT
  end
  optparse.parse!(args)
  if args.count < 1
    puts optparse
    return false
  end
  
  if !command_available?("curl")
    print "#{red}The 'curl' command is not available on your system.#{reset}\n"
    return false
  end
  
  @api_client = establish_remote_appliance_connection(options.merge({:no_prompt => true, :skip_verify_access_token => true, :skip_login => true}))

  if !@appliance_name
    raise_command_error "#{command_name} requires a remote to be specified, use -r [remote] or set the active remote with `remote use`"
  end

  # curry --insecure to curl
  if options[:insecure] || !Morpheus::RestClient.ssl_verification_enabled?
    #curl_args.unshift "-k"
    curl_args.unshift "--insecure"
  end

  if !@appliance_url
    raise "Unable to determine remote appliance url"
    print "#{red}Unable to determine remote appliance url.#{reset}\n"
    return false
  end

  # determine curl url
  url = nil
  api_path = args[0].to_s.strip
  # allow absolute path for the current appliance url only
  if api_path.match(/^#{Regexp.escape(@appliance_url)}/)
    url = api_path
  else
    api_path = api_path.sub(/^\//, "") # strip leading slash
    url = "#{@appliance_url.chomp('/')}/#{api_path}"
  end
  curl_cmd = "curl"
  if show_progress == false
    curl_cmd << " -s"
  end
  if curl_verbsose
    curl_cmd << " -v"
  end
  if curl_method
    curl_cmd << " -X#{curl_method}"
  end
  curl_cmd << " \"#{url}\""
  if @access_token
    if !(options[:headers] && options[:headers]['Authorization'])
      curl_cmd << " -H \"Authorization: Bearer #{@access_token}\""
    end
  end
  if curl_data
    #todo: curl_data.gsub("'","\\'")
    curl_cmd << " --data '#{curl_data}'"
    if api_path !~ /^\/?oauth/
      if !(options[:headers] && options[:headers]['Content-Type'])
        curl_cmd << " -H \"Content-Type: application/json\""
      end
    end
  end
  if options[:headers]
    options[:headers].each do |k,v|
      curl_cmd << " -H \"#{k}: #{v}\""
    end
  end
  if !curl_args.empty?
    curl_cmd << " " + curl_args.join(' ')
  end
  # Morpheus::Logging::DarkPrinter.puts "#{curl_cmd}" if Morpheus::Logging.debug?
  curl_cmd_str = options[:scrub] ? Morpheus::Logging.scrub_message(curl_cmd) : curl_cmd

  if options[:dry_run]
    print cyan
    print "#{cyan}#{curl_cmd_str}#{reset}"
    print "\n\n"
    print reset
    return 0
  end
  # print cyan
  # print "#{cyan}#{curl_cmd_str}#{reset}"
  # print "\n\n"
  print reset
  # print result
  curl_output = `#{curl_cmd}`
  if options[:pretty] || options[:json]
    output_lines = curl_output.split("\n")
    last_line = output_lines.pop
    if output_lines.size > 0
      puts output_lines.join("\n")
    end
    begin
      puts as_json(JSON.parse(last_line), options)
    rescue => ex
      Morpheus::Logging::DarkPrinter.puts "failed to parse curl result as JSON data Error: #{ex.message}" if Morpheus::Logging.debug?
      puts last_line
    end
  else
    puts curl_output
  end
  return $?.success?

end