Class: Morpheus::Cli::Instances

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

Instance Method Summary collapse

Methods included from ProvisioningHelper

included, #prompt_instance_volumes, #prompt_resize_instance_volumes

Methods included from CliCommand

#build_common_options, included

Constructor Details

#initialize ⇒ Instances

Returns a new instance of Instances.



13
14
15
16
# File 'lib/morpheus/cli/instances.rb', line 13

def initialize() 
  @appliance_name, @appliance_url = Morpheus::Cli::Remote.active_appliance
  
end

Instance Method Details

#add(args) ⇒ Object



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

def add(args)
  options = {}
  optparse = OptionParser.new do|opts|
    opts.banner = "Usage: morpheus instances add TYPE NAME"
    opts.on( '-g', '--group GROUP', "Group" ) do |val|
      options[:group] = val
    end
    opts.on( '-c', '--cloud CLOUD', "Cloud" ) do |val|
      options[:cloud] = val
    end
    build_common_options(opts, options, [:options, :json, :remote])
    
  end

  if args.count < 2
    puts "\n#{optparse}\n\n"
    return
  end
  optparse.parse(args)
  connect(options)
  instance_name = args[1]
  instance_type_code = args[0]
  instance_type = find_instance_type_by_code(instance_type_code)
  if instance_type.nil?
    exit 1
  end
  groupId = nil
  if !options[:group].nil?
    group = find_group_by_name(options[:group])
    if !group.nil?
      groupId = group
    end
  else
    groupId = @active_groups[@appliance_name.to_sym]  
  end

  if groupId.nil?
    puts "Group not found or specified! \n #{optparse}"
    exit 1
  end

  if options[:cloud].nil?
    puts "Cloud not specified! \n #{optparse}"
    exit 1
  end
  cloud = find_cloud_by_name(groupId,options[:cloud])
  if cloud.nil?
    puts "Cloud not found! \n #{optparse}"
    exit 1
  end

  payload = {
    :servicePlan => nil,
    zoneId: cloud,
    :instance => {
      :name => instance_name,
      :site => {
        :id => groupId
      },
      :instanceType => {
        :code => instance_type_code
      }
    }
  }

  version_prompt = Morpheus::Cli::OptionTypes.prompt([{'fieldName' => 'version', 'type' => 'select', 'fieldLabel' => 'Version', 'optionSource' => 'instanceVersions', 'required' => true, 'skipSingleOption' => true, 'description' => 'Select which version of the instance type to be provisioned.'}],options[:options],@api_client,{groupId: groupId, cloudId: cloud, instanceTypeId: instance_type['id']})
  layout_prompt = Morpheus::Cli::OptionTypes.prompt([{'fieldName' => 'layout', 'type' => 'select', 'fieldLabel' => 'Layout', 'optionSource' => 'layoutsForCloud', 'required' => true, 'description' => 'Select which configuration of the instance type to be provisioned.'}],options[:options],@api_client,{groupId: groupId, cloudId: cloud, instanceTypeId: instance_type['id'], version: version_prompt['version']})
  layout_id = layout_prompt['layout']
  plan_prompt = Morpheus::Cli::OptionTypes.prompt([{'fieldName' => 'servicePlan', 'type' => 'select', 'fieldLabel' => 'Plan', 'optionSource' => 'instanceServicePlans', 'required' => true, 'description' => 'Choose the appropriately sized plan for this instance'}],options[:options],@api_client,{groupId: groupId, zoneId: cloud, instanceTypeId: instance_type['id'], layoutId: layout_id, version: version_prompt['version']})
  payload[:servicePlan] = plan_prompt['servicePlan']

  layout = instance_type['instanceTypeLayouts'].find{ |lt| lt['id'].to_i == layout_id.to_i}
  instance_type['instanceTypeLayouts'].sort! { |x,y| y['sortOrder'] <=> x['sortOrder'] }
  
  payload[:instance][:layout] = {id: layout['id']}

  
  begin
    service_plan_options_json = @instance_types_interface.service_plan_options(plan_prompt['servicePlan'], {cloudId: cloud, zoneId: cloud, layoutId: layout_id})
    
    # puts ""
    # print JSON.pretty_generate(service_plan_options_json)
    
    plan_options = service_plan_options_json['plan']
    volumes = prompt_instance_volumes(plan_options, options, @api_client, {})

    # puts "VOLUMES:"
    # print JSON.pretty_generate(volumes)

    if !volumes.empty?
      payload[:volumes] = volumes
    end

    # puts "\nexiting early...\n"
    # exit 1

  rescue RestClient::Exception => e
    print_red_alert "Unable to load options for selected plan."
    print_rest_exception(e, options)
    exit 1
  end

  type_payload = {}
  if !layout['optionTypes'].nil? && !layout['optionTypes'].empty?
    type_payload = Morpheus::Cli::OptionTypes.prompt(layout['optionTypes'],options[:options],@api_client,{groupId: groupId, cloudId: cloud, zoneId: cloud, instanceTypeId: instance_type['id'], version: version_prompt['version']})
  elsif !instance_type['optionTypes'].nil? && !instance_type['optionTypes'].empty?
    type_payload = Morpheus::Cli::OptionTypes.prompt(instance_type['optionTypes'],options[:options],@api_client,{groupId: groupId, cloudId: cloud, zoneId: cloud, instanceTypeId: instance_type['id'], version: version_prompt['version']})
  end
  if !type_payload['config'].nil?
    payload.merge!(type_payload['config'])
  end

  provision_payload = {}
  if !layout['provisionType'].nil? && !layout['provisionType']['optionTypes'].nil? && !layout['provisionType']['optionTypes'].empty?
    #puts "Checking for option Types"
    provision_payload = Morpheus::Cli::OptionTypes.prompt(layout['provisionType']['optionTypes'],options[:options],@api_client,{groupId: groupId, cloudId: cloud, zoneId: cloud, instanceTypeId: instance_type['id'], version: version_prompt['version']})
  end

  if !provision_payload.nil? && !provision_payload['config'].nil?
    payload.merge!(provision_payload['config'])
  end
  if !provision_payload.nil? && !provision_payload['server'].nil?
    payload[:server] = provision_payload['server']
  end

  # avoid 500 error
  payload[:servicePlanOptions] = {}

  begin
    json_response = @instances_interface.create(payload)
    if options[:json]
      print JSON.pretty_generate(json_response)
      print "\n"
    else
      print_green_success "Provisioning instance #{instance_name}"
      list([])
    end
  rescue RestClient::Exception => e
    print_rest_exception(e, options)
    exit 1
  end
