Class: Morpheus::Cli::JobsCommand
- Inherits:
-
Object
- Object
- Morpheus::Cli::JobsCommand
- Includes:
- AccountsHelper, CliCommand, JobsHelper
- Defined in:
- lib/morpheus/cli/commands/jobs_command.rb
Instance Attribute Summary
Attributes included from CliCommand
Instance Method Summary collapse
- #_get(job_id, options = {}, max_execs = 3) ⇒ Object
- #add(args) ⇒ Object
- #connect(opts) ⇒ Object
- #execute(args) ⇒ Object
- #get(args) ⇒ Object
- #get_execution(args) ⇒ Object
- #get_execution_event(args) ⇒ Object
- #handle(args) ⇒ Object
- #list(args) ⇒ Object
- #list_executions(args) ⇒ Object
- #remove(args) ⇒ Object
- #update(args) ⇒ Object
Methods included from AccountsHelper
#account_column_definitions, #account_users_interface, #accounts_interface, #find_account_by_id, #find_account_by_name, #find_account_by_name_or_id, #find_account_from_options, #find_all_user_ids, #find_role_by_id, #find_role_by_name, #find_role_by_name_or_id, #find_user_by_id, #find_user_by_username, #find_user_by_username_or_id, #find_user_group_by_id, #find_user_group_by_name, #find_user_group_by_name_or_id, #format_access_string, #format_role_type, #format_user_role_names, #format_user_status, #get_access_color, #get_access_string, included, #list_account_column_definitions, #list_user_column_definitions, #list_user_group_column_definitions, #role_column_definitions, #roles_interface, #subtenant_role_column_definitions, #user_column_definitions, #user_group_column_definitions, #user_groups_interface
Methods included from JobsHelper
#api_client, #format_job_status, #get_available_contexts_for_task, #get_available_contexts_for_workflow, #get_process_event_data, included, #jobs_interface, #print_job_execution, #print_job_executions, #print_process_events, #wait_for_job_execution
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
#_get(job_id, options = {}, max_execs = 3) ⇒ Object
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 221 222 223 224 225 226 227 228 229 230 231 232 233 234 |
# File 'lib/morpheus/cli/commands/jobs_command.rb', line 143 def _get(job_id, = {}, max_execs = 3) @jobs_interface.setopts() if !(job_id.to_s =~ /\A\d{1,}\Z/) job = find_by_name_or_id('job', job_id) if !job print_red_alert "Job #{job_id} not found" exit 1 end job_id = job['id'] end max_execs = 3 if max_execs.nil? params = {'includeExecCount' => max_execs} if [:dry_run] print_dry_run @jobs_interface.dry.get(job_id, params) return end json_response = @jobs_interface.get(job_id, params) render_response(json_response, , 'job') do job = json_response['job'] schedule_name = '' if !job['scheduleMode'].nil? if job['scheduleMode'] == 'manual' schedule_name = 'Manual' elsif job['scheduleMode'].to_s.downcase == 'datetime' schedule_name = ("Date and Time - " + (format_local_dt(job['dateTime']).to_s rescue 'n/a')) elsif job['scheduleMode'].to_s == '' schedule_name = 'n/a' # should not happen else begin schedule = @execute_schedules_interface.get(job['scheduleMode'])['schedule'] schedule_name = schedule ? schedule['name'] : '' rescue => ex Morpheus::Logging::DarkPrinter.puts "Failed to load schedule name" if Morpheus::Logging.debug? schedule_name = 'n/a' end end end title = "Morpheus Job" subtitles = [] subtitles += parse_list_subtitles() print_h1 title, subtitles print cyan description_cols = [ {"ID" => lambda {|it| it['id'] } }, {"Name" => lambda {|it| it['name']} }, {"Labels" => lambda {|it| format_list(it['labels'], '', 3) rescue '' } }, {"Job Type" => lambda {|it| it['type']['name']} }, {"Enabled" => lambda {|it| format_boolean(it['enabled'])} }, job['workflow'] ? {'Task' => lambda {|it| (it['workflow']['name'] rescue nil) || it['jobSummary']} } : nil, job['task'] ? {'Workflow' => lambda {|it| (it['task']['name'] rescue nil) || it['jobSummary']} } : nil, job['securityPackage'] ? {'Security Package' => lambda {|it| (it['securityPackage']['name'] rescue nil) || it['jobSummary']} } : nil, job['securityPackage'] ? {'Scan Checklist' => lambda {|it| (it['scanPath'] rescue nil)} } : nil, job['securityPackage'] ? {'Security Profile' => lambda {|it| (it['securityProfile'] rescue nil)} } : nil, {"Schedule" => lambda {|it| schedule_name} } ].compact if job['targetType'] description_cols << {"Context Type" => lambda {|it| it['targetType'] == 'appliance' ? 'None' : it['targetType'] } } if job['targetType'] != 'appliance' description_cols << {"Context #{job['targetType'].capitalize}#{job['targets'].count > 1 ? 's' : ''}" => lambda {|it| it['targets'].collect {|it| it['name']}.join(', ')} } end end print_description_list(description_cols, job) # config = job['config'] # # prune config of stuff that user does not xare about # config = config.reject! {|k,v| ["configList","workflowId","taskId","securitySpecId", "customConfig"].include?(k) } # if config && !config.empty? # print_h2 "Configuration" # print_description_list(config.keys, config) # print reset,"\n" # end if max_execs != 0 print_h2 "Recent Executions" print_job_executions(json_response['executions']['jobExecutions'], ) if json_response['executions']['meta'] && json_response['executions']['meta']['total'] > max_execs print_results_pagination(json_response['executions']) end end print reset,"\n" end return 0, nil end |
#add(args) ⇒ Object
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 361 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 506 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 |
# File 'lib/morpheus/cli/commands/jobs_command.rb', line 236 def add(args) = {} params = {} optparse = Morpheus::Cli::OptionParser.new do |opts| opts. = subcommand_usage( "[name]") opts.on("--name NAME", String, "Updates job name") do |val| params['name'] = val.to_s end opts.on('-l', '--labels [LIST]', String, "Labels") do |val| params['labels'] = parse_labels(val) end opts.on('-a', '--active [on|off]', String, "Can be used to enable / disable the job. Default is on") do |val| params['enabled'] = val.to_s == 'on' || val.to_s == 'true' || val.to_s == '1' || val.to_s == '' end opts.on('--type [TYPE]', String, "Job Type Name, Code or ID. The available types are \"Security Scan Job\", \"Task Job\", and \"Workflow Job\"") do |val| [:type] = val end opts.on('-t', '--task [TASK]', String, "Task ID or name, assigns task to job. This sets the job type to \"Task Job\".") do |val| if [:workflow] raise_command_error "Options --task and --workflow are incompatible" elsif [:security_package] raise_command_error "Options --task and --security-package are incompatible" else [:task] = val end [:type] = 'morpheus.task' end opts.on('-w', '--workflow [WORKFLOW]', String, "Workflow ID or name, assigns workflow to job. This sets the job type to \"Workflow Job\".") do |val| if [:task] raise_command_error "Options --workflow and --task are incompatible" elsif [:security_package] raise_command_error "Options --workflow and --security-package are incompatible" else [:workflow] = val end [:type] = 'morpheus.workflow' end opts.on('--security-package [PACKAGE]', String, "Security Package ID or name, assigns security package to job. This sets the job type to \"Security Scan Job\".") do |val| if [:workflow] raise_command_error "Options --security-package and --workflow are incompatible" elsif [:task] raise_command_error "Options --security-package and --workflow are incompatible" else [:security_package] = val end [:type] = 'morpheus.securityScan' end opts.on('--context-type [TYPE]', String, "Context type (instance|instance-label|server|server-label|none). Default is none") do |val| val = val.to_s.downcase params['targetType'] = (val == 'none' ? 'appliance' : val) end opts.on('--target-type [TYPE]', String, "alias for --context-type") do |val| val = val.to_s.downcase params['targetType'] = (val == 'none' ? 'appliance' : val) end opts.add_hidden_option('--target-type') opts.on('--instances [LIST]', Array, "Context instances(s), comma separated list of instance IDs. Incompatible with --servers") do |list| params['targetType'] = 'instance' params['targets'] = list.collect {|it| it.to_s.strip.empty? ? nil : it.to_s.strip }.compact.uniq.collect {|it| {'refId' => it.to_i}} end opts.on('--instance-label LABEL', String, "Instance Label") do |val| if params['targetType'] && params['targetType'] != 'instance-label' raise ::OptionParser::InvalidOption.new("cannot be combined with another context (#{params['targetType']})") end params['targetType'] = 'instance-label' params['instanceLabel'] = val end opts.on('--servers [LIST]', Array, "Context server(s), comma separated list of server IDs. Incompatible with --instances") do |list| params['targetType'] = 'server' params['targets'] = list.collect {|it| it.to_s.strip.empty? ? nil : it.to_s.strip }.compact.uniq.collect {|it| {'refId' => it.to_i}} end opts.on('--server-label LABEL', String, "Server Label") do |val| if params['targetType'] && params['targetType'] != 'server-label' raise ::OptionParser::InvalidOption.new("cannot be combined with another context (#{params['targetType']})") end params['targetType'] = 'server-label' params['serverLabel'] = val end opts.on('-S', '--schedule [SCHEDULE]', String, "Job execution schedule type name or ID") do |val| [:schedule] = val end opts.on('--config [TEXT]', String, "Custom config") do |val| params['customConfig'] = val.to_s end opts.on('-R', '--run [on|off]', String, "Can be used to run the job now.") do |val| params['run'] = val.to_s == 'on' || val.to_s == 'true' || val.to_s == '1' || val.to_s == '' end opts.on('--date-time DATETIME', String, "Can be used to run schedule at a specific date and time. Use UTC time in the format 2020-02-15T05:00:00Z. This sets scheduleMode to 'dateTime'.") do |val| [:schedule] = 'dateTime' params['dateTime'] = val.to_s end opts.on('--scan-checklist [VALUE]', String, "Scan Checklist. Only applicable to the security scan job type") do |val| # params['config'] ||= {} # params['config']['scanPath'] = val.to_s params['scanPath'] = val.to_s end opts.on('--security-profile [VALUE]', String, "Security Profile. Only applicable to the security scan job type") do |val| # params['config'] ||= {} # params['config']['securityProfile'] = val.to_s params['securityProfile'] = val.to_s end (opts, ) opts. = "Create job." end optparse.parse!(args) connect() verify_args!(args:args, optparse:optparse, max:1) if [:payload] payload = parse_payload(, 'job') else (params, ) # name params['name'] = params['name'] || args[0] || name = Morpheus::Cli::OptionTypes.prompt([{'fieldName' => 'name', 'type' => 'text', 'fieldLabel' => 'Job Name', 'required' => true, 'description' => 'Job Name.'}],[:options],@api_client,{})['name'] # type id is needed to load the options right now.. job_type = nil job_types = get_available_job_types() if [:task].nil? && [:workflow].nil? && [:security_package].nil? if [:type] # match on value (id) or code or name job_type = job_types.find {|it| it['value'].to_s.downcase == [:type].to_s.downcase } || job_types.find {|it| it['code'].to_s.downcase == [:type].to_s.downcase } || job_types.find {|it| it['name'].to_s.downcase == [:type].to_s.downcase || it['name'].to_s.downcase == "#{[:type]} Job".to_s.downcase } if job_type.nil? raise_command_error "Job Type not found for '#{[:type]}'" end else # prompt job_type_id = Morpheus::Cli::OptionTypes.prompt([{'fieldName' => 'jobType', 'type' => 'select', 'fieldLabel' => 'Job Type', 'selectOptions' => job_types, 'required' => true, 'description' => 'Select Job Type.'}],[:options],@api_client,{})['jobType'] job_type = job_types.find {|it| it['value'] == job_type_id} end # prompt task / workflow / securityPackage if job_type['code'] == 'morpheus.task' params['task'] = Morpheus::Cli::OptionTypes.prompt([{'fieldName' => 'task.id', 'fieldLabel' => 'Task', 'type' => 'select', 'required' => true, 'optionSource' => 'tasks'}], [:options], @api_client, {})['task'] elsif job_type['code'] == 'morpheus.workflow' params['workflow'] = Morpheus::Cli::OptionTypes.prompt([{'fieldName' => 'workflow.id', 'fieldLabel' => 'Workflow', 'type' => 'select', 'required' => true, 'optionSource' => 'operationTaskSets'}], [:options], @api_client, {})['workflow'] elsif job_type['code'] == 'morpheus.securityScan' params['securityPackage'] = Morpheus::Cli::OptionTypes.prompt([{'fieldName' => 'securityPackage.id', 'fieldLabel' => 'Security Package', 'type' => 'select', 'required' => true, 'optionSource' => 'securityPackages'}], [:options], @api_client, {})['securityPackage'] end # type is not even included in the payload? lol # params["type"] = {"code" => job_type["code"]} end # task if ![:task].nil? task = find_by_name_or_id('task', [:task]) if task.nil? print_red_alert "Task #{[:task]} not found" exit 1 end params['task'] = {'id' => task['id']} job_type = job_types.find {|it| it['code'] == 'morpheus.task' } # || raise_command_error "Unable to find job type for 'morpheus.task'" end # workflow task_set = nil if ![:workflow].nil? task_set = find_by_name_or_id('task_set', [:workflow]) if task_set.nil? print_red_alert "Workflow #{[:workflow]} not found" exit 1 end params['workflow'] = {'id' => task_set['id']} job_type = job_types.find {|it| it['code'] == 'morpheus.workflow' } # || raise_command_error "Unable to find job type for 'morpheus.workflow'" end # load workflow if we havent yet if (params['workflow'] && params['workflow']['id']) && task_set.nil? task_set = find_by_name_or_id('task_set', params['workflow']['id']) if task_set.nil? print_red_alert "Workflow #{params['workflow']['id']} not found" exit 1 end end # prompt for custom options for workflow custom_option_types = task_set ? task_set['optionTypes'] : nil if custom_option_types && custom_option_types.size() > 0 # they are all returned in a single array right now, so skip prompting for the jobType optionTypes custom_option_types.reject! { |it| it['code'] && it['code'].include?('job.type') } custom_option_types = custom_option_types.collect {|it| it['fieldContext'] = 'customOptions' it } = Morpheus::Cli::OptionTypes.prompt(custom_option_types, [:options], @api_client, {}) params['customOptions'] = ['customOptions'] end # security package if ![:security_package].nil? # task = find_by_name_or_id('securityPackage', options[:security_package]) security_package = nil if ([:security_package].to_s =~ /\A\d{1,}\Z/) security_package = @options_interface.('securityPackages', {})['data'].find {|it| it['value'] == [:security_package].to_i }['value'] else security_package = @options_interface.('securityPackages', {})['data'].find {|it| it['name'].to_s.downcase == [:security_package].to_s.downcase }['value'] end if security_package.nil? print_red_alert "Security Package #{[:security_package]} not found" exit 1 end params['securityPackage'] = {'id' => security_package['id']} job_type = job_types.find {|it| it['code'] == 'morpheus.securityScan' } # || raise_command_error "Unable to find job type for 'morpheus.workflow'" end # load options based upon job type + task / workflow / securityPackage = @jobs_interface.(job_type['id'], {'taskId' => params['task'] ? params['task']['id'] : nil, 'workflowId' => params['workflow'] ? params['workflow']['id'] : nil, 'securityPackageId' => params['securityPackage'] ? params['securityPackage']['id'] : nil}) # securityScan options if job_type['code'] == 'morpheus.securityScan' job_type_option_types = [ {'fieldName' => 'scanPath', 'fieldLabel' => "Scan Checklist", 'type' => 'text', 'required' => true, 'displayOrder' => 20}, {'fieldName' => 'securityProfile', 'fieldLabel' => "Security Profile", 'type' => 'text', 'required' => true, 'displayOrder' => 21} ] #job_type_option_types = job_options['optionTypes'] || [] # reject securitySpecId because already prompted for securityPackage above, # and it is passed as securityPackage.id instead of config.securitySpecId # also remove config context because jobs return this configuration at the level too #job_type_option_types.reject! {|it| it['fieldName'] == "securitySpecId" } #job_type_option_types = job_type_option_types.collect {|it| it.delete("fieldContext") if it["fieldContext"] == "config" } v_prompt = Morpheus::Cli::OptionTypes.prompt(job_type_option_types, [:options], @api_client, {}) v_prompt.deep_compact! params.deep_merge!(v_prompt) end # context type if params['targetType'].nil? params['targetType'] = Morpheus::Cli::OptionTypes.prompt([{'fieldName' => 'targetType', 'fieldLabel' => 'Context Type', 'type' => 'select', 'required' => true, 'selectOptions' => ['targetTypes'], 'defaultValue' => ['targetTypes'].first['name']}], [:options], @api_client, {})['targetType'] end # contexts if ['instance', 'server'].include?(params['targetType']) && (params['targets'].nil? || params['targets'].empty?) targets = [] if params['targetType'] == 'instance' avail_targets = @instances_interface.list({max:10000})['instances'].collect {|it| {'name' => it['name'], 'value' => it['id']}} else avail_targets = @servers_interface.list({max:10000, 'vmHypervisor' => nil, 'containerHypervisor' => nil})['servers'].collect {|it| {'name' => it['name'], 'value' => it['id']}} end target_id = Morpheus::Cli::OptionTypes.prompt([{'fieldName' => 'target', 'fieldLabel' => "Context #{params['targetType'].capitalize}", 'type' => 'select', 'required' => true, 'selectOptions' => avail_targets}], [:options], @api_client, {}, [:no_prompt], true)['target'] targets << target_id avail_targets.reject! {|it| it['value'] == target_id} while !target_id.nil? && !avail_targets.empty? && Morpheus::Cli::OptionTypes.confirm("Add another context #{params['targetType']}?", {:default => false}) target_id = Morpheus::Cli::OptionTypes.prompt([{'fieldName' => 'target', 'fieldLabel' => "Context #{params['targetType'].capitalize}", 'type' => 'select', 'required' => false, 'selectOptions' => avail_targets}], [:options], @api_client, {}, [:no_prompt], true)['target'] if !target_id.nil? targets << target_id avail_targets.reject! {|it| it['value'] == target_id} end end params['targets'] = targets.collect {|it| {'refId' => it}} elsif params['targetType'] == 'instance-label' if params['instanceLabel'].nil? params['instanceLabel'] = Morpheus::Cli::OptionTypes.prompt([{'switch' => 'instance-label', 'fieldName' => 'instanceLabel', 'fieldLabel' => 'Instance Label', 'type' => 'text', 'required' => true, 'description' => 'Instance Label'}], [:options], @api_client)['instanceLabel'] end elsif params['targetType'] == 'server-label' if params['serverLabel'].nil? params['serverLabel'] = Morpheus::Cli::OptionTypes.prompt([{'switch' => 'server-label', 'fieldName' => 'serverLabel', 'fieldLabel' => 'Server Label', 'type' => 'text', 'required' => true, 'description' => 'Server Label'}], [:options], @api_client)['serverLabel'] end end # schedule if [:schedule].nil? [:schedule] = Morpheus::Cli::OptionTypes.prompt([{'fieldName' => 'scheduleMode', 'fieldLabel' => "Schedule", 'type' => 'select', 'required' => true, 'selectOptions' => ['schedules'], 'defaultValue' => ['schedules'].first['name']}], [:options], @api_client, {})['scheduleMode'] params['scheduleMode'] = [:schedule] end if [:schedule] == 'manual' # cool elsif [:schedule].to_s.downcase == 'datetime' # prompt for dateTime if params['dateTime'].nil? params['dateTime'] = Morpheus::Cli::OptionTypes.prompt([{'fieldName' => 'dateTime', 'fieldLabel' => "Date and Time", 'type' => 'text', 'required' => true}], [:options], @api_client, {}, [:no_prompt], true)['dateTime'] end elsif [:schedule].to_s != '' # ok they passed a schedule name or id schedule = ['schedules'].find {|it| it['name'] == [:schedule] || it['value'] == [:schedule].to_i} if schedule.nil? print_red_alert "Schedule #{[:schedule]} not found" exit 1 end [:schedule] = schedule['value'] end params['scheduleMode'] = [:schedule] # custom config if params['customConfig'].nil? && ['allowCustomConfig'] params['customConfig'] = Morpheus::Cli::OptionTypes.prompt([{'fieldName' => 'config', 'fieldLabel' => "Custom Config", 'type' => 'text', 'required' => false}], [:options], @api_client, {})['config'] end payload = {'job' => params} end @jobs_interface.setopts() if [:dry_run] print_dry_run @jobs_interface.dry.create(payload) return end json_response = @jobs_interface.create(payload) job = json_response['job'] || payload["job"] # api only recently started returning job! render_response(json_response, , 'job') do # print_green_success "Job created" print_green_success "Added job #{job['name']}" _get(job['id'], ) end end |
#connect(opts) ⇒ Object
14 15 16 17 18 19 20 21 22 23 24 |
# File 'lib/morpheus/cli/commands/jobs_command.rb', line 14 def connect(opts) @api_client = establish_remote_appliance_connection(opts) @jobs_interface = @api_client.jobs @options_interface = @api_client. @tasks_interface = @api_client.tasks @task_sets_interface = @api_client.task_sets @instances_interface = @api_client.instances @servers_interface = @api_client.servers @containers_interface = @api_client.containers @execute_schedules_interface = @api_client.execute_schedules end |
#execute(args) ⇒ Object
748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 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 798 |
# File 'lib/morpheus/cli/commands/jobs_command.rb', line 748 def execute(args) = {} params = {} optparse = Morpheus::Cli::OptionParser.new do |opts| opts. = subcommand_usage( "[job]") opts.on('--config [TEXT]', String, "Custom config") do |val| params['customConfig'] = val.to_s end (opts, , [:json, :dry_run, :remote]) opts. = "Run job.\n" + "[job] is required. Job ID or name" end optparse.parse!(args) connect() if args.count != 1 raise_command_error "wrong number of arguments, expected 1 and got (#{args.count}) #{args}\n#{optparse}" return 1 end begin job = find_by_name_or_id('job', args[0]) if job.nil? print_red_alert "Job #{args[0]} not found" exit 1 end @jobs_interface.setopts() if [:dry_run] print_dry_run @jobs_interface.dry.execute_job(job['id'], params) return end json_response = @jobs_interface.execute_job(job['id'], params) if [:json] puts as_json(json_response, ) elsif ![:quiet] if json_response['success'] print_green_success "Job queued for execution" _get(job['id'], ) else print_red_alert "Error executing job: #{json_response['msg'] || json_response['errors']}" end end return 0 rescue RestClient::Exception => e print_rest_exception(e, ) exit 1 end end |
#get(args) ⇒ Object
126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 |
# File 'lib/morpheus/cli/commands/jobs_command.rb', line 126 def get(args) = {} optparse = Morpheus::Cli::OptionParser.new do |opts| opts. = subcommand_usage("[job] [max-exec-count]") (opts, ) opts. = "Get details about a job.\n" + "[job] is required. Job ID or name.\n" + "[max-exec-count] is optional. Specified max # of most recent executions. Defaults is 3" end optparse.parse!(args) if args.count < 1 raise_command_error "wrong number of arguments, expected 1-N and got (#{args.count}) #{args}\n#{optparse}" end connect() return _get(args[0], , args.count > 1 ? args[1].to_i : nil) end |
#get_execution(args) ⇒ Object
893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 |
# File 'lib/morpheus/cli/commands/jobs_command.rb', line 893 def get_execution(args) = {} params = {} optparse = Morpheus::Cli::OptionParser.new do |opts| opts. = subcommand_usage("[id]") (opts, , [:details]) opts. = "Get details about a job.\n" + "[id] is required. Job execution ID." 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() @jobs_interface.setopts() if [:dry_run] print_dry_run @jobs_interface.dry.get_execution(args[0], params) return end json_response = @jobs_interface.get_execution(args[0], params) render_response(json_response, , 'jobExecution') do print_h1 "Morpheus Job Execution", [], print_job_execution(json_response['jobExecution'], ) end return 0, nil end |
#get_execution_event(args) ⇒ Object
921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 |
# File 'lib/morpheus/cli/commands/jobs_command.rb', line 921 def get_execution_event(args) = {} params = {} optparse = Morpheus::Cli::OptionParser.new do |opts| opts. = subcommand_usage("[id] [event]") (opts, ) opts. = "Get details about a job.\n" + "[id] is required. Job execution ID.\n" + "[event] is required. Process event ID." end optparse.parse!(args) if args.count != 2 raise_command_error "wrong number of arguments, expected 2 and got (#{args.count}) #{args}\n#{optparse}" end connect() begin @jobs_interface.setopts() if [:dry_run] print_dry_run @jobs_interface.dry.get_execution_event(args[0].to_i, args[1].to_i, params) return end json_response = @jobs_interface.get_execution_event(args[0].to_i, args[1].to_i, params) render_result = render_with_format(json_response, , 'processEvent') return 0 if render_result title = "Morpheus Job Execution Event" subtitles = [] subtitles += parse_list_subtitles() print_h1 title, subtitles event = json_response['processEvent'] event_data = get_process_event_data(event) description_cols = { "ID" => lambda {|it| it[:id]}, "Description" => lambda {|it| it[:description]}, "Start Date" => lambda {|it| it[:start_date]}, "Created By" => lambda {|it| it[:created_by]}, "Duration" => lambda {|it| it[:duration]}, "Status" => lambda {|it| it[:status]} } print_description_list(description_cols, event_data) if event_data[:output] && event_data[:output].strip.length > 0 print_h2 "Output" print event['output'] end if event_data[:error] && event_data[:error].strip.length > 0 print_h2 "Error" print red print event['message'] || event['error'] print reset end print reset,"\n" return 0 rescue RestClient::Exception => e print_rest_exception(e, ) exit 1 end end |
#handle(args) ⇒ Object
26 27 28 |
# File 'lib/morpheus/cli/commands/jobs_command.rb', line 26 def handle(args) handle_subcommand(args) end |
#list(args) ⇒ Object
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 |
# File 'lib/morpheus/cli/commands/jobs_command.rb', line 30 def list(args) = {} [:show_stats] = true params = {} optparse = Morpheus::Cli::OptionParser.new do |opts| opts. = subcommand_usage() opts.on("--source [all|user|discovered]", String, "Filters job based upon specified source. Default is all") do |val| [:source] = val.to_s end opts.on("--internal [true|false]", String, "Filters job based on internal flag. Internal jobs are excluded by default.") do |val| params["internalOnly"] = (val.to_s != "false") end opts.on("--stats [true|false]", String, "Hide Execution Stats. Job statistics are displayed by default.") do |val| [:show_stats] = (val.to_s != "false") 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 (opts, ) opts. = "List jobs." end optparse.parse!(args) connect() # verify_args!(args:args, optparse:optparse, count:0) if args.count > 0 [:phrase] = args.join(" ") end params.merge!(()) if ![:source].nil? if !['all', 'user', 'discovered', 'sync'].include?([:source]) raise_command_error("Invalid source filter #{[:source]}", args, optparse) end params['itemSource'] = [:source] == 'discovered' ? 'sync' : [:source] end @jobs_interface.setopts() if [:dry_run] print_dry_run @jobs_interface.dry.list(params) return end json_response = @jobs_interface.list(params) jobs = json_response['jobs'] render_response(json_response, , 'jobs') do title = "Morpheus Jobs" subtitles = [] subtitles += parse_list_subtitles() if params["internalOnly"] subtitles << "internalOnly: #{params['internalOnly']}" end print_h1 title, subtitles, if jobs.empty? print cyan,"No jobs found.",reset,"\n" else columns = { "ID" => 'id', "Type" => lambda {|job| job['type'] ? job['type']['name'] : '' }, "Name" => 'name', "Labels" => lambda {|it| format_list(it['labels'], '', 3) rescue '' }, "Details" => lambda {|job| job['jobSummary'] }, "Enabled" => lambda {|job| "#{job['enabled'] ? '' : yellow}#{format_boolean(job['enabled'])}#{cyan}" }, # "Date Created" => lambda {|job| format_local_dt(job['dateCreated']) }, # "Last Updated" => lambda {|job| format_local_dt(job['lastUpdated']) }, "Last Run" => lambda {|job| format_local_dt(job['lastRun']) }, "Next Run" => lambda {|job| job['enabled'] && job['scheduleMode'] && job['scheduleMode'] != 'manual' ? format_local_dt(job['nextFire']) : '' }, "Last Result" => lambda {|job| format_job_status(job['lastResult']) }, } print as_pretty_table(jobs, columns.upcase_keys!, ) print_results_pagination(json_response) if [:show_stats] if stats = json_response['stats'] label_width = 17 print_h2 "Execution Stats - Last 7 Days" print cyan print "Jobs".rjust(label_width, ' ') + ": #{stats['jobCount']}\n" print "Executions Today".rjust(label_width, ' ') + ": #{stats['todayCount']}\n" print "Daily Executions".rjust(label_width, ' ') + ": " + stats['executionsPerDay'].join(' | ') + "\n" print "Total Executions".rjust(label_width, ' ') + ": #{stats['execCount']}\n" print "Completed".rjust(label_width, ' ') + ": " + (stats['execSuccessRate'].to_f, 100, {bar_color:green}) + "#{stats['execSuccess']}".rjust(15, ' ') + " of " + "#{stats['execCount']}".ljust(15, ' ') + "\n#{cyan}" print "Failed".rjust(label_width, ' ') + ": " + (stats['execFailedRate'].to_f, 100, {bar_color:red}) + "#{stats['execFailed']}".rjust(15, ' ') + " of " + "#{stats['execCount']}".ljust(15, ' ') + "\n#{cyan}" end print reset,"\n" end end print reset,"\n" end if jobs.empty? return 1, "no jobs found" else return 0, nil end end |
#list_executions(args) ⇒ Object
832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 |
# File 'lib/morpheus/cli/commands/jobs_command.rb', line 832 def list_executions(args) = {} params = {} optparse = Morpheus::Cli::OptionParser.new do |opts| opts. = subcommand_usage("[job]") opts.on('--job JOB', String, "Filter by Job ID or name.") do |val| [:job] = val end opts.on("--internal [true|false]", String, "Filters executions based on internal flag. Internal executions are excluded by default.") do |val| params["internalOnly"] = (val.to_s != "false") end opts.on("--automation [true|false]", String, "Filters executions based on automation flag. Non-automation executions include ansible and kubernetes job types.") do |val| params["automation"] = (val.to_s != "false") end (opts, , [:details]) opts. = "List job executions.\n" + "[job] is optional. Job ID or name to filter executions." end optparse.parse!(args) connect() # verify_args!(args:args, optparse:optparse, max:1) if args.count > 0 [:job] = args.join(" ") end params.merge!(()) if [:job] job = find_by_name_or_id('job', [:job]) if job.nil? raise_command_error "Job #{[:job]} not found" end params['jobId'] = job['id'] end @jobs_interface.setopts() if [:dry_run] print_dry_run @jobs_interface.dry.list_executions(params) return end json_response = @jobs_interface.list_executions(params) job_executions = json_response['jobExecutions'] render_response(json_response, , 'jobExecutions') do title = "Morpheus Job Executions" subtitles = job ? ["Job: #{job['name']}"] : [] subtitles += parse_list_subtitles() if params["internalOnly"] subtitles << "internalOnly: #{params['internalOnly']}" end if !params["automation"].nil? subtitles << "automation: #{params['automation']}" end print_h1 title, subtitles, print_job_executions(job_executions, ) print_results_pagination(json_response) unless job_executions.size == 0 print reset,"\n" end return 0, nil end |
#remove(args) ⇒ Object
800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 |
# File 'lib/morpheus/cli/commands/jobs_command.rb', line 800 def remove(args) = {} params = {} optparse = Morpheus::Cli::OptionParser.new do |opts| opts. = subcommand_usage( "[job]") (opts, ) opts. = "Remove job.\n" + "[job] is required. Job ID or name" end optparse.parse!(args) connect() verify_args!(args:args, optparse:optparse, count:1) job = find_by_name_or_id('job', args[0]) if job.nil? print_red_alert "Job #{args[0]} not found" exit 1 end unless [:yes] || ::Morpheus::Cli::OptionTypes::confirm("Are you sure you would like to remove the job '#{job['name']}'?", ) return 9, "aborted command" end @jobs_interface.setopts() if [:dry_run] print_dry_run @jobs_interface.dry.destroy(job['id'], params) return end json_response = @jobs_interface.destroy(job['id'], params) render_response(json_response, ) do print_green_success "Job #{job['name']} removed" end return 0, nil end |
#update(args) ⇒ Object
543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 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 745 746 |
# File 'lib/morpheus/cli/commands/jobs_command.rb', line 543 def update(args) = {} params = {} optparse = Morpheus::Cli::OptionParser.new do |opts| opts. = subcommand_usage( "[job]") opts.on("--name NAME", String, "Updates job name") do |val| params['name'] = val.to_s end opts.on('-l', '--labels [LIST]', String, "Labels") do |val| params['labels'] = parse_labels(val) end opts.on('-a', '--active [on|off]', String, "Can be used to enable / disable the job. Default is on") do |val| params['enabled'] = val.to_s == 'on' || val.to_s == 'true' || val.to_s == '1' || val.to_s == '' end opts.on('-t', '--task [TASK]', String, "Task ID or name, assigns task to job. Only compatible with workflow job type.") do |val| if [:workflow] raise_command_error "Options --task and --workflow are incompatible" elsif [:security_package] raise_command_error "Options --task and --security-package are incompatible" else [:task] = val end end opts.on('-w', '--workflow [WORKFLOW]', String, "Workflow ID or name, assigns workflow to job. Only compatible with security scan job type.") do |val| if [:task] raise_command_error "Options --workflow and --task are incompatible" elsif [:security_package] raise_command_error "Options --workflow and --security-package are incompatible" else [:workflow] = val end end opts.on('--security-package [PACKAGE]', String, "Security Package ID or name, assigns security package to job. Only compatible with security scan job type.") do |val| if [:workflow] raise_command_error "Options --security-package and --workflow are incompatible" elsif [:task] raise_command_error "Options --security-package and --workflow are incompatible" else [:security_package] = val end end opts.on('--context-type [TYPE]', String, "Context type (instance|instance-label|server|server-label|none). Default is none") do |val| val = val.to_s.downcase params['targetType'] = (val == 'none' ? 'appliance' : val) end opts.on('--target-type [TYPE]', String, "alias for --context-type") do |val| val = val.to_s.downcase params['targetType'] = (val == 'none' ? 'appliance' : val) end opts.add_hidden_option('--target-type') opts.on('--instances [LIST]', Array, "Context instances(s), comma separated list of instance IDs. Incompatible with --servers") do |list| params['targetType'] = 'instance' [:targets] = list.collect {|it| it.to_s.strip.empty? ? nil : it.to_s.strip.to_i }.compact.uniq.collect {|it| {'refId' => it.to_i}} end opts.on('--instance-label LABEL', String, "Instance Label") do |val| if params['targetType'] && params['targetType'] != 'instance-label' raise ::OptionParser::InvalidOption.new("cannot be combined with another context (#{params['targetType']})") end params['targetType'] = 'instance-label' params['instanceLabel'] = val end opts.on('--servers [LIST]', Array, "Context server(s), comma separated list of server IDs. Incompatible with --instances") do |list| params['targetType'] = 'server' [:targets] = list.collect {|it| it.to_s.strip.empty? ? nil : it.to_s.strip.to_i }.compact.uniq.collect {|it| {'refId' => it.to_i}} end opts.on('--server-label LABEL', String, "Server Label") do |val| if params['targetType'] && params['targetType'] != 'server-label' raise ::OptionParser::InvalidOption.new("cannot be combined with another context (#{params['targetType']})") end params['targetType'] = 'server-label' params['serverLabel'] = val end opts.on('--schedule [SCHEDULE]', String, "Job execution schedule type name or ID") do |val| [:schedule] = val end opts.on('--config [TEXT]', String, "Custom config") do |val| params['customConfig'] = val.to_s end opts.on('-R', '--run [on|off]', String, "Can be used to run the job now.") do |val| params['run'] = val.to_s == 'on' || val.to_s == 'true' || val.to_s == '1' || val.to_s == '' end opts.on('--date-time DATETIME', String, "Can be used to run schedule at a specific date and time. Use UTC time in the format 2020-02-15T05:00:00Z. This sets scheduleMode to 'dateTime'.") do |val| [:schedule] = 'dateTime' params['dateTime'] = val.to_s end (opts, ) opts. = "Update job.\n" + "[job] is required. Job ID or name" end optparse.parse!(args) connect() verify_args!(args:args, optparse:optparse, count:1) job = find_by_name_or_id('job', args[0]) if job.nil? print_red_alert "Job #{args[0]} not found" exit 1 end if [:payload] payload = parse_payload(, 'job') else (params, ) job_type_id = job['type']['id'] if ![:task].nil? task = find_by_name_or_id('task', [:task]) if task.nil? print_red_alert "Task #{[:task]} not found" exit 1 end params['task'] = {'id': task['id']} job_type_id = load_job_type_id_by_code('morpheus.task') end if ![:workflow].nil? task_set = find_by_name_or_id('task_set', [:workflow]) if task_set.nil? print_red_alert "Workflow #{[:workflow]} not found" exit 1 end params['workflow'] = {'id': task_set['id']} job_type_id = load_job_type_id_by_code('morpheus.workflow') end if ![:targets].nil? && ['instance', 'server'].include?(params['targetType']) params['targets'] = [] target_type = params['targetType'] || job['targetType'] [:targets].collect do |it| target = find_by_name_or_id(target_type, it['refId']) if target.nil? print_red_alert "Context #{target_type} #{it['refId']} not found" exit 1 end params['targets'] << it end end if ![:schedule].nil? if [:schedule] != 'manual' && [:schedule].to_s.downcase != 'datetime' = @jobs_interface.(job_type_id) schedule = ['schedules'].find {|it| it['name'] == [:schedule] || it['value'] == [:schedule].to_i} if schedule.nil? print_red_alert "Schedule #{[:schedule]} not found" exit 1 end [:schedule] = schedule['value'] end params['scheduleMode'] = [:schedule] end # schedule if ![:schedule].nil? if [:schedule] == 'manual' # cool elsif [:schedule].to_s.downcase == 'datetime' # prompt for dateTime if params['dateTime'].nil? raise_command_error "--date-time is required for schedule '#{[:schedule]}'\n#{optparse}" end elsif [:schedule].to_s != '' = @jobs_interface.(job_type_id) [:schedule] = Morpheus::Cli::OptionTypes.prompt([{'fieldName' => 'schedule', 'fieldLabel' => "Schedule", 'type' => 'select', 'required' => true, 'selectOptions' => ['schedules'], 'defaultValue' => ['schedules'].first['name']}], [:options], @api_client, {})['schedule'] params['scheduleMode'] = [:schedule] # ok they passed a schedule name or id schedule = ['schedules'].find {|it| it['name'] == [:schedule] || it['value'] == [:schedule].to_i} if schedule.nil? print_red_alert "Schedule #{[:schedule]} not found" exit 1 end [:schedule] = schedule['value'] end end payload = {'job' => params} end if payload['job'].nil? || payload['job'].empty? print_green_success "Nothing to update" exit 1 end @jobs_interface.setopts() if [:dry_run] print_dry_run @jobs_interface.dry.update(job['id'], payload) return end json_response = @jobs_interface.update(job['id'], payload) job = json_response["job"] || job # api only recently started returning job! render_response(json_response, , 'job') do print_green_success "Updated job #{job['name']}" _get(job['id'], ) end end |