Class: Morpheus::Cli::Workflows

Inherits:
Object
  • Object
show all
Includes:
CliCommand, JobsHelper
Defined in:
lib/morpheus/cli/commands/workflows.rb

Instance Attribute Summary

Attributes included from CliCommand

#no_prompt

Instance Method Summary collapse

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(id, options) ⇒ Object



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
# File 'lib/morpheus/cli/commands/workflows.rb', line 312

def _get(id, options)
  workflow_name = id
  begin
    @task_sets_interface.setopts(options)
    if options[:dry_run]
      if workflow_name.to_s =~ /\A\d{1,}\Z/
        print_dry_run @task_sets_interface.dry.get(workflow_name.to_i)
      else
        print_dry_run @task_sets_interface.dry.get({name: workflow_name})
      end
      return
    end
    workflow = find_workflow_by_name_or_id(workflow_name)
    exit 1 if workflow.nil?
    # refetch it..
    json_response = {'taskSet' => workflow}
    unless workflow_name.to_s =~ /\A\d{1,}\Z/
      json_response = @task_sets_interface.get(workflow['id'])
    end
    workflow = json_response['taskSet']
    if options[:json]
      puts as_json(json_response, options, "taskSet")
      return 0
    elsif options[:yaml]
      puts as_yaml(json_response, options, "taskSet")
      return 0
    elsif options[:csv]
      puts records_as_csv([json_response['taskSet']], options)
      return 0
    else
      # tasks = []
      # (workflow['tasks'] || []).each do |task_name|
      #   tasks << find_task_by_name_or_id(task_name)['id']
      # end
      tasks = workflow['taskSetTasks'].sort { |x,y| x['taskOrder'].to_i <=> y['taskOrder'].to_i }
      print_h1 "Workflow Details"

      print cyan
      description_cols = {
        "ID" => 'id',
        "Name" => 'name',
        "Labels" => lambda {|it| format_list(it['labels'], '', 3) rescue '' },
        "Description" => 'description',
        "Type" => lambda {|workflow| format_workflow_type(workflow) },
        "Platform" => lambda {|it| format_platform(it['platform']) },
        "Allow Custom Config" => lambda {|it| format_boolean(it['allowCustomConfig']) },
        "Visibility" => lambda {|it| it['visibility'].to_s.capitalize },
        "Created" => lambda {|it| format_local_dt(it['dateCreated']) },
        "Updated" => lambda {|it| format_local_dt(it['lastUpdated']) }
      }
      print_description_list(description_cols, workflow)

      #task_names = tasks.collect {|it| it['name'] }
      print_h2 "Workflow Tasks"
      if tasks.empty?
        print cyan,"No tasks in this workflow.",reset,"\n"
      else
        print cyan
        # tasks.each_with_index do |taskSetTask, index|
        #   puts "#{(index+1).to_s.rjust(3, ' ')}. #{taskSetTask['task']['name']}"
        # end
        task_set_task_columns = [
          #{"ID" => lambda {|it| it['id'] } }, 
          {"TASK ID" => lambda {|it| it['task']['id'] } },
          {"NAME" => lambda {|it| it['task']['name'] } },
          {"TYPE" => lambda {|it| it['task']['taskType'] ? it['task']['taskType']['name'] : '' } },
          {"PHASE" => lambda {|it| it['taskPhase'] } }, # not returned yet?
        ]
        print cyan
        print as_pretty_table(tasks, task_set_task_columns)
      end

      workflow_option_types = workflow['optionTypes']

      if workflow_option_types && workflow_option_types.size() > 0
        print_h2 "Workflow Option Types"
        columns = [
          {"ID" => lambda {|it| it['id'] } },
          {"NAME" => lambda {|it| it['name'] } },
          {"TYPE" => lambda {|it| it['type'] } },
          {"FIELD NAME" => lambda {|it| it['fieldName'] } },
          {"FIELD LABEL" => lambda {|it| it['fieldLabel'] } },
          {"DEFAULT" => lambda {|it| it['defaultValue'] } },
          {"REQUIRED" => lambda {|it| format_boolean it['required'] } },
        ]
        print as_pretty_table(workflow_option_types, columns)
      end
      print reset
      print "\n"
    end
  rescue RestClient::Exception => e
    print_rest_exception(e, options)
    exit 1
  end