end

#apply_security_groups(args) ⇒ Object



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
945
946
947
948
949
950
951
# File 'lib/morpheus/cli/instances.rb', line 916

def apply_security_groups(args)
  options = {}
  clear_or_secgroups_specified = false
  optparse = OptionParser.new do|opts|
    opts.banner = "Usage: morpheus instances apply-security-groups [name] [options]"
    opts.on( '-c', '--clear', "Clear all security groups" ) do
      options[:securityGroupIds] = []
      clear_or_secgroups_specified = true
    end
    opts.on( '-S', '--secgroups SECGROUPS', "Apply the specified comma separated security group ids" ) do |secgroups|
      options[:securityGroupIds] = secgroups.split(",")
      clear_or_secgroups_specified = true
    end
    build_common_options(opts, options, [:json, :remote])
  end
  if args.count < 1
    puts "\n#{optparse.banner}\n\n"
    exit 1
  end
  optparse.parse(args)
  connect(options)

  if !clear_or_secgroups_specified 
    puts usage
    exit
  end

  begin
    instance = find_instance_by_name(args[0])
    @instances_interface.apply_security_groups(instance['id'], options)
    security_groups([args[0]])
  rescue RestClient::Exception => e
    print_rest_exception(e, options)
    exit 1
  end
end

#backup(args) ⇒ Object



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

def backup(args) 
  options = {}
  optparse = OptionParser.new do|opts|
    opts.banner = "Usage: morpheus instances backup [name]"
    build_common_options(opts, options, [:json, :remote])
  end
  if args.count < 1
    puts "\n#{optparse.banner}\n\n"
    exit 1 
  end
  optparse.parse(args)
  connect(options)
  begin
    instance = find_instance_by_name(args[0])
    json_response = @instances_interface.backup(instance['id'])
    if options[:json]
      print JSON.pretty_generate(json_response)
      print "\n"
    else
      puts "Backup initiated."
    end
    return
  rescue RestClient::Exception => e
    print_rest_exception(e, options)
    exit 1
  end
end

#connect(opts) ⇒ Object



18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
# File 'lib/morpheus/cli/instances.rb', line 18

