Class: Morpheus::Cli::BudgetsCommand
- Inherits:
-
Object
- Object
- Morpheus::Cli::BudgetsCommand
- Includes:
- CliCommand
- Defined in:
- lib/morpheus/cli/commands/budgets_command.rb
Instance Attribute Summary
Attributes included from CliCommand
Instance Method Summary collapse
- #add(args) ⇒ Object
- #connect(opts) ⇒ Object
- #get(args) ⇒ Object
- #handle(args) ⇒ Object
- #list(args) ⇒ Object
- #remove(args) ⇒ Object
- #update(args) ⇒ Object
Methods included from CliCommand
#add_query_parameter, #apply_options, #build_common_options, #build_get_options, #build_list_options, #build_option_type_options, #build_standard_add_many_options, #build_standard_add_options, #build_standard_api_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, #confirm, #confirm!, #default_refresh_interval, #default_sigdig, #default_subcommand, #establish_remote_appliance_connection, #execute_api, #execute_api_payload, #execute_api_request, #find_all, #find_all_json, #find_by_id, #find_by_name, #find_by_name_or_id, #find_record, #find_record_json, #full_command_usage, #get_interface, #get_list_key, #get_object_key, #get_subcommand_description, #handle_each_payload, #handle_subcommand, included, #interactive?, #my_help_command, #my_terminal, #my_terminal=, #parse_array, #parse_bytes_param, #parse_get_options!, #parse_id_list, #parse_labels, #parse_list_options, #parse_list_options!, #parse_list_subtitles, #parse_options, #parse_parameter_as_resource_id!, #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
#add(args) ⇒ Object
222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 |
# File 'lib/morpheus/cli/commands/budgets_command.rb', line 222 def add(args) = {} params = {} costs = [] optparse = Morpheus::Cli::OptionParser.new do |opts| opts. = subcommand_usage("[name] [options]") (opts, , add_budget_option_types) # opts.on('--cost [amount]', String, "Budget cost amount, for use with default year interval.") do |val| # costs['year'] = (val.nil? || val.empty?) ? 0 : val.to_f # end opts.on('--costs LIST', String, "Budget cost amounts, one for each interval in the budget. eg \"350\" for one year, \"25,25,25,100\" for quarters, and \"10,10,10,10,10,10,10,10,10,10,10,50\" for each month") do |val| val = val.to_s.gsub('[', '').gsub(']', '') costs = val.to_s.split(',').collect {|it| parse_cost_amount(it) } end (1..12).each.with_index do |cost_index, i| opts.on("--cost#{cost_index} VALUE", String, "Cost #{cost_index.to_s.capitalize} amount") do |val| #params["cost#{cost_index.to_s}"] = parse_cost_amount(val) costs[i] = parse_cost_amount(val) end opts.add_hidden_option("--cost#{cost_index}") end [:q1,:q2,:q3,:q4,].each.with_index do |quarter, i| opts.on("--#{quarter.to_s} VALUE", String, "#{quarter.to_s.capitalize} cost amount, use with quarter interval.") do |val| costs[i] = parse_cost_amount(val) end opts.add_hidden_option("--#{quarter.to_s}") end [:january,:february,:march,:april,:may,:june,:july,:august,:september,:october,:november,:december].each_with_index do |month, i| opts.on("--#{month.to_s} VALUE", String, "#{month.to_s.capitalize} cost amount, use with month interval.") do |val| costs[i] = parse_cost_amount(val) end opts.add_hidden_option("--#{month.to_s}") end opts.on('--enabled [on|off]', String, "Can be used to disable a policy") do |val| params['enabled'] = val.to_s == 'on' || val.to_s == 'true' || val.to_s.empty? end (opts, ) opts. = <<-EOT Create a budget. The default period is the current year, eg. "#{Time.now.year}" and the default interval is "year". Costs can be passed as an array of values, one for each interval. eg. --costs "[999]" Examples: budgets add example-budget --interval "year" --costs "[2500]" budgets add example-qtr-budget --interval "quarter" --costs "[500,500,500,1000]" budgets add example-monthly-budget --interval "month" --costs "[400,100,100,100,100,100,100,100,100,100,400,800]" budgets add example-future-budget --year "2022" --interval "year" --costs "[5000]" budgets add example-custom-budget --year "custom" --interval "year" --start "2021-01-01" --end "2023-12-31" --costs "[2500,5000,10000]" EOT end optparse.parse!(args) if args.count > 1 raise_command_error "wrong number of arguments, expected 0-1 and got (#{args.count}) #{args}\n#{optparse}" end if args[0] [:options]['name'] ||= args[0] end connect() begin # construct payload = [:options] ? [:options].reject {|k,v| k.is_a?(Symbol) } : {} payload = nil if [:payload] payload = [:payload] payload.deep_merge!({'budget' => }) unless .empty? else payload = { 'budget' => { } } # allow arbitrary -O options #passed_options.delete('costs') .delete('tenant') .delete('group') .delete('cloud') .delete('user') payload.deep_merge!({'budget' => }) unless .empty? # prompt for options v_prompt = Morpheus::Cli::OptionTypes.prompt(add_budget_option_types, [:options], @api_client) params.deep_merge!(v_prompt) # downcase year 'custom' always if params['year'] params['interval'] = params['interval'].to_s.downcase end # downcase interval always if params['interval'] params['interval'] = params['interval'].to_s.downcase end # parse MM/DD/YY but need to convert to to ISO format YYYY-MM-DD for api standard_start_date = (params['startDate'] ? Time.strptime(params['startDate'], "%x") : nil) rescue nil if standard_start_date params['startDate'] = format_date(standard_start_date, {format:"%Y-%m-%d"}) end standard_end_date = (params['endDate'] ? Time.strptime(params['endDate'], "%x") : nil) rescue nil if standard_end_date params['endDate'] = format_date(standard_end_date, {format:"%Y-%m-%d"}) end if !costs.empty? params['costs'] = costs else params['costs'] = prompt_costs(params, ) end # budgets api expects scope prefixed parameters like this if params['tenant'].is_a?(String) || params['tenant'].is_a?(Numeric) params['scopeTenantId'] = params.delete('tenant') end if params['group'].is_a?(String) || params['group'].is_a?(Numeric) params['scopeGroupId'] = params.delete('group') end if params['cloud'].is_a?(String) || params['cloud'].is_a?(Numeric) params['scopeCloudId'] = params.delete('cloud') end if params['user'].is_a?(String) || params['user'].is_a?(Numeric) params['scopeUserId'] = params.delete('user') end payload.deep_merge!({'budget' => params}) unless params.empty? end @budgets_interface.setopts() if [:dry_run] print_dry_run @budgets_interface.dry.create(payload) return end json_response = @budgets_interface.create(payload) if [:json] print JSON.pretty_generate(json_response) print "\n" else display_name = json_response['budget'] ? json_response['budget']['name'] : '' print_green_success "Budget #{display_name} added" get([json_response['budget']['id']] + ([:remote] ? ["-r",[:remote]] : [])) end return 0 rescue RestClient::Exception => e print_rest_exception(e, ) exit 1 end end |
#connect(opts) ⇒ Object
10 11 12 13 14 |
# File 'lib/morpheus/cli/commands/budgets_command.rb', line 10 def connect(opts) @api_client = establish_remote_appliance_connection(opts) @budgets_interface = @api_client.budgets @options_interface = @api_client. end |
#get(args) ⇒ Object
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 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 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 |
# File 'lib/morpheus/cli/commands/budgets_command.rb', line 93 def get(args) = {} params = {} optparse = Morpheus::Cli::OptionParser.new do |opts| opts. = subcommand_usage("[budget]") (opts, ) opts. = "Get details about a budget.\n[budget] is required. Budget ID or name" end optparse.parse!(args) verify_args!(args:args, optparse:optparse, count:1) connect() params.merge!(()) @budgets_interface.setopts() if [:dry_run] if args[0].to_s =~ /\A\d{1,}\Z/ print_dry_run @budgets_interface.dry.get(args[0], params) else print_dry_run @budgets_interface.dry.list({name: args[0].to_s}) end return 0 end budget = find_budget_by_name_or_id(args[0]) return 1 if budget.nil? # skip reload if already fetched via get(id) json_response = {'budget' => budget} if args[0].to_s != budget['id'].to_s json_response = @budgets_interface.get(budget['id'], params) budget = json_response['budget'] end render_response(json_response, , 'budget') do print_h1 "Budget Details" print cyan budget_columns = { "ID" => 'id', "Name" => 'name', "Description" => 'description', "Enabled" => lambda {|budget| format_boolean(budget['enabled']) }, "Scope" => lambda {|it| format_budget_scope(it) }, "Period" => lambda {|it| it['year'] }, "Interval" => lambda {|it| it['interval'].to_s.capitalize }, "Forecast Model" => lambda {|it| it['forecastType'] ? it['forecastType']['name'] : '' }, # the UI doesn't consider timezone, so uhh do it this hacky way for now. "Start Date" => lambda {|it| if it['timezone'] == 'UTC' ((parse_time(it['startDate'], "%Y-%m-%d").strftime("%x")) rescue it['startDate']) # + ' UTC' else format_local_date(it['startDate']) end }, "End Date" => lambda {|it| if it['timezone'] == 'UTC' ((parse_time(it['endDate'], "%Y-%m-%d").strftime("%x")) rescue it['endDate']) # + ' UTC' else format_local_date(it['endDate']) end }, # "Costs" => lambda {|it| # if it['costs'].is_a?(Array) # it['costs'] ? it['costs'].join(', ') : '' # elsif it['costs'].is_a?(Hash) # it['costs'].to_s # else # it['costs'].to_s # end # }, "Created By" => lambda {|it| it['createdByName'] ? it['createdByName'] : it['createdById'] }, "Created" => lambda {|it| format_local_dt(it['dateCreated']) }, "Updated" => lambda {|it| format_local_dt(it['lastUpdated']) }, } print_description_list(budget_columns, budget, ) # print reset,"\n" # a chart of Budget cost vs Actual cost for each interval in the period. print_h2 "Budget Summary", if budget['stats'] && budget['stats']['intervals'] begin budget_summary_columns = { # "Cost" => lambda {|it| it[:label] }, " " => lambda {|it| it[:label] }, } budget_row = {label:"Budget"} actual_row = {label:"Actual"} forecast_row = {label:"Forecast"} multi_year = false if budget['startDate'] && budget['endDate'] && parse_time(budget['startDate']).year != parse_time(budget['endDate']).year multi_year = true end budget['stats']['intervals'].each do |it| currency = budget['currency'] || budget['stats']['currency'] interval_key = format_budget_interval_label(budget, it).to_s.upcase # interval_date = parse_time(it["startDate"]) rescue nil budget_summary_columns[interval_key] = interval_key budget_cost = it["budget"].to_f actual_cost = it["cost"].to_f over_budget = actual_cost > 0 && actual_cost > budget_cost if over_budget budget_row[interval_key] = "#{cyan}#{format_money(budget_cost, currency)}#{cyan}" actual_row[interval_key] = "#{red}#{format_money(actual_cost, currency)}#{cyan}" else budget_row[interval_key] = "#{cyan}#{format_money(budget_cost, currency)}#{cyan}" actual_row[interval_key] = "#{cyan}#{format_money(actual_cost, currency)}#{cyan}" end forecast_cost = it["forecast"] ? it["forecast"].to_f : 0 forecast_over_budget = forecast_cost > 0 && forecast_cost > budget_cost if forecast_over_budget forecast_row[interval_key] = "#{red}#{format_money(forecast_cost, currency)}#{cyan}" else forecast_row[interval_key] = "#{cyan}#{format_money(forecast_cost, currency)}#{cyan}" end end chart_data = [budget_row, actual_row] if budget['stats']['intervals'].find { |it| it['forecast'] && it['forecast'] != 0 } chart_data << forecast_row end print as_pretty_table(chart_data, budget_summary_columns, ) print reset,"\n" rescue => ex print red,"Failed to render budget summary.",reset,"\n" raise ex end else print cyan,"No budget stat data found.",reset,"\n" end end return 0, nil end |
#handle(args) ⇒ Object
16 17 18 |
# File 'lib/morpheus/cli/commands/budgets_command.rb', line 16 def handle(args) handle_subcommand(args) end |
#list(args) ⇒ Object
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 |
# File 'lib/morpheus/cli/commands/budgets_command.rb', line 20 def list(args) = {} params = {} optparse = Morpheus::Cli::OptionParser.new do |opts| opts. = subcommand_usage() (opts, ) opts. = "List budgets." end optparse.parse!(args) # verify_args!(args:args, optparse:optparse, count:0) if args.count > 0 [:phrase] = args.join(" ") end params.merge!(()) connect() params.merge!(()) @budgets_interface.setopts() if [:dry_run] print_dry_run @budgets_interface.dry.list(params) return 0 end json_response = @budgets_interface.list(params) budgets = json_response['budgets'] render_response(json_response, , 'budgets') do title = "Morpheus Budgets" subtitles = [] subtitles += parse_list_subtitles() print_h1 title, subtitles if budgets.empty? print cyan,"No budgets found.",reset,"\n" else columns = [ {"ID" => lambda {|budget| budget['id'] } }, {"NAME" => lambda {|budget| budget['name'] } }, {"DESCRIPTION" => lambda {|budget| truncate_string(budget['description'], 30) } }, # {"ENABLED" => lambda {|budget| format_boolean(budget['enabled']) } }, # {"SCOPE" => lambda {|it| format_budget_scope(it) } }, {"SCOPE" => lambda {|it| it['refName'] } }, {"PERIOD" => lambda {|it| it['year'] } }, {"INTERVAL" => lambda {|it| it['interval'].to_s.capitalize } }, # the UI doesn't consider timezone, so uhh do it this hacky way for now. {"START DATE" => lambda {|it| if it['timezone'] == 'UTC' ((parse_time(it['startDate'], "%Y-%m-%d").strftime("%x")) rescue it['startDate']) # + ' UTC' else format_local_date(it['startDate']) end } }, {"END DATE" => lambda {|it| if it['timezone'] == 'UTC' ((parse_time(it['endDate'], "%Y-%m-%d").strftime("%x")) rescue it['endDate']) # + ' UTC' else format_local_date(it['endDate']) end } }, {"TOTAL" => lambda {|it| format_money(it['totalCost'], it['currency']) } }, {"AVERAGE" => lambda {|it| format_money(it['averageCost'], it['currency']) } }, # {"CREATED BY" => lambda {|budget| budget['createdByName'] ? budget['createdByName'] : budget['createdById'] } }, # {"CREATED" => lambda {|budget| format_local_dt(budget['dateCreated']) } }, # {"UPDATED" => lambda {|budget| format_local_dt(budget['lastUpdated']) } }, ] if [:include_fields] columns = [:include_fields] end print as_pretty_table(budgets, columns, ) print_results_pagination(json_response) end print reset,"\n" end return budgets.empty? ? [3, "no budgets found"] : [0, nil] end |
#remove(args) ⇒ Object
507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 |
# File 'lib/morpheus/cli/commands/budgets_command.rb', line 507 def remove(args) = {} optparse = Morpheus::Cli::OptionParser.new do |opts| opts. = subcommand_usage("[name]") (opts, , [:auto_confirm, :json, :dry_run, :remote]) opts. = "Delete budget.\n[budget] is required. Budget ID or name" end optparse.parse!(args) if args.count != 1 raise_command_error "wrong number of arguments, expected 1 and got (#{args.count}) #{args}\n#{optparse}" end connect() begin budget = find_budget_by_name_or_id(args[0]) return 1 if budget.nil? unless [:yes] || Morpheus::Cli::OptionTypes.confirm("Are you sure you want to delete the budget #{budget['name']}?") return 9, "aborted command" end @budgets_interface.setopts() if [:dry_run] print_dry_run @budgets_interface.dry.destroy(budget['id']) return end json_response = @budgets_interface.destroy(budget['id']) if [:json] print JSON.pretty_generate(json_response) print "\n" else print_green_success "Budget #{budget['name']} removed" # list([] + (options[:remote] ? ["-r",options[:remote]] : [])) end return 0 rescue RestClient::Exception => e print_rest_exception(e, ) exit 1 end end |
#update(args) ⇒ Object
362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 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 499 500 501 502 503 504 505 |
# File 'lib/morpheus/cli/commands/budgets_command.rb', line 362 def update(args) = {} params = {} costs = [] optparse = Morpheus::Cli::OptionParser.new do |opts| opts. = subcommand_usage("[budget] [options]") (opts, , update_budget_option_types) # opts.on('--cost [amount]', String, "Budget cost amount, for use with default year interval.") do |val| # costs['year'] = (val.nil? || val.empty?) ? 0 : val.to_f # end opts.on('--costs COSTS', String, "Budget cost amounts, one for each interval in the budget. eg. [999]") do |val| val = val.to_s.gsub('[', '').gsub(']', '') costs = val.to_s.split(',').collect {|it| parse_cost_amount(it) } end (1..12).each.with_index do |cost_index, i| opts.on("--cost#{cost_index} VALUE", String, "Cost #{cost_index.to_s.capitalize} amount") do |val| #params["cost#{cost_index.to_s}"] = parse_cost_amount(val) costs[i] = parse_cost_amount(val) end opts.add_hidden_option("--cost#{cost_index}") end [:q1,:q2,:q3,:q4,].each.with_index do |quarter, i| opts.on("--#{quarter.to_s} VALUE", String, "#{quarter.to_s.capitalize} cost amount, use with quarter interval.") do |val| costs[i] = parse_cost_amount(val) end opts.add_hidden_option("--#{quarter.to_s}") end [:january,:february,:march,:april,:may,:june,:july,:august,:september,:october,:november,:december].each_with_index do |month, i| opts.on("--#{month.to_s} VALUE", String, "#{month.to_s.capitalize} cost amount, use with month interval.") do |val| costs[i] = parse_cost_amount(val) end opts.add_hidden_option("--#{month.to_s}") end opts.on('--enabled [on|off]', String, "Can be used to disable a policy") do |val| params['enabled'] = val.to_s == 'on' || val.to_s == 'true' || val.to_s.empty? end (opts, ) opts. = <<-EOT Update a budget. [budget] is required. Budget ID or name EOT opts. = "Update a budget.\n[budget] is required. Budget ID or name" end optparse.parse!(args) if args.count != 1 raise_command_error "wrong number of arguments, expected 1 and got (#{args.count}) #{args}\n#{optparse}" end connect() budget = find_budget_by_name_or_id(args[0]) return 1 if budget.nil? original_year = budget['year'] original_interval = budget['interval'] original_costs = budget['costs'].is_a?(Array) ? budget['costs'] : nil # construct payload = [:options] ? [:options].reject {|k,v| k.is_a?(Symbol) } : {} payload = nil if [:payload] payload = [:payload] payload.deep_merge!({'budget' => }) unless .empty? else payload = { 'budget' => { } } # allow arbitrary -O options #passed_options.delete('costs') .delete('tenant') .delete('group') .delete('cloud') .delete('user') payload.deep_merge!({'budget' => }) unless .empty? # prompt for options #params = Morpheus::Cli::OptionTypes.prompt(update_budget_option_types, options[:options], @api_client, options[:params]) v_prompt = Morpheus::Cli::OptionTypes.prompt(update_budget_option_types, [:options].merge(:no_prompt => true), @api_client) params.deep_merge!(v_prompt) # downcase year 'custom' always if params['year'] params['interval'] = params['interval'].to_s.downcase end # downcase interval always if params['interval'] params['interval'] = params['interval'].to_s.downcase end # parse MM/DD/YY but need to convert to to ISO format YYYY-MM-DD for api if params['startDate'] params['startDate'] = format_date(parse_time(params['startDate']), {format:"%Y-%m-%d"}) end if params['endDate'] params['endDate'] = format_date(parse_time(params['endDate']), {format:"%Y-%m-%d"}) end if !costs.empty? params['costs'] = costs # merge original costs in on update unless interval is changing too, should check original_year too probably if going to custom... if params['interval'] && params['interval'] != original_interval original_costs = nil end if original_costs original_costs.each_with_index do |original_cost, i| if params['costs'][i].nil? params['costs'][i] = original_cost end end end else if params['interval'] && params['interval'] != original_interval raise_command_error "Changing interval requires setting the costs as well.\n#{optparse}" end end # budgets api expects scope prefixed parameters like this if params['tenant'].is_a?(String) || params['tenant'].is_a?(Numeric) params['scopeTenantId'] = params.delete('tenant') end if params['group'].is_a?(String) || params['group'].is_a?(Numeric) params['scopeGroupId'] = params.delete('group') end if params['cloud'].is_a?(String) || params['cloud'].is_a?(Numeric) params['scopeCloudId'] = params.delete('cloud') end if params['user'].is_a?(String) || params['user'].is_a?(Numeric) params['scopeUserId'] = params.delete('user') end payload.deep_merge!({'budget' => params}) unless params.empty? if payload.empty? || payload['budget'].empty? raise_command_error "Specify at least one option to update.\n#{optparse}" end end @budgets_interface.setopts() if [:dry_run] print_dry_run @budgets_interface.dry.update(budget['id'], payload) return end json_response = @budgets_interface.update(budget['id'], payload) render_response(json_response, , 'budget') do display_name = json_response['budget'] ? json_response['budget']['name'] : '' print_green_success "Budget #{display_name} updated" get([json_response['budget']['id']] + ([:remote] ? ["-r",[:remote]] : [])) end return 0, nil end |