Class: CloudStackClient::CLI

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

Overview

The commandline client ‘cloud-stack.rb’

Plesae run cloud-stack.rb –help for additional info.

Constant Summary collapse

DEFAULT_OPTIONS =

Default options for the command line. Can be overridden by parameters and a config file

{
  :api_uri => nil,
  :api_key => nil,
  :secret_key => nil,
  :username => nil,
  :password => nil,
  :domain => nil,
  :response => "json",
  :output => nil,
  :debug => false,
  :auto_paging => true,
  :page_size => 500
}.freeze

Instance Method Summary collapse

Constructor Details

#initializeCLI

Create new commandline instance



25
26
27
28
# File 'lib/cloud_stack_client/cli.rb', line 25

def initialize
  @options = DEFAULT_OPTIONS.dup
  @parameters = {}
end

Instance Method Details

#run(command, arguments) ⇒ Boolean

Execute the command

Parameters:

  • command (String)

    The name of the executable ($0)

  • arguments (Array)

    Commandline parameters (ARGV)

Returns:

  • (Boolean)

    true if successful



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
161
162
163
164
165
166
167
168
# File 'lib/cloud_stack_client/cli.rb', line 35

def run(command, arguments)
  # Parse commandline
  pos = arguments.find_index("--config")
  if pos
    arguments.delete_at pos
    raise "Path to config file missing" unless arguments[pos]
    filename = arguments.delete_at pos
    yaml = YAML.load_file filename
    yaml["default"].each {|key, value| @options[key.to_sym] = value}
  end
  if arguments.empty?
    print_help File.basename(command), DEFAULT_OPTIONS
    return false
  end
  while arguments.any? do
    arg = arguments.shift
    raise "Unknown parameter #{arg}" unless arg.start_with? '--'
    key = arg.slice(2, arg.length - 2)
    case key
    when 'debug', 'ignore-ssl', 'auto-paging', 'no-auto-paging'
      # Single parameter options
      if key.start_with? 'no-'
        key = key.slice(3, arg.length - 3)
        @options[key.gsub('-', '_').to_sym] = false
      else
        @options[key.gsub('-', '_').to_sym] = true
      end
    when 'api-key', 'secret-key', 'username', 'password', 'domain', 'api-uri', 'response', 'output', 'pagesize', 'config'
      # Second parameter options
      raise "Missing value for #{arg}" if arguments.empty?
      value = arguments.shift
      if key == 'pagesize'
        value = value.to_i
      end
      @options[key.gsub('-', '_').to_sym] = value
    when 'help'
      print_help File.basename(command), DEFAULT_OPTIONS
      return false
    when 'config-stub'
      print_config DEFAULT_OPTIONS
      return false
    else
      raise "Missing value for #{arg}" if arguments.empty?
      @parameters[key] = arguments.shift
    end
  end
  
  # Check existence of base URL
  unless @options[:api_uri] && !@options[:api_uri].empty?
    raise "Server API URL is missing. Specify with --api-uri parameter."
  end
  
  # Check existence of a command
  unless @parameters['command']
    warn "No command specified. Use --command COMMAND to specify a remote command."
  end
  
  # Check that auto paging is only used on list* commands
  unless @parameters['command'] && @parameters['command'].downcase.start_with?("list")
    @options[:auto_paging] = false
    warn "Auto Paging disabled because command does not start with 'list'." if @options[:debug]
  end
  
  # Set response format if specified
  if @options[:response]
    warn "Unknown response format #{@options[:response]}." unless ['xml', 'json'].include? @options[:response]
    @parameters['response'] = @options[:response]
  end
  
  # Login to CloudStack API
  api = CloudStackClient::Connector.new({:api_uri => @options[:api_uri], :page_size => @options[:page_size], :ssl_check => !@options[:ignore_ssl]})
  if @options[:api_key] && @options[:secret_key]
    unless api. @options[:api_key], @options[:secret_key]
      raise "Login using API key and secret key (--api-key KEY --secret-key SECRET) failed."
    end
  elsif @options[:username] && @options[:password]
    unless api. @options[:username], @options[:password], @options[:domain] 
      raise "Login using username and password failed."
    end
  else
    warn "No credentials specified." if @options[:debug]
  end
  
  # Execute query
  warn "Parameters:\n#{@parameters.inspect}\n" if @options[:debug]
  if @options[:auto_paging]
    output = api.query_all_pages @parameters
  else
    output = api.query @parameters
  end
  
  # Verify result
  errorcode = nil
  message = "Unrecognizable Result"
  unless CloudStackClient::API::response_is_success? output
    case CloudStackClient::API::response_format(output)
    when :xml
      errorcode = REXML::XPath.first(output.root, "//errorcode").text.to_i
      message = REXML::XPath.first(output.root, "//errortext").text
    when :json
      errorcode = output.first[1]["errorcode"]
      message = output.first[1]["errortext"]
    else
      message = "Unknown format #{CloudStackClient::API::response_format(output)}"
    end
    warn "Error #{errorcode} occured: #{message}\n"
  end
  
  # Output result
  if not @options[:output]
    # If no output is specified show formatted result on STDOUT
    case CloudStackClient::API::response_format(output)
    when :xml
      puts "XML Response:"
      puts output
    when :json
      puts "JSON Response:"
      puts output.to_yaml
    else
      warn "Unknown format #{CloudStackClient::API::response_format(output)}" if @options[:debug]
    end
  elsif @options[:output] == '-'
    # Pipe to STDOUT
    STDOUT << output
    puts # Fix missing newline
  else
    # Write to file
    file = File.new(@options[:output], 'w')
    file << output
    file.close
  end
  
  !!errorcode
end