def connect(opts)
  if opts[:remote]
    @appliance_url = opts[:remote]
    @appliance_name = opts[:remote]
    @access_token = Morpheus::Cli::Credentials.new(@appliance_name,@appliance_url).request_credentials(opts)
  else
    @access_token = Morpheus::Cli::Credentials.new(@appliance_name,@appliance_url).request_credentials(opts)
  end
  @api_client = Morpheus::APIClient.new(@access_token,nil,nil, @appliance_url)   
  @instances_interface = Morpheus::APIClient.new(@access_token,nil,nil, @appliance_url).instances
  @task_sets_interface = Morpheus::APIClient.new(@access_token,nil,nil, @appliance_url).task_sets
  @logs_interface = Morpheus::APIClient.new(@access_token,nil,nil, @appliance_url).logs
  @tasks_interface = Morpheus::APIClient.new(@access_token,nil,nil, @appliance_url).tasks
  @instance_types_interface = Morpheus::APIClient.new(@access_token,nil,nil, @appliance_url).instance_types
  @groups_interface = Morpheus::APIClient.new(@access_token,nil,nil, @appliance_url).groups
  @provision_types_interface = Morpheus::APIClient.new(@access_token,nil,nil, @appliance_url).provision_types
  @options_interface = Morpheus::APIClient.new(@access_token,nil,nil, @appliance_url).options
  @active_groups = ::Morpheus::Cli::Groups.load_group_file
  if @access_token.empty?
    print_red_alert "Invalid Credentials. Unable to acquire access token. Please verify your credentials and try again."
    exit 1
  end
end

#delenv(args) ⇒ Object



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/instances.rb', line 426

def delenv(args)
  options = {}
  optparse = OptionParser.new do|opts|
    opts.banner = "Usage: morpheus instances setenv INSTANCE NAME"
    build_common_options(opts, options, [:json, :remote])
  end
  if args.count < 2
    puts "\n#{optparse.banner}\n\n"
    exit 1
  end
  optparse.parse(args)
  connect(options)
  begin
    instance = find_instance_by_name(args[0])
    @instances_interface.del_env(instance['id'], args[1])
    envs([args[0]])
  rescue RestClient::Exception => e
    print_rest_exception(e, options)
    exit 1
  end
end

#details(args) ⇒ Object



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

def details(args)
  options = {}
  optparse = OptionParser.new do|opts|
    opts.banner = "Usage: morpheus instances details [name]"
    build_common_options(opts, options, [:json, :remote])
  end
  if args.count < 1
    puts "\n#{optparse.banner}\n\n"
    return
  end
  optparse.parse(args)
  connect(options)
  begin
    instance_results = @instances_interface.get({name: args[0]})
    if instance_results['instances'].empty?
      puts "Instance not found by name #{args[0]}"
      return
    end
    instance = instance_results['instances'][0]
    instance_id = instance['id']
    stats = instance_results['stats'][instance_id.to_s]
    print "\n" ,cyan, bold, "#{instance['name']} (#{instance['instanceType']['name']})\n","==================", reset, "\n\n"
    print cyan, "Memory: \t#{Filesize.from("#{stats['usedMemory']} B").pretty} / #{Filesize.from("#{stats['maxMemory']} B").pretty}\n"
    print cyan, "Storage: \t#{Filesize.from("#{stats['usedStorage']} B").pretty} / #{Filesize.from("#{stats['maxStorage']} B").pretty}\n\n",reset
    puts instance
  rescue RestClient::Exception => e
    print_rest_exception(e, options)
    exit 1
  end
end

#envs(args) ⇒ Object



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

def envs(args)
  options = {}
  optparse = OptionParser.new do|opts|
    opts.banner = "Usage: morpheus instances envs [name]"
    build_common_options(opts, options, [:json, :remote])
  end
  if args.count < 1
    puts "\n#{optparse.banner}\n\n"
    exit 1
  end
  optparse.parse(args)
  connect(options)
  begin
    instance = find_instance_by_name(args[0])
    env_results = @instances_interface.get_envs(instance['id'])
    print "\n" ,cyan, bold, "#{instance['name']} (#{instance['instanceType']['name']})\n","==================", "\n\n", reset, cyan
    envs = env_results['envs'] || {}
    if env_results['readOnlyEnvs']
      envs += env_results['readOnlyEnvs'].map { |k,v| {:name => k, :value => k.downcase.include?("password") || v['masked'] ? "********" : v['value'], :export => true}}
    end
    tp envs, :name, :value, :export
    print "\n" ,cyan, bold, "Imported Envs\n","==================", "\n\n", reset, cyan
     imported_envs = env_results['importedEnvs'].map { |k,v| {:name => k, :value => k.downcase.include?("password") || v['masked'] ? "********" : v['value']}}
     tp imported_envs
    print reset, "\n"
    
  rescue RestClient::Exception => e
    print_rest_exception(e, options)
    exit 1
  end
end

#firewall_disable(args) ⇒ Object



833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
# File 'lib/morpheus/cli/instances.rb', line 833

