Class: Morpheus::Cli::ExecuteSchedulesCommand

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

Instance Attribute Summary

Attributes included from CliCommand

#no_prompt

Instance Method Summary collapse

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



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

def _get(id, options)
  options ||= {}
  options[:max_servers] ||= 10
  options[:max_instances] ||= 10
  begin
    schedule = find_schedule_by_name_or_id(id)
    if schedule.nil?
      return 1
    end
    @execute_schedules_interface.setopts(options)
    if options[:dry_run]
      print_dry_run @execute_schedules_interface.dry.get(schedule['id'])
      return
    end
    json_response = @execute_schedules_interface.get(schedule['id'])
    schedule = json_response['schedule']
    instances = json_response['instances'] || []
    servers = json_response['servers'] || []
    if options[:json]
      puts as_json(json_response, options, "schedule")
      return 0
    elsif options[:yaml]
      puts as_yaml(json_response, options, "schedule")
      return 0
    elsif options[:csv]
      puts records_as_csv([json_response['schedule']], options)
      return 0
    end

    print_h1 "Execute Schedule Details"
    print cyan
    description_cols = {
      "ID" => lambda {|it| it['id'] },
      #"Tenant" => lambda {|it| it['owner'] ? it['owner']['name'] : '' },
      "Name" => lambda {|it| it['name'] },
      "Description" => lambda {|it| it['description'] },
      "Type" => lambda {|it| format_schedule_type(it['scheduleType']) },
      "Enabled" => lambda {|it| format_boolean it['enabled'] },
      "Time Zone" => lambda {|it| it['scheduleTimezone'] || 'UTC (default)' },
      "Cron" => lambda {|it| it['cron'] },
      "Created" => lambda {|it| format_local_dt(it['dateCreated']) },
      "Updated" => lambda {|it| format_local_dt(it['lastUpdated']) }
    }
    print_description_list(description_cols, schedule)

    ## Instances
    if instances.size == 0
      # print cyan,"No instances",reset,"\n"
    else
      print_h2 "Instances (#{instances.size})"
      instance_rows = instances.first(options[:max_instances])
      print as_pretty_table(instance_rows, [:id, :name])
      print_results_pagination({'meta'=>{'total'=>instances.size,'size'=>instance_rows.size,'max'=>options[:max_servers],'offset'=>0}}, {:label => "instance in schedule", :n_label => "instances in schedule"})
    end

    ## Hosts
    if servers.size == 0
      # print cyan,"No hosts",reset,"\n"
    else
      options[:max_servers] ||= 10
      print_h2 "Hosts (#{servers.size})"
      server_rows = servers.first(options[:max_servers])
      print as_pretty_table(server_rows, [:id, :name])
      print_results_pagination({'meta'=>{'total'=>servers.size,'size'=>server_rows.size,'max'=>options[:max_servers],'offset'=>0}}, {:label => "host in schedule", :n_label => "hosts in schedule"})
    end

    print reset,"\n"

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

#add(args) ⇒ Object



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