end

#add(args) ⇒ Object



89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
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
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
# File 'lib/morpheus/cli/commands/workflows.rb', line 89

def add(args)
  options = {}
  params = {}
  tasks = nil
  task_arg_list = nil
  option_types = nil
  option_type_arg_list = nil
  workflow_type = nil # 'provision'
  optparse = Morpheus::Cli::OptionParser.new do |opts|
    opts.banner = subcommand_usage("[name] --tasks taskId:phase,taskId2:phase,taskId3:phase")
    opts.on("--name NAME", String, "Name for workflow") do |val|
      params['name'] = val
    end
    opts.on('-l', '--labels [LIST]', String, "Labels") do |val|
      options[:options]['labels'] = parse_labels(val)
    end
    opts.on("--description DESCRIPTION", String, "Description of workflow") do |val|
      params['description'] = val
    end
    opts.on("-t", "--type TYPE", "Type of workflow. i.e. provision or operation. Default is provision.") do |val|
      workflow_type = val.to_s.downcase
      if workflow_type.include?('provision')
        workflow_type = 'provision'
      elsif workflow_type.include?('operation')
        workflow_type = 'operation'
      end
      params['type'] = workflow_type
    end
    opts.on("--operational", "--operational", "Create an operational workflow, alias for --type operational.") do |val|
      workflow_type = 'operation'
      params['type'] = workflow_type
    end
    opts.on("--tasks [x,y,z]", Array, "List of tasks to run in order, in the format <Task ID>:<Task Phase> Task Phase is optional. Default is the same workflow type: 'provision' or 'operation'.") do |list|
      task_arg_list = []
      list.each do |it|
        task_id, task_phase = it.split(":")
        task_arg_list << {task_id: task_id.to_s.strip, task_phase: task_phase.to_s.strip}
      end if list
    end
    opts.on("--option-types x,y,z", Array, "List of option type name or IDs. For use with operational workflows to add configuration during execution.") do |list|
      option_type_arg_list = []
      list.each do |it|
        option_type_arg_list << {option_type_id: it.to_s.strip}
      end
    end
    opts.on('--platform [PLATFORM]', String, "Platform, eg. linux, windows or osx") do |val|
      params['platform'] = val.to_s.empty? ? nil : val.to_s.downcase
    end
    opts.on('--allow-custom-config [on|off]', String, "Allow Custom Config") do |val|
      params['allowCustomConfig'] = val.to_s == 'on' || val.to_s == 'true' || val.to_s == ''
    end
    opts.on('--visibility VISIBILITY', String, "Visibility, eg. private or public") do |val|
      params['visibility'] = val.to_s.downcase
    end
    build_common_options(opts, options, [:options, :payload, :json, :dry_run, :quiet, :remote])
  end
  optparse.parse!(args)
  if args.count > 1
    raise_command_error "wrong number of arguments, expected 0-1 and got (#{args.count}) #{args.join(' ')}\n#{optparse}"
  end
  connect(options)
  begin
    passed_options = options[:options] ? options[:options].reject {|k,v| k.is_a?(Symbol) } : {}
    payload = nil
    if options[:payload]
      payload = options[:payload]
      payload.deep_merge!({'taskSet' => passed_options})  unless passed_options.empty?
    else
      params.deep_merge!(passed_options)  unless passed_options.empty?
      if args[0]
        params['name'] = args[0]
      end
      # if params['name'].to_s.empty?
      #   puts_error "#{Morpheus::Terminal.angry_prompt}missing required option: [name]\n#{optparse}"
      #   return 1
      # end
      # if task_arg_list.nil?
      #   puts_error "#{Morpheus::Terminal.angry_prompt}missing required option: --tasks\n#{optparse}"
      #   return 1
      # end
      
      # Name
      if params['name'].nil?
        v_prompt = Morpheus::Cli::OptionTypes.prompt([{'fieldName' => 'name', 'fieldLabel' => 'Name', 'type' => 'text', 'required' => true, 'description' => 'Name'}], options[:options], @api_client)
        params['name'] = v_prompt['name'] unless v_prompt['name'].to_s.empty?
      end

      # Description
      if params['description'].nil?
        v_prompt = Morpheus::Cli::OptionTypes.prompt([{'fieldName' => 'description', 'fieldLabel' => 'Description', 'type' => 'text', 'description' => 'Description'}], options[:options], @api_client)
        params['description'] = v_prompt['description'] unless v_prompt['description'].to_s.empty?
      end
      
      # Type
      if workflow_type.nil?
        v_prompt = Morpheus::Cli::OptionTypes.prompt([{'fieldName' => 'type', 'fieldLabel' => 'Type', 'type' => 'select', 'selectOptions' => get_available_workflow_types(), 'required' => true, 'description' => 'Workflow Type', 'defaultValue' => workflow_type || 'provision'}], options[:options], @api_client)
        workflow_type = v_prompt['type'] unless v_prompt['type'].to_s.empty?
        params['type'] = workflow_type
      end

      # Tasks
      while tasks.nil? do
        if task_arg_list.nil?
          tasks_val = nil
          v_prompt = Morpheus::Cli::OptionTypes.prompt([{'fieldName' => 'tasks', 'fieldLabel' => 'Tasks', 'type' => 'text', 'required' => false, 'description' => "List of tasks to run in order, in the format <Task ID>:<Task Phase> Task Phase is optional. Default is the same workflow type: 'provision' or 'operation'."}], options[:options], @api_client)
          tasks_val = v_prompt['tasks'] unless v_prompt['tasks'].to_s.empty?
          if tasks_val
            task_arg_list = []
            tasks_val.split(",").each do |it|
              task_id, task_phase = it.split(":")
              task_arg_list << {task_id: task_id.to_s.strip, task_phase: task_phase.to_s.strip}
            end
          else
            # empty array is allowed
            tasks = []
          end
        end
        if task_arg_list
          tasks = []
          task_arg_list.each do |task_arg|
            found_task = find_task_by_name_or_id(task_arg[:task_id])
            #return 1 if found_task.nil?
            if found_task.nil?
              task_arg_list = nil
              tasks = nil
              break
            end
            row = {'taskId' => found_task['id']}
            if !task_arg[:task_phase].to_s.strip.empty?
              row['taskPhase'] = task_arg[:task_phase]
            elsif workflow_type == 'operation'
              row['taskPhase'] = 'operation'
            end
            tasks << row
          end
        else
          if options[:no_prompt]
            # empty array is allowed
            tasks = []
          end
        end
      end

      # Option Types
      if workflow_type == 'operation'
        while option_types.nil? do
          if option_type_arg_list.nil?
            option_types_val = nil
            v_prompt = Morpheus::Cli::OptionTypes.prompt([{'fieldName' => 'optionTypes', 'fieldLabel' => 'Option Types', 'type' => 'text', 'description' => "List of option type name or IDs. For use with operational workflows to add configuration during execution."}], options[:options], @api_client)
            option_types_val = v_prompt['optionTypes'] unless v_prompt['optionTypes'].to_s.empty?
            if option_types_val
              option_type_arg_list = []
              option_types_val.split(",").each do |it|
                option_type_arg_list << {option_type_id: it.to_s.strip}
              end
            else
              option_types = [] # not required, break out
            end
          end
          if option_type_arg_list
            option_types = []
            option_type_arg_list.each do |option_type_arg|
              found_option_type = find_option_type_by_name_or_id(option_type_arg[:option_type_id])
              #return 1 if found_option_type.nil?
              if found_option_type.nil?
                option_type_arg_list = nil
                option_types = nil
                break
              end
              option_types << found_option_type['id']
            end
          end
        end
      end

      payload = {'taskSet' => {}}
      params.deep_merge!(options[:options].reject {|k,v| k.is_a?(Symbol) }) if options[:options]
      # params['type'] = workflow_type
      payload['taskSet'].deep_merge!(params)
      if tasks
        payload['taskSet']['tasks'] = tasks
      end
      if option_types && option_types.size > 0
        payload['taskSet']['optionTypes'] = option_types
      end
    end
    @task_sets_interface.setopts(options)
    if options[:dry_run]
      print_dry_run @task_sets_interface.dry.create(payload)
      return
    end
    json_response = @task_sets_interface.create(payload)
    if options[:json]
      print JSON.pretty_generate(json_response)
    else
      workflow = json_response['taskSet']
      print_green_success "Workflow #{workflow['name']} created"
      get([workflow['id']])
    end
  rescue RestClient::Exception => e
    print_rest_exception(e, options)
    exit 1
  end