def firewall_disable(args)
  options = {}
  optparse = OptionParser.new do|opts|
    opts.banner = "Usage: morpheus instances firewall-disable [name]"
    build_common_options(opts, options, [:json, :remote])
  end
  if args.count < 1
    puts "\n#{optparse.banner}\n\n"
    exit 1
  end
  optparse.parse(args)
  connect(options)
  begin
    instance = find_instance_by_name(args[0])
    @instances_interface.firewall_disable(instance['id'])
    security_groups([args[0]])
  rescue RestClient::Exception => e
    print_rest_exception(e, options)
    exit 1
  end
end

#firewall_enable(args) ⇒ Object



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

def firewall_enable(args)
  options = {}
  optparse = OptionParser.new do|opts|
    opts.banner = "Usage: morpheus instances firewall-enable [name]"
    build_common_options(opts, options, [:json, :remote])
  end
  if args.count < 1
    puts "\n#{optparse.banner}\n\n"
    exit 1
  end
  optparse.parse(args)
  connect(options)
  begin
    instance_results = @instances_interface.get({name: args[0]})
    if instance_results['instances'].empty?
      puts "Instance not found by name #{args[0]}"
      return
    end
    @instances_interface.firewall_enable(instance_results['instances'][0]['id'])
    security_groups([args[0]])
  rescue RestClient::Exception => e
    print_rest_exception(e, options)
    exit 1
  end
end

#handle(args) ⇒ Object



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

def handle(args) 
  usage = "Usage: morpheus instances [list,add,remove,stop,start,restart,backup,run-workflow,stop-service,start-service,restart-service,resize,upgrade,clone,envs,setenv,delenv] [name]"
  if args.empty?
    puts "\n#{usage}\n\n"
    return 
  end

  case args[0]
    when 'list'
      list(args[1..-1])
    when 'add'
      add(args[1..-1])
    when 'remove'
      remove(args[1..-1])
    when 'stop'
      stop(args[1..-1])
    when 'start'
      start(args[1..-1])
    when 'restart'
      restart(args[1..-1])
    when 'stop-service'
      stop_service(args[1..-1])
    when 'start-service'
      start_service(args[1..-1])
    when 'restart-service'
      restart_service(args[1..-1])
    when 'resize'
      resize(args[1..-1])
    when 'run-workflow'
      run_workflow(args[1..-1])
    when 'stats'
      stats(args[1..-1])
    when 'logs'
      logs(args[1..-1])
    when 'details'
      details(args[1..-1])
    when 'envs'
      envs(args[1..-1])
    when 'setenv'
      setenv(args[1..-1])  
    when 'delenv'
      delenv(args[1..-1])  
    when 'firewall-disable'
      firewall_disable(args[1..-1])  
    when 'firewall-enable'
      firewall_enable(args[1..-1]) 
    when 'security-groups'  
      security_groups(args[1..-1]) 
    when 'apply-security-groups'  
      apply_security_groups(args[1..-1]) 
    when 'backup'
      backup(args[1..-1])  
    else
      puts "\n#{usage}\n\n"
      exit 127
  end
end

#list(args) ⇒ Object



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

def list(args)
  options = {}
  optparse = OptionParser.new do|opts|
    opts.on( '-g', '--group GROUP', "Group Name" ) do |group|
      options[:group] = group
    end
    build_common_options(opts, options, [:list, :json, :remote])
  end
  optparse.parse(args)
  connect(options)
  begin
    params = {}
    if !options[:group].nil?
      group = find_group_by_name(options[:group])
      if !group.nil?
        params['site'] = group
      end
    end
    [:phrase, :offset, :max, :sort, :direction].each do |k|
      params[k] = options[k] unless options[k].nil?
    end

    json_response = @instances_interface.get(params)
    if options[:json]
      print JSON.pretty_generate(json_response)
      print "\n"
    else
      instances = json_response['instances']

      print "\n" ,cyan, bold, "Morpheus Instances\n","==================", reset, "\n\n"
      if instances.empty?
        puts yellow,"No instances currently configured.",reset
      else
        print cyan
        instance_table = instances.collect do |instance|
          status_string = instance['status']
          if status_string == 'running'
            status_string = "#{green}#{status_string.upcase}#{cyan}"
          elsif status_string == 'stopped' or status_string == 'failed'
            status_string = "#{red}#{status_string.upcase}#{cyan}"
          elsif status_string == 'unknown'
            status_string = "#{white}#{status_string.upcase}#{cyan}"
          else
            status_string = "#{yellow}#{status_string.upcase}#{cyan}"
          end
          connection_string = ''
          if !instance['connectionInfo'].nil? && instance['connectionInfo'].empty? == false
            connection_string = "#{instance['connectionInfo'][0]['ip']}:#{instance['connectionInfo'][0]['port']}"
          end
          {id: instance['id'], name: instance['name'], connection: connection_string, environment: instance['instanceContext'], nodes: instance['containers'].count, status: status_string, type: instance['instanceType']['name'], group: !instance['group'].nil? ? instance['group']['name'] : nil, cloud: !instance['cloud'].nil? ? instance['cloud']['name'] : nil}
        end
        tp instance_table, :id, :name, :group, :cloud, :type, :environment, :nodes, :connection, :status
      end
      print reset,"\n\n"
    end
    
  rescue RestClient::Exception => e
    print_rest_exception(e, options)
    exit 1
  end