def add(args)
  options = {}
  params = {'scheduleType' => 'execute'}
  optparse = Morpheus::Cli::OptionParser.new do |opts|
    opts.banner = subcommand_usage("[name]")
    opts.on('--name VALUE', String, "Name") do |val|
      params['name'] = val
    end
    # opts.on('--code VALUE', String, "Code") do |val|
    #   params['code'] = val
    # end
    opts.on('--description VALUE', String, "Description") do |val|
      params['description'] = val
    end
    opts.on('--type [execute]', String, "Type of Schedule. Default is 'execute'") do |val|
      params['scheduleType'] = val
    end
    opts.on('--timezone CODE', String, "The timezone. Default is UTC.") do |val|
      params['scheduleTimezone'] = val
    end
    opts.on('--cron EXPRESSION', String, "Cron Expression. Default is daily at midnight '0 0 * * *'") do |val|
      params['cron'] = val
    end
    opts.on('--enabled [on|off]', String, "Can be used to disable it") do |val|
      params['enabled'] = !(val.to_s == 'off' || val.to_s == 'false')
    end
    build_common_options(opts, options, [:options, :payload, :json, :dry_run, :remote, :quiet])
    opts.footer = "Create a new execute schedule." + "\n" +
                  "[name] is required and can be passed as --name instead."
  end
  optparse.parse!(args)
  if args.count > 1
    print_error Morpheus::Terminal.angry_prompt
    puts_error  "wrong number of arguments, expected 0-1 and got (#{args.count}) #{args.inspect}\n#{optparse}"
    return 1
  end
  # support [name] as first argument
  if args[0]
    params['name'] = args[0]
  end
  connect(options)
  begin
    # construct payload
    payload = nil
    if options[:payload]
      payload = options[:payload]
    else
      # merge -O options into normally parsed options
      params.deep_merge!(options[:options].reject {|k,v| k.is_a?(Symbol) }) if options[:options]
      # todo: prompt?
      payload = {'schedule' => params}
    end
    @execute_schedules_interface.setopts(options)
    if options[:dry_run]
      print_dry_run @execute_schedules_interface.dry.create(payload)
      return
    end
    json_response = @execute_schedules_interface.create(payload)
    if options[:json]
      puts as_json(json_response, options)
    elsif !options[:quiet]
      schedule = json_response['schedule']
      print_green_success "Added execute schedule #{schedule['name']}"
      _get(schedule['id'], {})
    end
    return 0
  rescue RestClient::Exception => e
    print_rest_exception(e, options)
    return 1
  end
end

#add_hosts(args) ⇒ Object



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

def add_hosts(args)
  options = {}
  params = {}
  optparse = Morpheus::Cli::OptionParser.new do |opts|
    opts.banner = subcommand_usage("[name] [host]")
    build_common_options(opts, options, [:payload, :json, :dry_run, :remote, :quiet])
    opts.footer = "Assign hosts to a execute schedule.\n" +
                  "[name] is required. This is the name or id of a execute schedule.\n" +
                  "[host] is required. This is the name or id of a host. More than one can be passed."
  end
  optparse.parse!(args)
  if args.count < 2
    puts optparse
    return 1
  end
  connect(options)
  begin
    schedule = find_schedule_by_name_or_id(args[0])
    if schedule.nil?
      return 1
    end

    # construct payload
    payload = nil
    if options[:payload]
      payload = options[:payload]
    else
      server_ids = args[1..-1]
      servers = []
      server_ids.each do |server_id|
        server = find_server_by_name_or_id(server_id)
        return 1 if server.nil?
        servers << server
      end
      payload = {'servers' => servers.collect {|it| it['id'] } }
    end
    @execute_schedules_interface.setopts(options)
    if options[:dry_run]
      print_dry_run @execute_schedules_interface.dry.add_servers(schedule["id"], payload)
      return 0
    end
    json_response = @execute_schedules_interface.add_servers(schedule["id"], payload)
    if options[:json]
      puts as_json(json_response, options)
    elsif !options[:quiet]
      if servers.size == 1
          print_green_success  "Added host #{servers[0]['name']} to execute schedule #{schedule['name']}"
        else
          print_green_success "Added #{servers.size} hosts to execute schedule #{schedule['name']}"
        end
      _get(schedule['id'], {})
    end
    return 0
  rescue RestClient::Exception => e
    print_rest_exception(e, options)
    return 1
  end
end

#add_instances(args) ⇒ Object



362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
# File 'lib/morpheus/cli/execute_schedules_command.rb', line 362

