Class: Morpheus::Cli::JobsCommand

Inherits:
Object
  • Object
show all
Includes:
AccountsHelper, CliCommand
Defined in:
lib/morpheus/cli/jobs_command.rb

Instance Attribute Summary

Attributes included from CliCommand

#no_prompt

Instance Method Summary collapse

Methods included from AccountsHelper

#account_column_definitions, #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, #users_interface

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

#_get(job_id, max_execs = 3, options = {}) ⇒ Object



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
221
222
223
224
225
226
227
228
# File 'lib/morpheus/cli/jobs_command.rb', line 142

def _get(job_id, max_execs = 3, options = {})
  begin
    @jobs_interface.setopts(options)

    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 options[:dry_run]
      print_dry_run @jobs_interface.dry.get(job_id, params)
      return
    end
    json_response = @jobs_interface.get(job_id, params)

    render_result = render_with_format(json_response, options, 'job')
    return 0 if render_result

    title = "Morpheus Job"
    subtitles = []
    subtitles += parse_list_subtitles(options)
    print_h1 title, subtitles

    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

    print cyan
    description_cols = {
        "ID" => lambda {|it| it['id'] },
        "Name" => lambda {|it| it['name']},
        "Job Type" => lambda {|it| it['type']['name']},
        "Enabled" => lambda {|it| format_boolean(it['enabled'])},
        (job['workflow'] ? 'Workflow' : 'Task') => lambda {|it| it['jobSummary']},
        "Schedule" => lambda {|it| schedule_name}
    }

    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)

    if max_execs != 0
      print_h2 "Recent Executions"
      print_job_executions(json_response['executions']['jobExecutions'], options)

      if json_response['executions']['meta'] && json_response['executions']['meta']['total'] > max_execs
        print_results_pagination(json_response['executions'])
      end
    end
    print reset,"\n"
    return 0
  rescue RestClient::Exception => e
    print_rest_exception(e, options)
    exit 1
  end
end

#add(args) ⇒ Object



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
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
# File 'lib/morpheus/cli/jobs_command.rb', line 230