end

#logs(args) ⇒ Object



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

def logs(args) 
  options = {}
  optparse = OptionParser.new do|opts|
    opts.banner = "Usage: morpheus instances logs [name]"
    opts.on( '-n', '--node NODE_ID', "Scope logs to specific Container or VM" ) do |node_id|
      options[:node_id] = node_id.to_i
    end
    build_common_options(opts, options, [:list, :json, :remote])
  end
  if args.count < 1
    puts "\n#{optparse.banner}\n\n"
    return
  end
  optparse.parse(args)
  connect(options)
  begin
    instance = find_instance_by_name(args[0])
    container_ids = instance['containers']
    if options[:node_id] && container_ids.include?(options[:node_id])
      container_ids = [options[:node_id]]
    end
    logs = @logs_interface.container_logs(container_ids, { max: options[:max] || 100, offset: options[:offset] || 0, query: options[:phrase]})
    if options[:json]
      puts logs
    else
      logs['data'].reverse.each do |log_entry|
        log_level = ''
        case log_entry['level']
          when 'INFO'
            log_level = "#{blue}#{bold}INFO#{reset}"
          when 'DEBUG'
            log_level = "#{white}#{bold}DEBUG#{reset}"
          when 'WARN'
            log_level = "#{yellow}#{bold}WARN#{reset}"
          when 'ERROR'
            log_level = "#{red}#{bold}ERROR#{reset}"
          when 'FATAL'
            log_level = "#{red}#{bold}FATAL#{reset}"
        end
        puts "[#{log_entry['ts']}] #{log_level} - #{log_entry['message']}"
      end
      print reset,"\n"
    end
  rescue RestClient::Exception => e
    print_rest_exception(e, options)
    exit 1
  end
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
831
# File 'lib/morpheus/cli/instances.rb', line 800

def remove(args)
  options = {}
  query_params = {keepBackups: 'off', force: 'off'}
  optparse = OptionParser.new do|opts|
    opts.banner = "Usage: morpheus instances remove [name] [-fB]"
    opts.on( '-f', '--force', "Force Remove" ) do
      query_params[:force] = 'on'
    end
    opts.on( '-B', '--keep-backups', "Preserve copy of backups" ) do
      query_params[:keepBackups] = 'on'
    end
    build_common_options(opts, options, [:auto_confirm, :json, :remote])

  end
  if args.count < 1
    puts "\n#{optparse}\n\n"
    exit 1
  end
  optparse.parse(args)
  connect(options)
  begin
    instance = find_instance_by_name(args[0])
    unless options[:yes] || ::Morpheus::Cli::OptionTypes::confirm("Are you sure you would like to remove this instance?", options)
      exit 1
    end
    @instances_interface.destroy(instance['id'],query_params)
    list([])
  rescue RestClient::Exception => e
    print_rest_exception(e, options)
    exit 1
  end
end

#resize(args) ⇒ Object



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