def add_instances(args)
  options = {}
  params = {}
  optparse = Morpheus::Cli::OptionParser.new do |opts|
    opts.banner = subcommand_usage("[name] [instance]")
    build_common_options(opts, options, [:payload, :json, :dry_run, :remote, :quiet])
    opts.footer = "Assign instances to a execute schedule.\n" +
                  "[name] is required. This is the name or id of a execute schedule.\n" +
                  "[instance] is required. This is the name or id of an instance. More than one can be passed."
  end
  optparse.parse!(args)
  if args.count < 2
    puts optparse
    return 1
  end
  connect(options)
  begin
    schedule = find_schedule_by_name_or_id(args[0])
    if schedule.nil?
      return 1
    end

    # construct payload
    payload = nil
    if options[:payload]
      payload = options[:payload]
    else
      instance_ids = args[1..-1]
      instances = []
      instance_ids.each do |instance_id|
        instance = find_instance_by_name_or_id(instance_id)
        return 1 if instance.nil?
        instances << instance
      end
      payload = {'instances' => instances.collect {|it| it['id'] } }
    end
    @execute_schedules_interface.setopts(options)
    if options[:dry_run]
      print_dry_run @execute_schedules_interface.dry.add_instances(schedule["id"], payload)
      return 0
    end
    json_response = @execute_schedules_interface.add_instances(schedule["id"], payload)
    if options[:json]
      puts as_json(json_response, options)
    elsif !options[:quiet]
      if instances.size == 1
          print_green_success  "Added #{instances[0]['name']} to execute schedule #{schedule['name']}"
        else
          print_green_success "Added #{instances.size} instances to execute schedule #{schedule['name']}"
        end
      _get(schedule['id'], {})
    end
    return 0
  rescue RestClient::Exception => e
    print_rest_exception(e, options)
    return 1
  end
end

#connect(opts) ⇒ Object



14
15
16
17
18
19
# File 'lib/morpheus/cli/execute_schedules_command.rb', line 14

def connect(opts)
  @api_client = establish_remote_appliance_connection(opts)
  @execute_schedules_interface = Morpheus::APIClient.new(@access_token,nil,nil, @appliance_url).execute_schedules
  @instances_interface = Morpheus::APIClient.new(@access_token,nil,nil, @appliance_url).instances
  @servers_interface = Morpheus::APIClient.new(@access_token,nil,nil, @appliance_url).servers
end

#get(args) ⇒ Object



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

def get(args)
  options = {}
  options[:max_instances] = 10
  options[:max_servers] = 10
  optparse = Morpheus::Cli::OptionParser.new do |opts|
    opts.banner = subcommand_usage("[name]")
    opts.on('--max-instances VALUE', String, "Display a limited number of instances in schedule. Default is 25") do |val|
      options[:max_instances] = val.to_i
    end
    opts.on('--max-hosts VALUE', String, "Display a limited number of hosts in schedule. Default is 25") do |val|
      options[:max_servers] = val.to_i
    end
    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



21
22
23
# File 'lib/morpheus/cli/execute_schedules_command.rb', line 21

def handle(args)
  handle_subcommand(args)
end

#list(args) ⇒ Object



25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
# File 'lib/morpheus/cli/execute_schedules_command.rb', line 25

def list(args)
  options = {}
  params = {}
  optparse = Morpheus::Cli::OptionParser.new do |opts|
    opts.banner = subcommand_usage()
    build_common_options(opts, options, [:list, :json, :yaml, :csv, :fields, :dry_run, :remote])
  end
  optparse.parse!(args)
  connect(options)
  begin
    params.merge!(parse_list_options(options))
    @execute_schedules_interface.setopts(options)
    if options[:dry_run]
      print_dry_run @execute_schedules_interface.dry.list(params)
      return
    end
    json_response = @execute_schedules_interface.list(params)
    if options[:json]
      puts as_json(json_response, options, "schedules")
      return 0
    elsif options[:csv]
      puts records_as_csv(json_response['schedules'], options)
      return 0
    elsif options[:yaml]
      puts as_yaml(json_response, options, "schedules")
      return 0
    end
    schedules = json_response['schedules']
    title = "Morpheus Execute Schedules"
    subtitles = []
    subtitles += parse_list_subtitles(options)
    print_h1 title, subtitles
    if schedules.empty?
      print cyan,"No execute schedules found.",reset,"\n"
    else
      print_schedules_table(schedules, options)
      print_results_pagination(json_response, {:label => "schedule", :n_label => "schedules"})
      # print_results_pagination(json_response)
    end
    print reset,"\n"
  rescue RestClient::Exception => e
    print_rest_exception(e, options)
    return 1
  end