end

#connect(opts) ⇒ Object

def initialize()

@appliance_name, @appliance_url = Morpheus::Cli::Remote.active_appliance

end



14
15
16
17
18
19
20
21
# File 'lib/morpheus/cli/commands/workflows.rb', line 14

def connect(opts)
  @api_client = establish_remote_appliance_connection(opts)
  @task_sets_interface = @api_client.task_sets
  @tasks_interface = @api_client.tasks
  @option_types_interface = @api_client.option_types
  @instances_interface = @api_client.instances
  @servers_interface = @api_client.servers
end

#execute(args) ⇒ Object



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
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
# File 'lib/morpheus/cli/commands/workflows.rb', line 547

def execute(args)
  params = {}
  options = {}
  target_type = nil
  instance_ids = []
  instances = []
  instance_label = nil
  server_ids = []
  servers = []
  server_label = nil
  default_refresh_interval = 5
  all_target_types = ['appliance', 'instance', 'instance-label', 'server', 'server-label']
  optparse = Morpheus::Cli::OptionParser.new do |opts|
    opts.banner = subcommand_usage("[workflow] [options]")
    opts.on('--context-type VALUE', String, "Context Type, #{ored_list(all_target_types)}") do |val|
      val = val.downcase
      val = 'appliance' if val == 'none'
      if target_type && target_type != val
        raise ::OptionParser::InvalidOption.new("cannot be combined with another context (#{target_type})")
      end
      if !all_target_types.include?(val)
        raise ::OptionParser::InvalidOption.new("'#{val}' is invalid. It must be one of the following: instance, instance-label, server, server-label or appliance")
      end
      target_type = val
    end
    opts.on('--target-type VALUE', String, "alias for context-type") do |val|
      val = val.downcase
      val = 'appliance' if val == 'none'
      if target_type && target_type != val
        raise ::OptionParser::InvalidOption.new("cannot be combined with another context (#{target_type})")
      end
      if !all_target_types.include?(val)
        raise ::OptionParser::InvalidOption.new("'#{val}' is invalid. It must be one of the following: instance, instance-label, server, server-label or appliance")
      end
      target_type = val
    end
    opts.add_hidden_option('--target-type')
    opts.on('--instance INSTANCE', String, "Instance name or id to target for execution. This option can be passed more than once.") do |val|
      if target_type && target_type != 'instance'
        raise ::OptionParser::InvalidOption.new("cannot be combined with another context (#{target_type})")
      end
      target_type = 'instance'
      instance_ids << val
    end
    opts.on('--instances LIST', Array, "Instances, comma separated list of instance names or IDs.") do |list|
      if target_type && target_type != 'instance'
        raise ::OptionParser::InvalidOption.new("cannot be combined with another context (#{target_type})")
      end
      target_type = 'instance'
      instance_ids = list.collect {|it| it.to_s.strip.empty? ? nil : it.to_s.strip }.compact.uniq
    end
    opts.on('--instance-label LABEL', String, "Instance Label") do |val|
      if target_type && target_type != 'instance-label'
        raise ::OptionParser::InvalidOption.new("cannot be combined with another context (#{target_type})")
      end
      target_type = 'instance-label'
      instance_label = val
    end
    opts.on('--server SERVER', String, "Server name or id to target for execution. This option can be passed more than once.") do |val|
      if target_type && target_type != 'server'
        raise ::OptionParser::InvalidOption.new("cannot be combined with another context (#{target_type})")
      end
      target_type = 'server'
      server_ids << val
    end
    opts.on('--servers LIST', Array, "Servers, comma separated list of host names or IDs.") do |list|
      if target_type && target_type != 'server'
        raise ::OptionParser::InvalidOption.new("cannot be combined with another context (#{target_type})")
      end
      target_type = 'server'
      server_ids = list.collect {|it| it.to_s.strip.empty? ? nil : it.to_s.strip }.compact.uniq
    end
    opts.on('--server-label LABEL', String, "Server Label") do |val|
      if target_type && target_type != 'server-label'
        raise ::OptionParser::InvalidOption.new("cannot be combined with another context (#{target_type})")
      end
      target_type = 'server-label'
      server_label = val
    end
    opts.on('--host HOST', String, "alias for --server") do |val|
      if target_type && target_type != 'server'
        raise ::OptionParser::InvalidOption.new("cannot be combined with another context (#{target_type})")
      end
      target_type = 'server'
      server_ids << val
    end
    opts.add_hidden_option('--host')
    opts.on('--hosts HOSTS', Array, "alias for --servers") do |list|
      if target_type && target_type != 'server'
        raise ::OptionParser::InvalidOption.new("The --hosts option cannot be combined with another context (#{target_type})")
      end
      target_type = 'server'
      server_ids = list.collect {|it| it.to_s.strip.empty? ? nil : it.to_s.strip }.compact.uniq
    end
    opts.add_hidden_option('--hosts')
    opts.on('-a', '--appliance', "Execute on the appliance, the target is the appliance itself.") do
      if target_type && target_type != 'appliance'
        raise ::OptionParser::InvalidOption.new("The --appliance option cannot be combined with another context (#{target_type})")
      end
      target_type = 'appliance'
    end
    opts.on('--config [TEXT]', String, "Custom config") do |val|
      params['customConfig'] = val.to_s
    end
    opts.on('--refresh [SECONDS]', String, "Refresh until execution is complete. Default interval is #{default_refresh_interval} seconds.") do |val|
      options[:refresh_interval] = val.to_s.empty? ? default_refresh_interval : val.to_f
    end
    opts.on(nil, '--no-refresh', "Do not refresh" ) do
      options[:no_refresh] = true
    end
    build_standard_post_options(opts, options)
  end
  optparse.parse!(args)
  if args.count != 1
    raise_command_error "wrong number of arguments, expected 1 and got (#{args.count}) #{args.join(' ')}\n#{optparse}"
  end
  workflow_name = args[0]
  connect(options)
  
    workflow = find_workflow_by_name_or_id(workflow_name)
    return 1 if workflow.nil?

    passed_options = options[:options] ? options[:options].reject {|k,v| k.is_a?(Symbol) } : {}
    payload = nil
    if options[:payload]
      payload = options[:payload]
      payload.deep_merge!({'job' => passed_options})  unless passed_options.empty?
    else
      # prompt for target type and target
      if target_type.nil?
        # todo: Need api to fetch available Context Types for taskId/workflowId
        available_target_types = get_available_contexts_for_workflow(workflow)
        default_target_type = available_target_types.first ? available_target_types.first['name'] : nil
        if !available_target_types.empty?
          default_target_type = available_target_types.first ? available_target_types.first['name'] : nil
          target_type = Morpheus::Cli::OptionTypes.prompt([{'switch' => 'context-type', 'fieldName' => 'targetType', 'fieldLabel' => 'Context Type', 'type' => 'select', 'selectOptions' => available_target_types, 'defaultValue' => default_target_type, 'required' => true, 'description' => 'Context Type determines the type of target(s) for the execution'}], options[:options], @api_client)['targetType']
        end
      end
      if target_type
        params['targetType'] = target_type
      end
      if target_type == 'instance'
        if instance_ids.empty?
          instance_ids_value = Morpheus::Cli::OptionTypes.prompt([{'switch' => 'instances', 'fieldName' => 'instances', 'fieldLabel' => 'Instance(s)', 'type' => 'text', 'required' => true, 'description' => 'Instances, comma separated list of instance names or IDs.'}], options[:options], @api_client)['instances']
          instance_ids = parse_array(instance_ids_value)
        end
        instance_ids.each do |instance_id|
          instance = find_instance_by_name_or_id(instance_id)
          return 1 if instance.nil?
          instances << instance
        end
        params['instances'] = instances.collect {|it| it['id'] }
      elsif target_type == 'instance-label'
        if instance_label.nil?
          instance_label = Morpheus::Cli::OptionTypes.prompt([{'switch' => 'instance-label', 'fieldName' => 'instanceLabel', 'fieldLabel' => 'Instance Label', 'type' => 'text', 'required' => true, 'description' => 'Instance Label'}], options[:options], @api_client)['instanceLabel']
        end
        # params['config'] ||= {}
        # params['config']['instanceLabel'] = instance_label
        params['instanceLabel'] = instance_label
      elsif target_type == 'server'
        if server_ids.empty?
          server_ids_value = Morpheus::Cli::OptionTypes.prompt([{'switch' => 'servers', 'fieldName' => 'servers', 'fieldLabel' => 'Server(s)', 'type' => 'text', 'required' => true, 'description' => 'Servers, comma separated list of server names or IDs.'}], options[:options], @api_client)['servers']
          server_ids = parse_array(server_ids_value)
        end
        server_ids.each do |server_id|
          server = find_server_by_name_or_id(server_id)
          return 1 if server.nil?
          servers << server
        end
        params['servers'] = servers.collect {|it| it['id'] }
      elsif target_type == 'server-label'
        if server_label.nil?
          server_label = Morpheus::Cli::OptionTypes.prompt([{'switch' => 'server-label', 'fieldName' => 'serverLabel', 'fieldLabel' => 'Server Label', 'type' => 'text', 'required' => true, 'description' => 'Server Label'}], options[:options], @api_client)['serverLabel']
        end
        # params['config'] ||= {}
        # params['config']['serverLabel'] = server_label
        params['serverLabel'] = server_label
      end

      # prompt to workflow optionTypes for customOptions
      custom_options = nil
      if workflow['optionTypes'] && workflow['optionTypes'].size() > 0
        custom_option_types = workflow['optionTypes'].collect {|it|
          it['fieldContext'] = 'customOptions'
          it
        }
        custom_options = Morpheus::Cli::OptionTypes.prompt(custom_option_types, options[:options], @api_client, {})
      end
      job_payload = {}
      job_payload.deep_merge!(params)
      passed_options.delete('customOptions')
      job_payload.deep_merge!(passed_options) unless passed_options.empty?
      if custom_options
        # job_payload.deep_merge!('config' => custom_options)
        job_payload.deep_merge!(custom_options)
      end
      payload = {'job' => job_payload}
    end

    @task_sets_interface.setopts(options)
    if options[:dry_run]
      print_dry_run @task_sets_interface.dry.run(workflow['id'], payload)
      return 0
    end
    json_response = @task_sets_interface.run(workflow['id'], payload)

    render_response(json_response, options) do
      target_desc = nil
      if instances.size() > 0
        target_desc = (instances.size() == 1) ? "instance #{instances[0]['name']}" : "#{instances.size()} instances"
      elsif servers.size() > 0
        target_desc = (servers.size() == 1) ? "host #{servers[0]['name']}" : "#{servers.size()} hosts"
      end
      if target_desc
        print_green_success "Executing workflow #{workflow['name']} on #{target_desc}"
      else
        print_green_success "Executing workflow #{workflow['name']}"
      end
      if json_response["jobExecution"] && json_response["jobExecution"]["id"]
        job_execution_id = json_response["jobExecution"]["id"]
        if options[:no_refresh]
          get_args = [json_response["jobExecution"]["id"], "--details"] + (options[:remote] ? ["-r",options[:remote]] : [])
          Morpheus::Logging::DarkPrinter.puts((['jobs', 'get-execution'] + get_args).join(' ')) if Morpheus::Logging.debug?
          ::Morpheus::Cli::JobsCommand.new.handle(['get-execution'] + get_args)
        else
          #Morpheus::Cli::JobsCommand.new.handle(["get-execution", job_execution_id, "--refresh", options[:refresh_interval].to_s]+ (options[:remote] ? ["-r",options[:remote]] : []))
          job_execution_results = wait_for_job_execution(job_execution_id, options.merge({:details => true}))
        end
      end
    end
    return 0, nil