def resize(args)
  options = {}
  optparse = OptionParser.new do|opts|
    opts.banner = "Usage: morpheus instances resize [name]"
    build_common_options(opts, options, [:options, :json, :remote])
  end
  if args.count < 1
    puts "\n#{optparse.banner}\n\n"
    exit 1
  end
  optparse.parse(args)
  connect(options)
  begin
    instance = find_instance_by_name(args[0])

    group_id = instance['group']['id']
    cloud_id = instance['cloud']['id']
    layout_id = instance['layout']['id']

    plan_id = instance['plan']['id']
    payload = {}

    # avoid 500 error
    payload[:servicePlanOptions] = {}

    puts "\nDue to limitations by most Guest Operating Systems, Disk sizes can only be expanded and not reduced.\nIf a smaller plan is selected, memory and CPU (if relevant) will be reduced but storage will not.\n\n"


    #plan_prompt = Morpheus::Cli::OptionTypes.prompt([{'fieldName' => 'servicePlan', 'type' => 'select', 'fieldLabel' => 'Plan', 'optionSource' => 'instanceServicePlans', 'required' => true, 'description' => 'Choose the appropriately sized plan for this instance'}],options[:options],@api_client,{groupId: groupId, zoneId: cloud, instanceTypeId: instance_type['id'], layoutId: layout_id, version: version_prompt['version']})
    available_plans_result = @options_interface.options_for_source('instanceServicePlans',{groupId: group_id, zoneId: cloud_id, instanceTypeId: instance['instanceType']['id'], layoutId: layout_id, version: instance['instanceVersion']})
    available_plans = available_plans_result['data']
    available_plans.each do |plan|
      if plan['value'] && plan['value'].to_i == plan_id.to_i
        plan['name'] = "#{plan['name']} (current)"
      end
    end

    plan_prompt = Morpheus::Cli::OptionTypes.prompt([{'fieldName' => 'servicePlan', 'type' => 'select', 'fieldLabel' => 'New Plan', 'selectOptions' => available_plans, 'required' => true, 'description' => 'Choose the new plan for this instance'}],options[:options] )
    new_plan_id = plan_prompt['servicePlan']
    payload[:servicePlanId] = new_plan_id

    volumes_response = @instances_interface.volumes(instance['id'])
    current_volumes = volumes_response['volumes'].sort {|x,y| x['displayOrder'] <=> y['displayOrder'] }

    begin
      service_plan_options_json = @instance_types_interface.service_plan_options(new_plan_id, {cloudId: cloud_id, zoneId: cloud_id, layoutId: layout_id})
      
      # puts ""
      # print JSON.pretty_generate(service_plan_options_json)
      
      plan_options = service_plan_options_json['plan']
      volumes = prompt_resize_instance_volumes(current_volumes, plan_options, options, @api_client, {})

      # puts "VOLUMES:"
      # print JSON.pretty_generate(volumes)

      if !volumes.empty?
        payload[:volumes] = volumes
      end

      # puts "\nexiting early...\n"
      # exit 1

    rescue RestClient::Exception => e
      print_red_alert "Unable to load options for selected plan."
      print_rest_exception(e, options)
      exit 1
    end

    # only amazon supports this option
    # for now, always do this
    payload[:deleteOriginalVolumes] = true

    json_response = @instances_interface.resize(instance['id'], payload)
    if options[:json]
      print JSON.pretty_generate(json_response)
      print "\n"
    else
      print_green_success "Resizing instance #{instance['name']}"
      list([])
    end
    
  rescue RestClient::Exception => e
    print_rest_exception(e, options)
    exit 1
  end
end

#restart(args) ⇒ Object



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

def restart(args)
  options = {}
  optparse = OptionParser.new do|opts|
    opts.banner = "Usage: morpheus instances restart [name]"
    build_common_options(opts, options, [:auto_confirm, :json, :remote])
  end
  if args.count < 1
    puts "\n#{optparse.banner}\n\n"
    exit 1
  end
  optparse.parse(args)
  connect(options)
  begin
    instance = find_instance_by_name(args[0])
    unless options[:yes] || ::Morpheus::Cli::OptionTypes::confirm("Are you sure you would like to restart this instance?", options)
      exit 1
    end
    json_response = @instances_interface.restart(instance['id'])
    if options[:json]
      print JSON.pretty_generate(json_response)
      print "\n"
    end
    return
  rescue RestClient::Exception => e
    print_rest_exception(e, options)
    exit 1
  end
end

#restart_service(args) ⇒ Object



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

def restart_service(args)
  options = {}
  optparse = OptionParser.new do|opts|
    opts.banner = "Usage: morpheus instances restart-service [name]"
    build_common_options(opts, options, [:auto_confirm, :json, :remote])
  end
  if args.count < 1
    puts "\n#{optparse.banner}\n\n"
    exit 1
  end
  optparse.parse(args)
  connect(options)
  begin
    instance = find_instance_by_name(args[0])
    unless options[:yes] || ::Morpheus::Cli::OptionTypes::confirm("Are you sure you would like to restart this instance?", options)
      exit 1
    end
    json_response = @instances_interface.restart(instance['id'],false)
    if options[:json]
      print JSON.pretty_generate(json_response)
      print "\n"
    else
      puts "Restarting service on instance #{args[0]}"
    end
    return
  rescue RestClient::Exception => e
    print_rest_exception(e, options)
    exit 1
  end
end