end

#remove(args) ⇒ Object



314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
# File 'lib/morpheus/cli/execute_schedules_command.rb', line 314

def remove(args)
  options = {}
  params = {}
  optparse = Morpheus::Cli::OptionParser.new do |opts|
    opts.banner = subcommand_usage("[name]")
    build_common_options(opts, options, [:json, :dry_run, :quiet, :auto_confirm])
  end
  optparse.parse!(args)
  if args.count < 1
    puts optparse
    return 127
  end
  connect(options)

  begin
    schedule = find_schedule_by_name_or_id(args[0])
    if schedule.nil?
      return 1
    end

    unless options[:yes] || ::Morpheus::Cli::OptionTypes::confirm("Are you sure you would like to delete execute schedule '#{schedule['name']}'?", options)
      return false
    end

    # payload = {
    #   'schedule' => {id: schedule["id"]}
    # }
    # payload['schedule'].merge!(schedule)
    payload = params
    @execute_schedules_interface.setopts(options)
    if options[:dry_run]
      print_dry_run @execute_schedules_interface.dry.destroy(schedule["id"])
      return
    end

    json_response = @execute_schedules_interface.destroy(schedule["id"])
    if options[:json]
      puts as_json(json_response, options)
    elsif !options[:quiet]
      print_green_success "Deleted execute schedule #{schedule['name']}"
    end
    return 0, nil
  rescue RestClient::Exception => e
    print_rest_exception(e, options)
    return 1
  end
end

#remove_hosts(args) ⇒ Object



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

def remove_hosts(args)
  options = {}
  params = {}
  optparse = Morpheus::Cli::OptionParser.new do |opts|
    opts.banner = subcommand_usage("[name] [host]")
    build_common_options(opts, options, [:payload, :json, :dry_run, :remote, :quiet])
    opts.footer = "Remove hosts from a execute schedule.\n" +
                  "[name] is required. This is the name or id of a execute schedule.\n" +
                  "[host] is required. This is the name or id of a host. More than one can be passed."
  end
  optparse.parse!(args)
  if args.count < 2
    puts optparse
    return 1
  end
  connect(options)
  begin
    schedule = find_schedule_by_name_or_id(args[0])
    if schedule.nil?
      return 1
    end

    # construct payload
    payload = nil
    if options[:payload]
      payload = options[:payload]
    else
      server_ids = args[1..-1]
      servers = []
      server_ids.each do |server_id|
        server = find_server_by_name_or_id(server_id)
        return 1 if server.nil?
        servers << server
      end
      payload = {'servers' => servers.collect {|it| it['id'] } }
    end
    @execute_schedules_interface.setopts(options)
    if options[:dry_run]
      print_dry_run @execute_schedules_interface.dry.remove_servers(schedule["id"], payload)
      return 0
    end
    json_response = @execute_schedules_interface.remove_servers(schedule["id"], payload)
    if options[:json]
      puts as_json(json_response, options)
    elsif !options[:quiet]
      if servers.size == 1
          print_green_success  "Removed host #{servers[0]['name']} from execute schedule #{schedule['name']}"
        else
          print_green_success "Removed #{servers.size} hosts from execute schedule #{schedule['name']}"
        end
      _get(schedule['id'], {})
    end
    return 0
  rescue RestClient::Exception => e
    print_rest_exception(e, options)
    return 1
  end
end

#remove_instances(args) ⇒ Object



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