end

#get(args) ⇒ Object



294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
# File 'lib/morpheus/cli/commands/workflows.rb', line 294

def get(args)
  options = {}
  optparse = Morpheus::Cli::OptionParser.new do |opts|
    opts.banner = subcommand_usage("[workflow]")
    build_common_options(opts, options, [:json, :yaml, :csv, :fields, :dry_run, :remote])
  end
  optparse.parse!(args)
  if args.count < 1
    puts optparse
    return 1
  end
  connect(options)
  id_list = parse_id_list(args)
  return run_command_for_each_arg(id_list) do |arg|
    _get(arg, options)
  end
end

#handle(args) ⇒ Object



24
25
26
# File 'lib/morpheus/cli/commands/workflows.rb', line 24

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

def list(args)
  params = {}
  options = {}
  optparse = Morpheus::Cli::OptionParser.new do |opts|
    opts.banner = subcommand_usage("[search]")
    opts.on("-t", "--type TYPE", "Type of workflow. i.e. provision or operation. Default is provision.") do |val|
      workflow_type = val.to_s.downcase
      if workflow_type.include?('provision')
        workflow_type = 'provision'
      elsif workflow_type.include?('operation')
        workflow_type = 'operation'
      end
      params['type'] = workflow_type
    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
    build_standard_list_options(opts, options)
    opts.footer = "List workflows."
  end
  optparse.parse!(args)
  connect(options)
  if args.count > 0
    options[:phrase] = args.join(" ")
  end
  params.merge!(parse_list_options(options))
  @task_sets_interface.setopts(options)
  if options[:dry_run]
    print_dry_run @task_sets_interface.dry.get(params)
    return
  end
  json_response = @task_sets_interface.get(params)
  task_sets = json_response['taskSets']
  render_response(json_response, options, 'taskSets') do
    title = "Morpheus Workflows"
    subtitles = []
    subtitles += parse_list_subtitles(options)
    if params['type']
      subtitles << "Type: #{params['type']}"
    end
    print_h1 title, subtitles
    if task_sets.empty?
      print cyan,"No workflows found.",reset,"\n"
    else
      print cyan
      print_workflows_table(task_sets)
      print_results_pagination(json_response)
    end
    print reset,"\n"
  end
  if task_sets.empty?
    return 1, "no workflows found"
  else
    return 0, nil
  end