#run_workflow(args) ⇒ Object



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
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
# File 'lib/morpheus/cli/instances.rb', line 954

def run_workflow(args)
  options = {}
  
  optparse = OptionParser.new do|opts|
    opts.banner = "Usage: morpheus instances run-workflow [INSTANCE] [name] [options]"
    build_common_options(opts, options, [:options, :json, :remote])
  end
  if args.count < 2
    puts "\n#{optparse}\n\n"
    exit 1
  end
  
  optparse.parse(args)
  connect(options)
  instance = find_instance_by_name(args[0])
  workflow = find_workflow_by_name(args[1])
  task_types = @tasks_interface.task_types()
  editable_options = []
  workflow['taskSetTasks'].sort{|a,b| a['taskOrder'] <=> b['taskOrder']}.each do |task_set_task|
    task_type_id = task_set_task['task']['taskType']['id']
    task_type = task_types['taskTypes'].find{ |current_task_type| current_task_type['id'] == task_type_id}
    task_opts = task_type['optionTypes'].select { |otype| otype['editable']}
    if !task_opts.nil? && !task_opts.empty?
      editable_options += task_opts.collect do |task_opt|
        new_task_opt = task_opt.clone
        new_task_opt['fieldContext'] = "#{task_set_task['id']}.#{new_task_opt['fieldContext']}"
      end
    end
  end
  params = options[:options] || {}

  if params.empty? && !editable_options.empty?
    puts "\n#{optparse.banner}\n\n"
    option_lines = editable_options.collect {|it| "\t-O #{it['fieldContext'] ? (it['fieldContext'] + '.') : ''}#{it['fieldName']}=\"value\"" }.join("\n")
    puts "\nAvailable Options:\n#{option_lines}\n\n"
    exit 1
  end

  workflow_payload = {taskSet: {"#{workflow['id']}" => params }}
  begin
    
    json_response = @instances_interface.workflow(instance['id'],workflow['id'], workflow_payload)
    if options[:json]
      print JSON.pretty_generate(json_response)
      print "\n"
    else
      puts "Running workflow..."
    end
  rescue RestClient::Exception => e
    print_rest_exception(e, options)
    exit 1
  end
end

#security_groups(args) ⇒ Object



881
882
883
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
# File 'lib/morpheus/cli/instances.rb', line 881

def security_groups(args)
  options = {}
  optparse = OptionParser.new do|opts|
    opts.banner = "Usage: morpheus instances security-groups [name]"
    build_common_options(opts, options, [:json, :remote])
  end
  if args.count < 1
    puts "\n#{optparse.banner}\n\n"
    exit 1
  end
  optparse.parse(args)
  connect(options)
  begin
    instance = find_instance_by_name(args[0])
    instance_id = instance['id']
    json_response = @instances_interface.security_groups(instance_id)

    securityGroups = json_response['securityGroups']
    print "\n" ,cyan, bold, "Morpheus Security Groups for Instance:#{instance_id}\n","==================", reset, "\n\n"
    print cyan, "Firewall Enabled=#{json_response['firewallEnabled']}\n\n"
    if securityGroups.empty?
      puts yellow,"No security groups currently applied.",reset
    else
      securityGroups.each do |securityGroup|
        print cyan, "=  #{securityGroup['id']} (#{securityGroup['name']}) - (#{securityGroup['description']})\n"
      end
    end
    print reset,"\n\n"

  rescue RestClient::Exception => e
    print_rest_exception(e, options)
    exit 1
  end
end

#setenv(args) ⇒ Object



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

def setenv(args)
  options = {}

  optparse = OptionParser.new do|opts|
    opts.banner = "Usage: morpheus instances setenv INSTANCE NAME VALUE [-e]"
    opts.on( '-e', "Exportable" ) do |exportable|
      options[:export] = exportable
    end
    opts.on( '-M', "Masked" ) do |masked|
      options[:masked] = masked
    end
    build_common_options(opts, options, [:json, :remote])
  end
  if args.count < 3
    puts "\n#{optparse.banner}\n\n"
    exit 1
  end
  optparse.parse(args)
  connect(options)
  begin
    instance = find_instance_by_name(args[0])
    evar = {name: args[1], value: args[2], export: options[:export], masked: options[:masked]}
    params = {}
    @instances_interface.create_env(instance['id'], [evar])
    envs([args[0]])
  rescue RestClient::Exception => e
    print_rest_exception(e, options)
    exit 1
  end
end

#start(args) ⇒ Object



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