def add(args)
  options = {}
  params = {}
  optparse = Morpheus::Cli::OptionParser.new do |opts|
    opts.banner = subcommand_usage( "[name]")
    opts.on("--name NAME", String, "Updates job name") do |val|
      params['name'] = val.to_s
    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 code, assigns task to job. Incompatible with --workflow option.") do |val|
      if options[:workflow].nil?
        options[:task] = val
      else
        raise_command_error "Options --task and --workflow are incompatible"
      end
    end
    opts.on('-w', '--workflow [WORKFLOW]', String, "Workflow ID or code, assigns workflow to job. Incompatible with --task option.") do |val|
      if options[:task].nil?
        options[:workflow] = val
      else
        raise_command_error "Options --task and --workflow are incompatible"
      end
    end
    opts.on('--context-type [TYPE]', String, "Context type (instance|server|none). Default is none") do |val|
      params['targetType'] = (val == 'none' ? 'appliance' : val)
    end
    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('--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('-S', '--schedule [SCHEDULE]', String, "Job execution schedule type name or ID") do |val|
      options[: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|
      options[:schedule] = 'dateTime'
      params['dateTime'] = val.to_s
    end
    build_common_options(opts, options, [:options, :payload, :json, :dry_run, :remote, :quiet])
    opts.footer = "Create job."
  end
  optparse.parse!(args)
  connect(options)
  if args.count > 1
    raise_command_error "wrong number of arguments, expected 0 or 1 and got (#{args.count}) #{args}\n#{optparse}"
    return 1
  end

  begin
    if options[:payload]
      payload = parse_payload(options, 'job')
    else
      apply_options(params, options)

      # 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[:options],@api_client,{})['name']

      if options[:task].nil? && options[:workflow].nil?
        # prompt job type
        job_types = @options_interface.options_for_source('jobTypes', {})['data']
        job_type_id = Morpheus::Cli::OptionTypes.prompt([{'fieldName' => 'jobType', 'type' => 'select', 'fieldLabel' => 'Job Type', 'selectOptions' => job_types, 'required' => true, 'description' => 'Select Job Type.'}],options[:options],@api_client,{})['jobType']
        job_type = job_types.find {|it| it['value'] == job_type_id}

        job_options = @jobs_interface.options(job_type_id)

        # prompt task / workflow
        if ['morpheus.task.jobType', 'morpheus.task'].include?(job_type['code'])
          params['task'] = Morpheus::Cli::OptionTypes.prompt([{'fieldName' => 'task.id', 'fieldLabel' => 'Task', 'type' => 'select', 'required' => true, 'optionSource' => 'tasks'}], options[:options], @api_client, {})['task']
        else
          params['workflow'] = Morpheus::Cli::OptionTypes.prompt([{'fieldName' => 'workflow.id', 'fieldLabel' => 'Workflow', 'type' => 'select', 'required' => true, 'optionSource' => 'operationTaskSets'}], options[:options], @api_client, {})['workflow']
        end
      end

      # task
      if !options[:task].nil?
        task = find_by_name_or_id('task', options[:task])

        if task.nil?
          print_red_alert "Task #{options[:task]} not found"
          exit 1
        end
        params['task'] = {'id' => task['id']}
        job_type_id = load_job_type_id_by_code('morpheus.task.jobType') || load_job_type_id_by_code('morpheus.task')
      end

      # workflow
      task_set = nil
      if !options[:workflow].nil?
        task_set = find_by_name_or_id('task_set', options[:workflow])

        if task_set.nil?
          print_red_alert "Workflow #{options[:workflow]} not found"
          exit 1
        end
        params['workflow'] = {'id' => task_set['id']}
        job_type_id = load_job_type_id_by_code('morpheus.workflow.jobType') || load_job_type_id_by_code('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
        }
        custom_options = Morpheus::Cli::OptionTypes.prompt(custom_option_types, options[:options], @api_client, {})
        params['customOptions'] = custom_options['customOptions']
      end


      # load options based upon job type + task / taskset
      job_options = @jobs_interface.options(job_type_id, {'taskId' => params['task'] ? params['task']['id'] : nil, 'workflowId' => params['workflow'] ? params['workflow']['id'] : nil})
      option_type_id = job_options['optionTypes'][0]['id']

      # context type
      if params['targetType'].nil?
        params['targetType'] = Morpheus::Cli::OptionTypes.prompt([{'fieldName' => 'targetType', 'fieldLabel' => 'Context Type', 'type' => 'select', 'required' => true, 'selectOptions' => job_options['targetTypes'], 'defaultValue' => job_options['targetTypes'].first['name']}], options[: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[:options], @api_client, {}, options[: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[:options], @api_client, {}, options[: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}}
      end

      # schedule
      if options[:schedule].nil?
        options[:schedule] = Morpheus::Cli::OptionTypes.prompt([{'fieldName' => 'scheduleMode', 'fieldLabel' => "Schedule", 'type' => 'select', 'required' => true, 'selectOptions' => job_options['schedules'], 'defaultValue' => job_options['schedules'].first['name']}], options[:options], @api_client, {})['scheduleMode']
        params['scheduleMode'] = options[:schedule]
      end

      if options[:schedule] == 'manual'
        # cool
      elsif options[: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[:options], @api_client, {}, options[:no_prompt], true)['dateTime']
        end
      elsif options[:schedule].to_s != ''
         # ok they passed a schedule name or id
        schedule = job_options['schedules'].find {|it| it['name'] == options[:schedule] || it['value'] == options[:schedule].to_i}

        if schedule.nil?
          print_red_alert "Schedule #{options[:schedule]} not found"
          exit 1
        end
        options[:schedule] = schedule['value']
      end
      params['scheduleMode'] = options[:schedule]

      # custom config
      if params['customConfig'].nil? && job_options['allowCustomConfig']
        params['customConfig'] = Morpheus::Cli::OptionTypes.prompt([{'fieldName' => 'config', 'fieldLabel' => "Custom Config", 'type' => 'text', 'required' => false}], options[:options], @api_client, {})['config']
      end
      payload = {'job' => params}
    end

    @jobs_interface.setopts(options)
    if options[:dry_run]
      print_dry_run @jobs_interface.dry.create(payload)
      return
    end
    json_response = @jobs_interface.create(payload)

    if options[:json]
      puts as_json(json_response, options)
    elsif !options[:quiet]
      if json_response['success']
        print_green_success  "Job created"
        _get(json_response['id'], 0, options)
      else
        print_red_alert "Error creating job: #{json_response['msg'] || json_response['errors']}"
      end
    end
    return 0
  rescue RestClient::Exception => e
    print_rest_exception(e, options)
    exit 1
  end
end

#connect(opts) ⇒ Object



13
14
15
16
17
18
19
20
21
22
23
# File 'lib/morpheus/cli/jobs_command.rb', line 13

def connect(opts)
  @api_client = establish_remote_appliance_connection(opts)
  @jobs_interface = @api_client.jobs
  @options_interface = @api_client.options
  @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



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
# File 'lib/morpheus/cli/jobs_command.rb', line 632

def execute(args)
  options = {}
  params = {}
  optparse = Morpheus::Cli::OptionParser.new do |opts|
    opts.banner = subcommand_usage( "[job]")
    opts.on('--config [TEXT]', String, "Custom config") do |val|
      params['customConfig'] = val.to_s
    end
    build_common_options(opts, options, [:json, :dry_run, :remote])
    opts.footer = "Run job.\n" +
        "[job] is required. Job ID or name"
  end
  optparse.parse!(args)
  connect(options)
  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(options)
    if options[: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 options[:json]
      puts as_json(json_response, options)
    elsif !options[:quiet]
      if json_response['success']
        print_green_success  "Job queued for execution"
        _get(job['id'], nil, options)
      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, options)
    exit 1
  end
end

#get(args) ⇒ Object



125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
# File 'lib/morpheus/cli/jobs_command.rb', line 125

def get(args)
  options = {}
  optparse = Morpheus::Cli::OptionParser.new do |opts|
    opts.banner = subcommand_usage("[job] [max-exec-count]")
    build_common_options(opts, options, [:json, :dry_run, :remote])
    opts.footer = "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(options)
  return _get(args[0], args.count > 1 ? args[1].to_i : nil, options)
end

#get_execution(args) ⇒ Object



788
789
790
791
792
793
794
795
796
797
798
799
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
831
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
# File 'lib/morpheus/cli/jobs_command.rb', line 788

def get_execution(args)
  options = {}
  params = {}
  optparse = Morpheus::Cli::OptionParser.new do |opts|
    opts.banner = subcommand_usage("[id]")
    opts.on('-D', '--details [on|off]', String, "Can be used to enable / disable execution details. Default is on") do |val|
      options[:details] = val.to_s == 'on' || val.to_s == 'true' || val.to_s == '1' || val.to_s == ''
    end
    build_common_options(opts, options, [:json, :dry_run, :remote])
    opts.footer = "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(options)

  begin
    @jobs_interface.setopts(options)

    if options[: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_result = render_with_format(json_response, options, 'job')
    return 0 if render_result

    title = "Morpheus Job Execution"
    subtitles = []
    subtitles += parse_list_subtitles(options)
    print_h1 title, subtitles

    exec = json_response['jobExecution']
    process = exec['process']
    print cyan
    description_cols = {
        "ID" => lambda {|it| it['id'] },
        "Job" => lambda {|it| it['job'] ? it['job']['name'] : ''},
        "Job Type" => lambda {|it| it['job'] && it['job']['type'] ? (it['job']['type']['code'] == 'morpheus.workflow' ? 'Workflow' : 'Task') : ''},
        # "Description" => lambda {|it| it['description'] || (it['job'] ? it['job']['description'] : '') },
        "Start Date" => lambda {|it| format_local_dt(it['startDate'])},
        "ETA/Time" => lambda {|it| it['duration'] ? format_human_duration(it['duration'] / 1000.0) : ''},
        "Status" => lambda {|it| format_status(it['status'])},
        "Error" => lambda {|it| it['process'] && (it['process']['message'] || it['process']['error']) ? red + (it['process']['message'] || it['process']['error']) + cyan : ''},
        "Created By" => lambda {|it| it['createdBy'].nil? ? '' : it['createdBy']['displayName'] || it['createdBy']['username']}
    }
    description_cols["Process ID"] = lambda {|it| process['id']} if !process.nil?

    print_description_list(description_cols, exec)

    if !process.nil?
      if options[:details]
      process_data = get_process_event_data(process)
        print_h2 "Execution Details"
        description_cols = {
            "Process ID" => lambda {|it| it[:id]},
            "Description" => lambda {|it| it[:description]},
            "Start Data" => lambda {|it| it[:start_date]},
            "Created By" => lambda {|it| it[:created_by]},
            "Duration" => lambda {|it| it[:duration]},
            "Status" => lambda {|it| it[:status]}
        }
        if !options[:details]
          description_cols["Output"] = lambda {|it| it[:output]} if process_data[:output] && process_data[:output].strip.length > 0
          description_cols["Error"] = lambda {|it| it[:error]} if process_data[:error] && process_data[:error].strip.length > 0
        end

        print_description_list(description_cols, process_data)

        if process_data[:output] && process_data[:output].strip.length > 0
          print_h2 "Output"
          print process['output']
        end
        if process_data[:error] && process_data[:error].strip.length > 0
          print_h2 "Error"
          print process['message'] || process['error']
          print reset,"\n"
        end
      end

      if process['events'] && !process['events'].empty?
        print_h2 "Execution Events"
        print_process_events(process['events'])
      end
    end
    print reset,"\n"
    return 0
  rescue RestClient::Exception => e
    print_rest_exception(e, options)
    exit 1
  end
end

#get_execution_event(args) ⇒ Object



884
885
886
887
888
889
890
891
892
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
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
# File 'lib/morpheus/cli/jobs_command.rb', line 884

def get_execution_event(args)
  options = {}
  params = {}
  optparse = Morpheus::Cli::OptionParser.new do |opts|
    opts.banner = subcommand_usage("[id] [event]")
    build_common_options(opts, options, [:json, :dry_run, :remote])
    opts.footer = "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(options)

  begin
    @jobs_interface.setopts(options)

    if options[: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, options, 'processEvent')
    return 0 if render_result

    title = "Morpheus Job Execution Event"
    subtitles = []
    subtitles += parse_list_subtitles(options)
    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 Data" => 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 event['message'] || event['error']
    end
    print reset,"\n"
    return 0
  rescue RestClient::Exception => e
    print_rest_exception(e, options)
    exit 1
  end
end

#handle(args) ⇒ Object



25
26
27
# File 'lib/morpheus/cli/jobs_command.rb', line 25

def handle(args)
  handle_subcommand(args)
end

#list(args) ⇒ Object



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
# File 'lib/morpheus/cli/jobs_command.rb', line 29

def list(args)
  options = {}
  params = {}
  optparse = Morpheus::Cli::OptionParser.new do |opts|
    opts.banner = subcommand_usage()
    opts.on("--source [all|user|discovered]", String, "Filters job based upon specified source. Default is all") do |val|
      options[: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
    build_common_options(opts, options, [:list, :query, :json, :yaml, :csv, :fields, :dry_run, :remote])
    opts.footer = "List jobs."
  end
  optparse.parse!(args)
  connect(options)
  if args.count != 0
    raise_command_error "wrong number of arguments, expected 0 and got (#{args.count}) #{args}\n#{optparse}"
    return 1
  end

  begin
    params.merge!(parse_list_options(options))

    if !options[:source].nil?
      if !['all', 'user', 'discovered', 'sync'].include?(options[:source])
        print_red_alert "Invalid source filter #{options[:source]}"
        exit 1
      end
      params['itemSource'] = options[:source] == 'discovered' ? 'sync' : options[:source]
    end

    @jobs_interface.setopts(options)
    if options[:dry_run]
      print_dry_run @jobs_interface.dry.list(params)
      return
    end
    json_response = @jobs_interface.list(params)

    render_result = render_with_format(json_response, options, 'jobs')
    return 0 if render_result

    title = "Morpheus Jobs"
    subtitles = []
    subtitles += parse_list_subtitles(options)
    if params["internalOnly"]
      subtitles << "internalOnly: #{params['internalOnly']}"
    end
    print_h1 title, subtitles

    jobs = json_response['jobs']

    if jobs.empty?
      print cyan,"No jobs found.",reset,"\n"
    else
      rows = jobs.collect do |job|
        {
            id: job['id'],
            type: job['type'] ? job['type']['name'] : '',
            name: job['name'],
            details: job['jobSummary'],
            enabled: "#{job['enabled'] ? '' : yellow}#{format_boolean(job['enabled'])}#{cyan}",
            lastRun: format_local_dt(job['lastRun']),
            nextRun: job['enabled'] && job['scheduleMode'] && job['scheduleMode'] != 'manual' ? format_local_dt(job['nextFire']) : '',
            lastResult: format_status(job['lastResult'])
        }
      end
      columns = [
          :id, :type, :name, :details, :enabled, :lastRun, :nextRun, :lastResult
      ]
      print as_pretty_table(rows, columns, options)
      print_results_pagination(json_response)

      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, ' ') + ": " + generate_usage_bar(stats['execSuccessRate'].to_f, 100, {bar_color:green}) + "#{stats['execSuccess']}".rjust(15, ' ') + " of " + "#{stats['execCount']}".ljust(15, ' ') + "\n#{cyan}"
        print "Failed".rjust(label_width, ' ') + ": " + generate_usage_bar(stats['execFailedRate'].to_f, 100, {bar_color:red}) + "#{stats['execFailed']}".rjust(15, ' ') + " of " + "#{stats['execCount']}".ljust(15, ' ') + "\n#{cyan}"
      end
      print reset,"\n"
    end
    print reset,"\n"
    return 0
  rescue RestClient::Exception => e
    print_rest_exception(e, options)
    exit 1
  end
end

#list_executions(args) ⇒ Object



733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
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
# File 'lib/morpheus/cli/jobs_command.rb', line 733

def list_executions(args)
  options = {}
  params = {}
  optparse = Morpheus::Cli::OptionParser.new do |opts|
    opts.banner = subcommand_usage("[job]")
    build_common_options(opts, options, [:list, :query, :json, :yaml, :csv, :fields, :dry_run, :remote])
    opts.footer = "List job executions.\n" +
        "[job] is optional. Job ID or name to filter executions."

  end
  optparse.parse!(args)
  connect(options)
  if args.count > 1
    raise_command_error "wrong number of arguments, expected 0..1 and got (#{args.count}) #{args}\n#{optparse}"
    return 1
  end

  begin
    params.merge!(parse_list_options(options))

    if args.count > 0
      job = find_by_name_or_id('job', args[0])

      if job.nil?
        print_red_alert "Job #{args[0]} not found"
        exit 1
      end
      params['jobId'] = job['id']
    end

    @jobs_interface.setopts(options)
    if options[:dry_run]
      print_dry_run @jobs_interface.dry.list_executions(params)
      return
    end
    json_response = @jobs_interface.list_executions(params)

    render_result = render_with_format(json_response, options, 'jobExecutions')
    return 0 if render_result

    title = "Morpheus Job Executions"
    subtitles = job ? ["Job: #{job['name']}"] : []
    subtitles += parse_list_subtitles(options)
    print_h1 title, subtitles

    print_job_executions(json_response['jobExecutions'], options)
    print_results_pagination(json_response)
    print reset,"\n"
    return 0
  rescue RestClient::Exception => e
    print_rest_exception(e, options)
    exit 1
  end
end

#remove(args) ⇒ Object



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
# File 'lib/morpheus/cli/jobs_command.rb', line 684

def remove(args)
  options = {}
  params = {}
  optparse = Morpheus::Cli::OptionParser.new do |opts|
    opts.banner = subcommand_usage( "[job]")
    build_common_options(opts, options, [:json, :dry_run, :remote])
    opts.footer = "Remove job.\n" +
        "[job] is required. Job ID or name"
  end
  optparse.parse!(args)
  connect(options)
  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

    unless options[:yes] || ::Morpheus::Cli::OptionTypes::confirm("Are you sure you would like to remove the job '#{job['name']}'?", options)
      return 9, "aborted command"
    end

    @jobs_interface.setopts(options)
    if options[:dry_run]
      print_dry_run @jobs_interface.dry.destroy(job['id'], params)
      return
    end

    json_response = @jobs_interface.destroy(job['id'], params)

    if options[:json]
      print JSON.pretty_generate(json_response)
      print "\n"
    elsif !options[:quiet]
      print_green_success "Job #{job['name']} removed"
    end
    return 0
  rescue RestClient::Exception => e
    print_rest_exception(e, options)
    exit 1
  end
end

#update(args) ⇒ Object



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
542
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
# File 'lib/morpheus/cli/jobs_command.rb', line 448

def update(args)
  options = {}
  params = {}
  optparse = Morpheus::Cli::OptionParser.new do |opts|
    opts.banner = subcommand_usage( "[job]")
    opts.on("--name NAME", String, "Updates job name") do |val|
      params['name'] = val.to_s
    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 code, assigns task to job. Incompatible with --workflow option.") do |val|
      if options[:workflow].nil?
        options[:task] = val
      else
        raise_command_error "Options --task and --workflow are incompatible"
      end
    end
    opts.on('-w', '--workflow [WORKFLOW]', String, "Workflow ID or code, assigns workflow to job. Incompatible with --task option.") do |val|
      if options[:task].nil?
        options[:workflow] = val
      else
        raise_command_error "Options --task and --workflow are incompatible"
      end
    end
    opts.on('--context-type [TYPE]', String, "Context type (instance|server|none). Default is none") do |val|
      params['targetType'] = (val == 'none' ? 'appliance' : val)
    end
    opts.on('--instances [LIST]', Array, "Context instances(s), comma separated list of instance IDs. Incompatible with --servers") do |list|
      params['targetType'] = 'instance'
      options[: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('--servers [LIST]', Array, "Context server(s), comma separated list of server IDs. Incompatible with --instances") do |list|
      params['targetType'] = 'server'
      options[: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('--schedule [SCHEDULE]', String, "Job execution schedule type name or ID") do |val|
      options[: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|
      options[:schedule] = 'dateTime'
      params['dateTime'] = val.to_s
    end
    build_common_options(opts, options, [:options, :payload, :list, :query, :json, :yaml, :csv, :fields, :dry_run, :remote])
    opts.footer = "Update job.\n" +
        "[job] is required. Job ID or name"
  end
  optparse.parse!(args)
  connect(options)
  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

    if options[:payload]
      payload = parse_payload(options, 'job')
    else
      apply_options(params, options)

      job_type_id = job['type']['id']

      if !options[:task].nil?
        task = find_by_name_or_id('task', options[:task])

        if task.nil?
          print_red_alert "Task #{options[:task]} not found"
          exit 1
        end
        params['task'] = {'id': task['id']}
        job_type_id = load_job_type_id_by_code('morpheus.task')
      end

      if !options[:workflow].nil?
        task_set = find_by_name_or_id('task_set', options[:workflow])

        if task_set.nil?
          print_red_alert "Workflow #{options[: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 !options[:targets].nil? && ['instance', 'server'].include?(params['targetType'])
        params['targets'] = []
        target_type = params['targetType'] || job['targetType']
        options[: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 !options[:schedule].nil?
        if options[:schedule] != 'manual' && options[:schedule].to_s.downcase != 'datetime'
          job_options = @jobs_interface.options(job_type_id)
          schedule = job_options['schedules'].find {|it| it['name'] == options[:schedule] || it['value'] == options[:schedule].to_i}

          if schedule.nil?
            print_red_alert "Schedule #{options[:schedule]} not found"
            exit 1
          end
          options[:schedule] = schedule['value']
        end
        params['scheduleMode'] = options[:schedule]
      end


      # schedule
      if !options[:schedule].nil?
        

        if options[:schedule] == 'manual'
          # cool
        elsif options[:schedule].to_s.downcase == 'datetime'
          # prompt for dateTime
          if params['dateTime'].nil?
            raise_command_error "--date-time is required for schedule '#{options[:schedule]}'\n#{optparse}"
          end
        elsif options[:schedule].to_s != ''
          job_options = @jobs_interface.options(job_type_id)
          options[:schedule] = Morpheus::Cli::OptionTypes.prompt([{'fieldName' => 'schedule', 'fieldLabel' => "Schedule", 'type' => 'select', 'required' => true, 'selectOptions' => job_options['schedules'], 'defaultValue' => job_options['schedules'].first['name']}], options[:options], @api_client, {})['schedule']
          params['scheduleMode'] = options[:schedule]
           # ok they passed a schedule name or id
          schedule = job_options['schedules'].find {|it| it['name'] == options[:schedule] || it['value'] == options[:schedule].to_i}

          if schedule.nil?
            print_red_alert "Schedule #{options[:schedule]} not found"
            exit 1
          end
          options[: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(options)
    if options[:dry_run]
      print_dry_run @jobs_interface.dry.update(job['id'], payload)
      return
    end
    json_response = @jobs_interface.update(job['id'], payload)

    if options[:json]
      puts as_json(json_response, options)
    elsif !options[:quiet]
      if json_response['success']
        print_green_success  "Job updated"
        _get(job['id'], nil, options)
      else
        print_red_alert "Error updating job: #{json_response['msg'] || json_response['errors']}"
      end
    end
    return 0
  rescue RestClient::Exception => e
    print_rest_exception(e, options)
    exit 1
  end
end