end

#remove(args) ⇒ Object



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
# File 'lib/morpheus/cli/commands/workflows.rb', line 511

def remove(args)
  options = {}
  optparse = Morpheus::Cli::OptionParser.new do |opts|
    opts.banner = "Usage: morpheus workflows remove [name]"
    build_common_options(opts, options, [:auto_confirm, :json, :dry_run, :quiet, :remote])
  end
  optparse.parse!(args)
  if args.count < 1
    puts optparse
    exit 1
  end
  workflow_name = args[0]
  connect(options)
  begin
    workflow = find_workflow_by_name_or_id(workflow_name)
    exit 1 if workflow.nil?
    unless options[:yes] || Morpheus::Cli::OptionTypes.confirm("Are you sure you want to delete the workflow #{workflow['name']}?")
      exit 1
    end
    @task_sets_interface.setopts(options)
    if options[:dry_run]
      print_dry_run @task_sets_interface.dry.destroy(workflow['id'])
      return
    end
    json_response = @task_sets_interface.destroy(workflow['id'])
    if options[:json]
      print JSON.pretty_generate(json_response)
    elsif !options[:quiet]
      print_green_success "Workflow #{workflow['name']} removed"
    end
  rescue RestClient::Exception => e
    print_rest_exception(e, options)
    exit 1
  end