def start(args)
  options = {}
  optparse = OptionParser.new do|opts|
    opts.banner = "Usage: morpheus instances start [name]"
    build_common_options(opts, options, [:json, :remote])
  end
  if args.count < 1
    puts "\n#{optparse.banner}\n\n"
    exit 1
  end
  optparse.parse(args)
  connect(options)
  begin
    instance = find_instance_by_name(args[0])
    json_response = @instances_interface.start(instance['id'])
    if options[:json]
      print JSON.pretty_generate(json_response)
      print "\n"
    end
    return
  rescue RestClient::Exception => e
    print_rest_exception(e, options)
    exit 1
  end
end

#start_service(args) ⇒ Object



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

def start_service(args)
  options = {}
  optparse = OptionParser.new do|opts|
    opts.banner = "Usage: morpheus instances start-service [name]"
    build_common_options(opts, options, [:json, :remote])
  end
  if args.count < 1
    puts "\n#{optparse.banner}\n\n"
    exit 1
  end
  optparse.parse(args)
  connect(options)
  begin
    instance = find_instance_by_name(args[0])
    json_response = @instances_interface.start(instance['id'],false)
    if options[:json]
      print JSON.pretty_generate(json_response)
      print "\n"
    else
      puts "Starting service on #{args[0]}"
    end
    return
  rescue RestClient::Exception => e
    print_rest_exception(e, options)
    exit 1
  end
end

#stats(args) ⇒ Object



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

def stats(args)
  options = {}
  optparse = OptionParser.new do|opts|
    opts.banner = "Usage: morpheus instances stats [name]"
    build_common_options(opts, options, [:json, :remote])
  end
  if args.count < 1
    puts "\n#{optparse.banner}\n\n"
    return
  end
  optparse.parse(args)
  connect(options)
  begin
    instance_results = @instances_interface.get({name: args[0]})
    if instance_results['instances'].empty?
      puts "Instance not found by name #{args[0]}"
      return
    end
    instance = instance_results['instances'][0]
    instance_id = instance['id']
    stats = instance_results['stats'][instance_id.to_s]
    if options[:json]
      print JSON.pretty_generate(stats)
      print "\n"
    else
      print "\n" ,cyan, bold, "#{instance['name']} (#{instance['instanceType']['name']})\n","==================", "\n\n", reset, cyan
      stats_map = {}
      stats_map[:memory] = "#{Filesize.from("#{stats['usedMemory']} B").pretty} / #{Filesize.from("#{stats['maxMemory']} B").pretty}"
      stats_map[:storage] = "#{Filesize.from("#{stats['usedStorage']} B").pretty} / #{Filesize.from("#{stats['maxStorage']} B").pretty}"
      stats_map[:cpu] = "#{stats['usedCpu'].to_f.round(2)}%"
      tp [stats_map], :memory,:storage,:cpu
      print reset, "\n"
    end
  rescue RestClient::Exception => e
    print_rest_exception(e, options)
    exit 1
  end
end

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

def stop(args)
  options = {}
  optparse = OptionParser.new do|opts|
    opts.banner = "Usage: morpheus instances stop [name]"
    build_common_options(opts, options, [:auto_confirm, :json, :remote])
  end
  if args.count < 1
    puts "\n#{optparse.banner}\n\n"
    exit 1
  end
  optparse.parse(args)
  connect(options)
  begin
    instance = find_instance_by_name(args[0])
    unless options[:yes] || ::Morpheus::Cli::OptionTypes::confirm("Are you sure you would like to stop this instance?", options)
      exit 1
    end
    json_response = @instances_interface.stop(instance['id'])
    if options[:json]
      print JSON.pretty_generate(json_response)
      print "\n"
    end
    return
  rescue RestClient::Exception => e
    print_rest_exception(e, options)
    exit 1
  end
end

#stop_service(args) ⇒ Object



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

def stop_service(args)
  options = {}
  optparse = OptionParser.new do|opts|
    opts.banner = "Usage: morpheus instances stop-service [name]"
    build_common_options(opts, options, [:auto_confirm, :json, :remote])
  end
  if args.count < 1
    puts "\n#{optparse.banner}\n\n"
    exit 1
  end
  optparse.parse(args)
  connect(options)
  begin
    instance = find_instance_by_name(args[0])
    unless options[:yes] || ::Morpheus::Cli::OptionTypes::confirm("Are you sure you would like to stop this instance?", options)
      exit 1
    end
    json_response = @instances_interface.stop(instance['id'],false)
    if options[:json]
      print JSON.pretty_generate(json_response)
      print "\n"
    else
      puts "Stopping service on #{args[0]}"
    end
    return
  rescue RestClient::Exception => e
    print_rest_exception(e, options)
    exit 1
  end
end