def remove_instances(args)
  options = {}
  params = {}
  optparse = Morpheus::Cli::OptionParser.new do |opts|
    opts.banner = subcommand_usage("[name] [instance]")
    build_common_options(opts, options, [:payload, :json, :dry_run, :remote, :quiet])
    opts.footer = "Remove instances from a execute schedule.\n" +
                  "[name] is required. This is the name or id of a execute schedule.\n" +
                  "[instance] is required. This is the name or id of an instance. More than one can be passed."
  end
  optparse.parse!(args)
  if args.count < 2
    puts optparse
    return 1
  end
  connect(options)
  begin
    schedule = find_schedule_by_name_or_id(args[0])
    if schedule.nil?
      return 1
    end

    # construct payload
    payload = nil
    if options[:payload]
      payload = options[:payload]
    else
      instance_ids = args[1..-1]
      instances = []
      instance_ids.each do |instance_id|
        instance = find_instance_by_name_or_id(instance_id)
        return 1 if instance.nil?
        instances << instance
      end
      payload = {'instances' => instances.collect {|it| it['id'] } }
    end
    @execute_schedules_interface.setopts(options)
    if options[:dry_run]
      print_dry_run @execute_schedules_interface.dry.remove_instances(schedule["id"], payload)
      return 0
    end
    json_response = @execute_schedules_interface.remove_instances(schedule["id"], payload)
    if options[:json]
      puts as_json(json_response, options)
    elsif !options[:quiet]
      if instances.size == 1
          print_green_success  "Removed instance #{instances[0]['name']} from execute schedule #{schedule['name']}"
        else
          print_green_success "Removed #{instances.size} instances from execute schedule #{schedule['name']}"
        end
      _get(schedule['id'], {})
    end
    return 0
  rescue RestClient::Exception => e
    print_rest_exception(e, options)
    return 1
  end
end

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

def update(args)
  options = {}
  params = {}
  optparse = Morpheus::Cli::OptionParser.new do |opts|
    opts.banner = subcommand_usage("[name]")
    opts.on('--name VALUE', String, "Name") do |val|
      params['name'] = val
    end
    # opts.on('--code VALUE', String, "Code") do |val|
    #   params['code'] = val
    # end
    opts.on('--description VALUE', String, "Description") do |val|
      params['description'] = val
    end
    opts.on('--type [execute]', String, "Type of Schedule. Default is 'execute'") do |val|
      params['scheduleType'] = val
    end
    opts.on('--timezone CODE', String, "The timezone. Default is UTC.") do |val|
      params['scheduleTimezone'] = val
    end
    opts.on('--cron EXPRESSION', String, "Cron Expression") do |val|
      params['cron'] = val
    end
    opts.on('--enabled [on|off]', String, "Can be used to disable it") do |val|
      params['enabled'] = !(val.to_s == 'off' || val.to_s == 'false')
    end
    build_common_options(opts, options, [:options, :payload, :json, :dry_run, :remote, :quiet])
    opts.footer = "Update a execute schedule." + "\n" +
                  "[name] is required. This is the name or id of a execute schedule."
  end
  optparse.parse!(args)
  if args.count != 1
    print_error Morpheus::Terminal.angry_prompt
    puts_error  "wrong number of arguments, expected 1 and got (#{args.count}) #{args.inspect}\n#{optparse}"
    return 1
  end
  connect(options)
  begin
    schedule = find_schedule_by_name_or_id(args[0])
    if schedule.nil?
      return 1
    end
    # construct payload
    payload = nil
    if options[:payload]
      payload = options[:payload]
    else
      # merge -O options into normally parsed options
      params.deep_merge!(options[:options].reject {|k,v| k.is_a?(Symbol) }) if options[:options]
      payload = {'schedule' => params}
    end
    @execute_schedules_interface.setopts(options)
    if options[:dry_run]
      print_dry_run @execute_schedules_interface.dry.update(schedule["id"], payload)
      return
    end
    json_response = @execute_schedules_interface.update(schedule["id"], payload)
    if options[:json]
      puts as_json(json_response, options)
    elsif !options[:quiet]
      print_green_success "Updated execute schedule #{schedule['name']}"
      _get(schedule['id'], {})
    end
    return 0
  rescue RestClient::Exception => e
    print_rest_exception(e, options)
    return 1
  end
end