end

#update(args) ⇒ Object



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
# File 'lib/morpheus/cli/commands/workflows.rb', line 408

def update(args)
  options = {}
  params = {}
  tasks = nil
  task_arg_list = nil
  option_types = nil
  option_type_arg_list = nil
  optparse = Morpheus::Cli::OptionParser.new do |opts|
    opts.banner = subcommand_usage("[name] --tasks taskId:phase,taskId2:phase,taskId3:phase")
    opts.on("--name NAME", String, "New name for workflow") do |val|
      params['name'] = val
    end
    opts.on('-l', '--labels [LIST]', String, "Labels") do |val|
      options[:options]['labels'] = parse_labels(val)
    end
    opts.on("--description DESCRIPTION", String, "Description of workflow") do |val|
      params['description'] = val
    end
    opts.on("--tasks [x,y,z]", Array, "List of tasks to run in order, in the format <Task ID>:<Task Phase> Task Phase is optional. Default is the same workflow type: 'provision' or 'operation'.") do |list|
      task_arg_list = []
      list.each do |it|
        task_id, task_phase = it.split(":")
        task_arg_list << {task_id: task_id.to_s.strip, task_phase: task_phase.to_s.strip}
      end if list
    end
    opts.on("--option-types [x,y,z]", Array, "List of option type name or IDs. For use with operational workflows to add configuration during execution.") do |list|
      option_type_arg_list = []
      list.each do |it|
        option_type_arg_list << {option_type_id: it.to_s.strip}
      end if list
    end
    opts.on('--platform [PLATFORM]', String, "Platform, eg. linux, windows or osx") do |val|
      params['platform'] = val.to_s.empty? ? nil : val.to_s.downcase
    end
    opts.on('--allow-custom-config [on|off]', String, "Allow Custom Config") do |val|
      params['allowCustomConfig'] = val.to_s == 'on' || val.to_s == 'true' || val.to_s == ''
    end
    opts.on('--visibility VISIBILITY', String, "Visibility, eg. private or public") do |val|
      params['visibility'] = val.to_s.downcase
    end
    build_common_options(opts, options, [:options, :payload, :json, :dry_run, :quiet, :remote])
  end
  optparse.parse!(args)
  if args.count != 1
    raise_command_error "wrong number of arguments, expected 1 and got (#{args.count}) #{args.join(' ')}\n#{optparse}"
  end
  workflow_name = args[0]
  connect(options)
  begin
    workflow = find_workflow_by_name_or_id(workflow_name)
    return 1 if workflow.nil?
    payload = nil
    if options[:payload]
      payload = options[:payload]
    else
      if task_arg_list
        tasks = []
        task_arg_list.each do |task_arg|
          found_task = find_task_by_name_or_id(task_arg[:task_id])
          return 1 if found_task.nil?
          row = {'taskId' => found_task['id']}
          if !task_arg[:task_phase].to_s.strip.empty?
            row['taskPhase'] = task_arg[:task_phase]
          end
          tasks << row
        end
      end
      if option_type_arg_list
        option_types = []
        option_type_arg_list.each do |option_type_arg|
          found_option_type = find_option_type_by_name_or_id(option_type_arg[:option_type_id])
          return 1 if found_option_type.nil?
          option_types << found_option_type['id']
        end
      end
      payload = {'taskSet' => {}}
      params.deep_merge!(options[:options].reject {|k,v| k.is_a?(Symbol) }) if options[:options]
      payload['taskSet'].deep_merge!(params)
      if tasks
        payload['taskSet']['tasks'] = tasks
      end
      if option_types
        payload['taskSet']['optionTypes'] = option_types
      end
    end
    @task_sets_interface.setopts(options)
    if options[:dry_run]
      print_dry_run @task_sets_interface.dry.update(workflow['id'], payload)
      return
    end
    json_response = @task_sets_interface.update(workflow['id'], payload)
    if options[:json]
      print JSON.pretty_generate(json_response)
    elsif !options[:quiet]
      print_green_success "Workflow #{json_response['taskSet']['name']} updated"
      get([workflow['id']])
    end
  rescue RestClient::Exception => e
    print_rest_exception(e, options)
    exit 1
  end
end