Class: Chimp::Chimp

Inherits:
Object
  • Object
show all
Defined in:
lib/right_chimp/Chimp.rb

Constant Summary collapse

@@verbose =

These class variables control verbosity

false
@@quiet =
false

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initializeChimp

Set up reasonable defaults



21
22
23
24
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
70
71
72
73
74
75
76
77
78
79
80
81
82
# File 'lib/right_chimp/Chimp.rb', line 21

def initialize
  #
  # General configuration options
  #
  @progress     = false
  @prompt       = true
  @verify       = true
  @dry_run      = false
  @interactive  = true

  #
  # Job control options
  #
  @concurrency  = 1
  @delay        = 0
  @retry_count  = 0
  @hold         = false
  @timeout      = 900

  @limit_start  = 0
  @limit_end    = 0

  #
  # Action configuration
  #
  @action            = :action_none
  @group             = :default
  @group_type        = :parallel
  @group_concurrency = 1

  #
  # Options for selecting objects to work on
  #
  @current          = true
  @match_all        = true
  @servers          = []
  @arrays           = []
  @tags             = []
  @array_names      = []
  @deployment_names = []
  @template         = nil
  @script           = nil
  @ssh              = nil
  @ssh_user         = "rightscale"
  @report           = nil
  @inputs           = {}
  @set_tags         = []
  @ignore_errors    = false

  @break_array_into_instances = false
  @dont_check_templates_for_script = false

  #
  # chimpd configuration
  #
  @use_chimpd                 = false
  @chimpd_host                = 'localhost'
  @chimpd_port                = 9055
  @chimpd_wait_until_done     = false

  RestClient.log = nil
end

Instance Attribute Details

#actionObject

Returns the value of attribute action.



7
8
9
# File 'lib/right_chimp/Chimp.rb', line 7

def action
  @action
end

#array_namesObject

Returns the value of attribute array_names.



7
8
9
# File 'lib/right_chimp/Chimp.rb', line 7

def array_names
  @array_names
end

#chimpd_hostObject

Returns the value of attribute chimpd_host.



7
8
9
# File 'lib/right_chimp/Chimp.rb', line 7

def chimpd_host
  @chimpd_host
end

#chimpd_portObject

Returns the value of attribute chimpd_port.



7
8
9
# File 'lib/right_chimp/Chimp.rb', line 7

def chimpd_port
  @chimpd_port
end

#concurrencyObject

Returns the value of attribute concurrency.



7
8
9
# File 'lib/right_chimp/Chimp.rb', line 7

def concurrency
  @concurrency
end

#delayObject

Returns the value of attribute delay.



7
8
9
# File 'lib/right_chimp/Chimp.rb', line 7

def delay
  @delay
end

#deployment_namesObject

Returns the value of attribute deployment_names.



7
8
9
# File 'lib/right_chimp/Chimp.rb', line 7

def deployment_names
  @deployment_names
end

#dry_runObject

Returns the value of attribute dry_run.



7
8
9
# File 'lib/right_chimp/Chimp.rb', line 7

def dry_run
  @dry_run
end

#groupObject

Returns the value of attribute group.



7
8
9
# File 'lib/right_chimp/Chimp.rb', line 7

def group
  @group
end

#holdObject

Returns the value of attribute hold.



7
8
9
# File 'lib/right_chimp/Chimp.rb', line 7

def hold
  @hold
end

#interactiveObject

Returns the value of attribute interactive.



7
8
9
# File 'lib/right_chimp/Chimp.rb', line 7

def interactive
  @interactive
end

#job_idObject

Always returns 0. Used for chimpd compatibility.



893
894
895
# File 'lib/right_chimp/Chimp.rb', line 893

def job_id
  @job_id
end

#limit_endObject

Returns the value of attribute limit_end.



7
8
9
# File 'lib/right_chimp/Chimp.rb', line 7

def limit_end
  @limit_end
end

#limit_startObject

Returns the value of attribute limit_start.



7
8
9
# File 'lib/right_chimp/Chimp.rb', line 7

def limit_start
  @limit_start
end

#progressObject

Returns the value of attribute progress.



7
8
9
# File 'lib/right_chimp/Chimp.rb', line 7

def progress
  @progress
end

#promptObject

Returns the value of attribute prompt.



7
8
9
# File 'lib/right_chimp/Chimp.rb', line 7

def prompt
  @prompt
end

#quietObject

Returns the value of attribute quiet.



7
8
9
# File 'lib/right_chimp/Chimp.rb', line 7

def quiet
  @quiet
end

#reportObject

Returns the value of attribute report.



7
8
9
# File 'lib/right_chimp/Chimp.rb', line 7

def report
  @report
end

#retry_countObject

Returns the value of attribute retry_count.



7
8
9
# File 'lib/right_chimp/Chimp.rb', line 7

def retry_count
  @retry_count
end

#scriptObject

Returns the value of attribute script.



7
8
9
# File 'lib/right_chimp/Chimp.rb', line 7

def script
  @script
end

#serversObject

Returns the value of attribute servers.



7
8
9
# File 'lib/right_chimp/Chimp.rb', line 7

def servers
  @servers
end

#sshObject

Returns the value of attribute ssh.



7
8
9
# File 'lib/right_chimp/Chimp.rb', line 7

def ssh
  @ssh
end

#tagsObject

Returns the value of attribute tags.



7
8
9
# File 'lib/right_chimp/Chimp.rb', line 7

def tags
  @tags
end

#use_chimpdObject

Returns the value of attribute use_chimpd.



7
8
9
# File 'lib/right_chimp/Chimp.rb', line 7

def use_chimpd
  @use_chimpd
end

#verify=(value) ⇒ Object

Sets the attribute verify

Parameters:

  • value

    the value to set the attribute verify to.



7
8
9
# File 'lib/right_chimp/Chimp.rb', line 7

def verify=(value)
  @verify = value
end

Class Method Details

.set_verbose(v = true, q = false) ⇒ Object

Configure the Log object



958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
# File 'lib/right_chimp/Chimp.rb', line 958

def self.set_verbose(v=true, q=false)
  @@verbose = v
  @@quiet = q

  STDOUT.sync = true
  STDERR.sync = true

  if @@verbose == true
    Log.threshold = Logger::DEBUG
  elsif @@quiet == true
    Log.threshold = Logger::WARN
  else
    Log.threshold = Logger::INFO
  end
end

.verbose?Boolean

Returns:

  • (Boolean)


974
975
976
# File 'lib/right_chimp/Chimp.rb', line 974

def self.verbose?
  return @@verbose
end

Instance Method Details

#add_to_queue(a) ⇒ Object



739
740
741
# File 'lib/right_chimp/Chimp.rb', line 739

def add_to_queue(a)
  a.each { |task| ChimpQueue.instance.push(@group, task) }
end

#check_option_validityObject

Check for any invalid combinations of command line options



344
345
346
347
348
349
350
351
352
353
354
355
356
# File 'lib/right_chimp/Chimp.rb', line 344

def check_option_validity
  if @tags.empty? and @array_names.empty? and @deployment_names.empty? and not @chimpd_wait_until_done
    puts "ERROR: Please select the objects to operate upon."
    help
    exit 1
  end

  if not @array_names.empty? and ( not @tags.empty? or not @deployment_names.empty? )
    puts "ERROR: You cannot mix ServerArray queries with other types of queries."
    help
    exit 1
  end
end

#chimpd_wait_until_doneObject

Connect to chimpd and wait for the work queue to empty, and prompt the user if there are any errors.



901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
# File 'lib/right_chimp/Chimp.rb', line 901

def chimpd_wait_until_done
  local_queue = ChimpQueue.instance
  $stdout.print "Waiting for chimpd jobs to complete for group #{@group}..."

  begin
    while !@dry_run
      local_queue = ChimpQueue.instance

      #
      # load up remote chimpd jobs into the local queue
      # this makes all the standard queue control methods available to us
      #
      while true
        local_queue.reset!

        begin
          all = ChimpDaemonClient.retrieve_group_info(@chimpd_host, @chimpd_port, @group, :all)
        rescue RestClient::ResourceNotFound
          sleep 5
          retry
        end

        ChimpQueue.instance.create_group(@group)
        ChimpQueue[@group].set_jobs(all)

        break if ChimpQueue[@group].done?

        $stdout.print "."
        $stdout.flush
        sleep 5
      end

      #
      # If verify_results returns true, then ask chimpd to requeue all failed jobs.
      #
      if verify_results(@group)
        break
      else
        ChimpDaemonClient.retry_group(@chimpd_host, @chimpd_port, @group)
      end
    end
  ensure
    #$stdout.print " done\n"
  end
end

#detect_right_script(st, script) ⇒ Object

Look up the RightScript

Returns: RestConnection::Executable



534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
# File 'lib/right_chimp/Chimp.rb', line 534

def detect_right_script(st, script)
  executable = nil

  if script == ""
    if not @interactive
      puts "Error: empty --script= option is supported only in interactive mode. Exiting."
      exit 1
    end
    # Find operational scripts that exist in this server template
    op_script_names = ['dummy name']      # Placeholder for #0 since we want to offer choices 1..n
    op_script_hrefs = [ 'dummy href' ]
    st.executables.each do |ex|
        if ex.apply == "operational"
          op_script_names.push( ex.name )
          op_script_hrefs.push( ex.href )
        end
    end
    if op_script_names.length <= 1
      puts "Warning: No operational scripts found on the server(s). "
      puts "         (Search performed on server template '#{st.nickname}')"
    else
      puts "List of available operational scripts in the server template: ('#{st.nickname}')"
      puts "------------------------------------------------------------"
      for i in 1..op_script_names.length - 1
        puts "  %3d. #{op_script_names[i]}" % i
      end
      puts "------------------------------------------------------------"
      while true
        printf "Type the number of the script to run and press Enter (Ctrl-C to quit): "
        op_script_id = Integer(gets.chomp) rescue -1
        if op_script_id > 0 && op_script_id < op_script_names.length
          puts "Script choice: #{op_script_id}. #{op_script_names[ op_script_id ]}"
          break
        else
          puts "#{op_script_id < 0 ? 'Invalid input' : 'Input out of range'}."
        end
      end
      # Provide the href as the input for the block that will do the lookup
      script = op_script_hrefs[ op_script_id ]
    end
  end

  if script
    if script =~ /^http/ or script =~ /^\d+$/
      if script =~ /^\d+$/
        url_prefix = st.params['href'].match( /^.*\/acct\/\d+/)[0]  # extract the 'https://my.rightscale.com/api/acct/<account_id>' part from the template's href
        script = url_prefix + "/right_scripts/#{script}"
      end
      script_URI = script
      Log.debug "Looking for script href \"#{script_URI}\""
      puts
      # First look up the script URI in the template.
      # It *will* be found if we came here from the 'if script = ""' block
      script = st.executables.detect { |ex| ex.href == script }
      if not script
         script_obj = ::RightScript.find(script_URI)
         script_data = {}
         script_data[ 'name' ] = script_obj.params['name']
         script = ::RightScript.new({ :href => script_URI, :right_script => script_data })
      end
    else
      Log.debug "Looking for script \"#{script}\""
      script = st.executables.detect { |ex| ex.name =~ /#{script}/ }
    end

   if script != nil and script['right_script'] != nil
     puts "RightScript: \"#{script['right_script']['name']}\"" if @interactive
   else
     puts "No matching RightScript found!"
     raise "No matching RightScript found!"
   end

   executable = script
  end

  return(executable)
end

#detect_server_template(template, script, servers, array_names_to_detect) ⇒ Object

ServerTemplate auto-detection

Returns: RestConnection::ServerTemplate



477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
# File 'lib/right_chimp/Chimp.rb', line 477

def detect_server_template(template, script, servers, array_names_to_detect)
  st = nil

  #
  # If we have a script name but no template, check
  # each server for the script until we locate it.
  #
  if script and template == nil
    Log.debug "Getting template URI..."

    if not servers.empty?
      for i in (0..servers.size - 1)

        template = servers[i]['server_template_href'] if not servers[i].empty?
        break if template
      end

    elsif not array_names_to_detect.empty?
      array_names_to_detect.each do |array_name|
        a = Ec2ServerArray.find_by(:nickname) { |n| n =~ /^#{array_name}/i }.first
        next unless a
        template = a['server_template_href']
        break if template
      end
    end

    raise "Unable to locate ServerTemplate!" unless template
    Log.debug "Template: #{template}"
  end

  #
  # Now look up the ServerTemplate via the RightScale API
  #
  if template
    Log.debug "Looking up template..."

    if template =~ /^http/
      st = ::ServerTemplate.find(template)
    else
      st = ::ServerTemplate.find_by_nickname(template).first
    end

    if st == nil
      raise "No matching ServerTemplate found!"
    else
      Log.debug "ServerTemplate: \"#{st['nickname']}\""
    end
  end

  return(st)
end

#disable_loggingObject

Disable rest_connection logging



950
951
952
953
# File 'lib/right_chimp/Chimp.rb', line 950

def disable_logging
  ENV['REST_CONNECTION_LOG'] = "/dev/null"
  ENV['RESTCLIENT_LOG'] = "/dev/null"
end

#do_workObject

Do work: either by submitting to chimpd or running it ourselves.



858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
# File 'lib/right_chimp/Chimp.rb', line 858

def do_work
  done = false

  while not done
    queue_runner(@concurrency, @delay, @retry_count, @progress)

    if @interactive and @verify
      done = verify_results(@group)
    else
      done = true
    end
  end

  if not @verify
    failed_workers, results_display = get_results(group)
    exit 1 if failed_workers.size > 0
  end

  puts "chimp run complete"
end

#filter_out_non_operational_servers(servers) ⇒ Object

Filter out non-operational servers Then add operational servers to the list of objects to display



848
849
850
851
852
# File 'lib/right_chimp/Chimp.rb', line 848

def filter_out_non_operational_servers(servers)
  Log.debug "Filtering out non-operational servers..."
  servers.reject! { |s| s == nil || s['state'] != "operational" }
  return(servers)
end

#generate_jobs(queue_servers, queue_arrays, queue_template, queue_executable) ⇒ Object

Load up the queue with work

FIXME this needs to be refactored



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
# File 'lib/right_chimp/Chimp.rb', line 617

def generate_jobs(queue_servers, queue_arrays, queue_template, queue_executable)
  counter = 0
  tasks = []
  Log.debug "Loading queue..."

  #
  # Configure group
  #
  if not ChimpQueue[@group]
    ChimpQueue.instance.create_group(@group, @group_type, @group_concurrency)
  end

  #
  # Process ServerArray selection
  #
  Log.debug("processing queue selection")
  if not queue_arrays.empty?
    queue_arrays.each do |array|
      instances = filter_out_non_operational_servers(array.instances)

      if not instances
        Log.error("no instances in array!")
        break
      end

      instances.each do |array_instance|
        #
        # Handle limiting options
        #
        counter += 1
        next if @limit_start.to_i > 0 and counter < @limit_start.to_i
        break if @limit_end.to_i > 0 and counter > @limit_end.to_i
        a = ExecArray.new(
          :array => array,
          :server => array_instance,
          :exec => queue_executable,
          :inputs => @inputs,
          :template => queue_template,
          :timeout => @timeout,
          :verbose => @@verbose,
          :quiet => @@quiet
        )
        a.dry_run = @dry_run
        ChimpQueue.instance.push(@group, a)
      end
    end
  end

  #
  # Process Server selection
  #
  Log.debug("Processing server selection")

  queue_servers.sort! { |a,b| a['nickname'] <=> b['nickname'] }
  queue_servers.each do |server|

    #
    # Handle limiting options
    #
    counter += 1
    next if @limit_start.to_i > 0 and counter < @limit_start.to_i
    break if @limit_end.to_i > 0 and counter > @limit_end.to_i

    #
    # Construct the Server object
    #
    s = ::Server.new
    s.href = server['href']
    s.current_instance_href = server['current_instance_href']
    s.name = server['nickname'] || server['name']
    s.nickname = s.name
    s.ip_address = server['ip-address'] || server['ip_address']
    e = nil

    if queue_executable
      e = ExecRightScript.new(
        :server => s,
        :exec => queue_executable,
        :inputs => @inputs,
        :timeout => @timeout,
        :verbose => @@verbose,
        :quiet => @@quiet
      )
    elsif @ssh
      e = ExecSSH.new(
        :server => s,
        :ssh_user => @ssh_user,
        :exec => @ssh,
        :verbose => @@verbose,
        :quiet => @@quiet
      )
    elsif queue_template and not clone
      e = ExecSetTemplate.new(
        :server => s,
        :template => queue_template,
        :verbose => @@verbose,
        :quiet => @@quiet
      )
    elsif @report
      if s.href
        s.href = s.href.sub("/current","")
        e = ExecReport.new(:server => s, :verbose => @@verbose, :quiet => @@quiet)
        e.fields = @report
      end
    elsif @set_tags.size > 0
      e = ExecSetTags.new(:server => s, :verbose => @@verbose, :quiet => @@quiet)
      e.tags = set_tags
    end

    if e != nil
      e.dry_run = @dry_run
      e.quiet   = @@quiet
      e.status  = Executor::STATUS_HOLDING if @hold

      tasks.push(e)
    end

  end

  return(tasks)
end

#get_array_infoObject

Load up @array with server arrays to operate on



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
# File 'lib/right_chimp/Chimp.rb', line 372

def get_array_info
  return if @array_names.empty?

  #
  # Some operations (e.g. ExecSSH) require individual server information.
  # Check for @break_array_into_instances and break up the ServerArray
  # into Servers as necessary.
  #
  if @break_array_into_instances
    Log.debug "Breaking array into instances..."
    @servers += get_servers_by_array(@array_names)
    @array_names = []
  end

  @array_names.each do |array_name|
    Log.debug "Querying API for ServerArray \'#{array_name}\'..."
    a = Ec2ServerArray.find_by(:nickname) { |n| n =~ /^#{array_name}/i }.first
    if not a.nil?
      @arrays << a
    else
      if @ignore_errors
        Log.warn "cannot find ServerArray #{array_name}"
      else
        raise "cannot find ServerArray #{array_name}"
      end
    end
  end
end

#get_executable_infoObject

Get the Executable (RightScript) info from the API



178
179
180
181
182
183
# File 'lib/right_chimp/Chimp.rb', line 178

def get_executable_info
  if not (@servers.empty? and @array_names.empty?)
    @executable = detect_right_script(@server_template, @script)
    puts "Using SSH command: \"#{@ssh}\"" if @action == :action_ssh
  end
end

#get_failuresObject



840
841
842
# File 'lib/right_chimp/Chimp.rb', line 840

def get_failures
  return get_results(@group)
end

#get_results(group_name) ⇒ Object

Get the results from the QueueRunner and format them in a way that’s easy to display to the user



812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
# File 'lib/right_chimp/Chimp.rb', line 812

def get_results(group_name)
  queue = ChimpQueue.instance
  Log.debug("getting results for group #{group_name}")
  results = queue.group[@group].results()
  failed_workers = []
  results_display = []

  results.each do |result|
    next if result == nil

    if result[:status] == :error
      name = result[:host] || "unknown"
      message = result[:error].to_s || "unknown"
      message.sub!("\n", "")
      failed_workers << result[:worker]
      results_display << "#{name.ljust(40)} #{message}"
    end
  end

  return [failed_workers, results_display]
end

#get_server_infoObject

Go through each of the various ways to specify servers via the command line (tags, deployments, etc.) and get all the info needed from the RightScale API.



363
364
365
366
367
# File 'lib/right_chimp/Chimp.rb', line 363

def get_server_info
  @servers += get_servers_by_tag(@tags)
  @servers += get_servers_by_deployment(@deployment_names)
  @servers = filter_out_non_operational_servers(@servers)
end

#get_servers_by_array(names) ⇒ Object

Parse array names

Returns: array of RestConnection::Server objects



455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
# File 'lib/right_chimp/Chimp.rb', line 455

def get_servers_by_array(names)
  array_servers = []
  if names.size > 0
    names.each do |array_name|
      all_arrays = ::Ec2ServerArray.find_by(:nickname) { |n| n =~ /^#{array_name}/i }

      if all_arrays != nil and all_arrays.first != nil
        all_arrays.first.instances.each do |s|
          array_servers << s
        end
      end
    end
  end

  return(array_servers)
end

#get_servers_by_deployment(names) ⇒ Object

Parse deployment names and get Server objects

Returns: array of RestConnection::Server objects



426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
# File 'lib/right_chimp/Chimp.rb', line 426

def get_servers_by_deployment(names)
  servers = []

  if names.size > 0
    names.each do |deployment|
      d = ::Deployment.find_by_nickname(deployment).first

      if d == nil
        if @ignore_errors
          Log.warn "cannot find deployment #{deployment}"
        else
          raise "cannot find deployment #{deployment}"
        end
      else
        d.servers_no_reload.each do |s|
          servers << s
        end
      end
    end
  end

  return(servers)
end

#get_servers_by_tag(tags) ⇒ Object

Get servers to operate on via a tag query

Returns: array of RestConnection::Server objects



406
407
408
409
410
411
412
413
414
415
416
417
418
419
# File 'lib/right_chimp/Chimp.rb', line 406

def get_servers_by_tag(tags)
  return([]) unless tags.size > 0
  servers = ::Tag.search("ec2_instance", tags, :match_all => @match_all)

  if tags.size > 0 and servers.nil? or servers.empty?
    if @ignore_errors
      Log.warn "Tag query returned no results: #{tags.join(" ")}"
    else
       raise "Tag query returned no results: #{tags.join(" ")}"
    end
  end

  return(servers)
end

#get_template_infoObject

Get the ServerTemplate info from the API



169
170
171
172
173
# File 'lib/right_chimp/Chimp.rb', line 169

def get_template_info
  if not (@servers.empty? and @array_names.empty?)
    @server_template = detect_server_template(@template, @script, @servers, @array_names)
  end
end

#parse_command_lineObject

Parse command line options



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
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
# File 'lib/right_chimp/Chimp.rb', line 188

def parse_command_line
  begin
    opts = GetoptLong.new(
      [ '--tag', '-t', GetoptLong::REQUIRED_ARGUMENT ],
      [ '--tag-use-and', '-a', GetoptLong::NO_ARGUMENT ],
      [ '--tag-use-or', '-o', GetoptLong::NO_ARGUMENT ],
      [ '--array', '-r', GetoptLong::REQUIRED_ARGUMENT ],
      [ '--deployment', '-e', GetoptLong::REQUIRED_ARGUMENT ],
      [ '--script', '-s', GetoptLong::OPTIONAL_ARGUMENT ],
      [ '--ssh', '-x', GetoptLong::OPTIONAL_ARGUMENT ],
      [ '--input', '-i', GetoptLong::REQUIRED_ARGUMENT ],
      [ '--set-template', '-m', GetoptLong::REQUIRED_ARGUMENT ],
      [ '--set-tag', '-w', GetoptLong::REQUIRED_ARGUMENT ],
      [ '--report', '-b', GetoptLong::REQUIRED_ARGUMENT ],
      [ '--progress', '-p', GetoptLong::NO_ARGUMENT ],
      [ '--verbose', '-v', GetoptLong::NO_ARGUMENT ],
      [ '--quiet', '-q', GetoptLong::NO_ARGUMENT ],
      [ '--noprompt', '-z', GetoptLong::NO_ARGUMENT ],
      [ '--concurrency', '-c', GetoptLong::REQUIRED_ARGUMENT ],
      [ '--delay', '-d', GetoptLong::REQUIRED_ARGUMENT ],
      [ '--retry', '-y', GetoptLong::REQUIRED_ARGUMENT ],
      [ '--hold', '-7', GetoptLong::NO_ARGUMENT ],
      [ '--dry-run', '-n', GetoptLong::NO_ARGUMENT ],
      [ '--limit', '-l', GetoptLong::REQUIRED_ARGUMENT ],
      [ '--version', '-1', GetoptLong::NO_ARGUMENT ],
      [ '--chimpd', '-f', GetoptLong::OPTIONAL_ARGUMENT ],
      [ '--chimpd-wait-until-done', '-j', GetoptLong::NO_ARGUMENT ],
      [ '--dont-check-templates', '-0', GetoptLong::NO_ARGUMENT ],
      [ '--ignore-errors', '-9', GetoptLong::NO_ARGUMENT ],
      [ '--ssh-user', '-u', GetoptLong::REQUIRED_ARGUMENT ],
      [ '--help', '-h', GetoptLong::NO_ARGUMENT ],
      [ '--group', '-g', GetoptLong::REQUIRED_ARGUMENT ],
      [ '--group-type', '-2', GetoptLong::REQUIRED_ARGUMENT ],
      [ '--group-concurrency', '-3', GetoptLong::REQUIRED_ARGUMENT ],
      [ '--timing-log', '-4', GetoptLong::REQUIRED_ARGUMENT ],
      [ '--timeout', '-5',  GetoptLong::REQUIRED_ARGUMENT ],
      [ '--noverify', '-6', GetoptLong::NO_ARGUMENT ]
    )

    opts.each do |opt, arg|
      case opt
        when '--help', '-h'
          help
          exit 0
        when '--tag', '-t'
          @tags << arg
        when '--tag-use-and', '-a'
          @match_all = true
        when '--tag-use-or', '-o'
          @match_all = false
        when '--array', '-a'
          @array_names << arg
        when '--deployment', '-e'
          @deployment_names << arg
        when '--template', '-m'
          @template = arg
        when '--script', '-s'
          set_action(:action_rightscript)
          if arg == ""
            # Empty but not nil means show list of operational scripts to choose from
            @script = ""
          else
            @script = arg
          end
        when '--ssh', '-x'
          set_action(:action_ssh)
          @break_array_into_instances = true
          if arg == ""
            print "Enter SSH command line to execute: "
            @ssh = gets.chomp
          else
            @ssh = arg
          end
        when '--ssh-user', '-u'
          @ssh_user = arg
        when '--input', '-i'
          arg =~ /(.+)=(.+)/
          @inputs[$1]=$2
        when '--set-template', '-m'
          set_action(:action_set)
          @template = arg
        when '--set-tag', '-w'
          set_action(:action_set)
          @set_tags << arg
        when '--report', '-b'
          set_action(:action_report)
          @report = arg
          @@verbose = false
          @@quiet = true
          @break_array_into_instances = true
          @concurrency = 5 if @concurrency == 1
        when '--progress', '-p'
          @progress = @progress ? false : true
        when '--noprompt', '-z'
          @prompt = false
        when '--concurrency', '-c'
          @concurrency = arg.to_i
        when '--delay', '-d'
          @delay = arg.to_i
        when '--hold', '-7'
          @hold = true
        when '--retry', '-y'
          @retry_count = arg.to_i
        when '--limit', '-l'
          @limit_start, @limit_end = arg.split(',')
        when '--verbose', '-v'
          @@verbose = true
        when '--quiet', '-q'
          @@quiet = true
        when '--dont-check-templates', '-0'
          @dont_check_templates_for_script = true
        when '--version'
          puts VERSION
          exit 0
        when '--chimpd'
          @use_chimpd = true
          @chimpd_port = arg.to_i unless arg.empty?
        when '--chimpd-wait-until-done'
          @use_chimpd = true
          @chimpd_wait_until_done = true
        when '--dry-run', '-n'
          @dry_run = true
        when '--ignore-errors', '-9'
          @ignore_errors = true
        when '--group', '-g'
          @group = arg.to_sym
        when '--group-type'
          @group_type = arg.to_sym
        when '--group-concurrency'
          @group_concurrency = arg.to_i
        when '--timing-log'
          @timing_log = arg
        when '--timeout'
          @timeout = arg
        when '--noverify'
          @verify = false
      end
    end
  rescue GetoptLong::InvalidOption => ex
    help
    exit 1
  end

  #
  # Before we're totally done parsing command line options,
  # let's make sure that a few things make sense
  #
  if @group_concurrency > @concurrency
    @concurrency = @group_concurrency
  end

end


834
835
836
837
838
# File 'lib/right_chimp/Chimp.rb', line 834

def print_timings
  ChimpQueue.instance.group[@group].results.each do |task|
    puts "Host: #{task[:host]} Type: #{task[:name]} Time: #{task[:total]} seconds"
  end
end

#processObject

Completely process a non-interactive chimp object command



157
158
159
160
161
162
163
164
# File 'lib/right_chimp/Chimp.rb', line 157

def process
  get_array_info
  get_server_info
  get_template_info
  get_executable_info
  jobs = generate_jobs(@servers, @arrays, @server_template, @executable)
  return(jobs)
end

#queue_runner(concurrency, delay, retry_count, progress) ⇒ Object

Execute the user’s command and provide for retrys etc.



746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
# File 'lib/right_chimp/Chimp.rb', line 746

def queue_runner(concurrency, delay, retry_count, progress)
  queue = ChimpQueue.instance
  queue.max_threads = concurrency
  queue.delay = delay
  queue.retry_count = retry_count
  total_queue_size = queue.size

  puts "Executing..." unless progress or not quiet
  pbar = ProgressBar.new("Executing", 100) if progress
  queue.start

  queue.wait_until_done(@group) do
    pbar.set(((total_queue_size.to_f - queue.size.to_f)/total_queue_size.to_f*100).to_i) if progress
  end

  pbar.finish if progress
end

#runObject

Entry point for the chimp command line application



87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
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
# File 'lib/right_chimp/Chimp.rb', line 87

def run
  queue = ChimpQueue.instance

  parse_command_line if @interactive
  check_option_validity if @interactive
  disable_logging unless @@verbose

  puts "chimp #{VERSION} executing..." if (@interactive and not @use_chimpd) and not @@quiet

  #
  # Wait for chimpd to complete tasks
  #
  if @chimpd_wait_until_done
    chimpd_wait_until_done
    exit
  end

  #
  # Send the command to chimpd for execution
  #
  if @use_chimpd
    ChimpDaemonClient.submit(@chimpd_host, @chimpd_port, self)
    exit
  end

  #
  # If we're processing the command ourselves, then go
  # ahead and start making API calls to select the objects
  # to operate upon
  #
  get_array_info
  get_server_info
  get_template_info
  get_executable_info

  #
  # Optionally display the list of objects to operate on
  # and prompt the user
  #
  if @prompt and @interactive
    list_of_objects = make_human_readable_list_of_objects
    confirm = (list_of_objects.size > 0 and @action != :action_none) or @action == :action_none

    verify("Your command will be executed on the following:", list_of_objects, confirm)

    if @servers.length >= 2 and @server_template and @executable and not @dont_check_templates_for_script
      warn_if_rightscript_not_in_all_servers @servers, @server_template, @executable
    end
  end

  #
  # Load the queue with work
  #
  jobs = generate_jobs(@servers, @arrays, @server_template, @executable)
  add_to_queue(jobs)

  #
  # Exit early if there is nothing to do
  #
  if @action == :action_none or queue.group[@group].size == 0
    puts "No actions to perform." unless @@quiet
  else
    do_work
  end
end

#set_action(a) ⇒ Object

Set the action



767
768
769
770
# File 'lib/right_chimp/Chimp.rb', line 767

def set_action(a)
  raise ArgumentError.new "Cannot reset action" unless @action == :action_none
  @action = a
end

#verify_results(group = :default) ⇒ Object

Allow user to verify results and retry if necessary



775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
# File 'lib/right_chimp/Chimp.rb', line 775

def verify_results(group = :default)
  failed_workers, results_display = get_results(group)

  #
  # If no workers failed, then we're done.
  #
  return true if failed_workers.empty?

  #
  # Some workers failed; offer the user a chance to retry them
  #
  verify("The following objects failed:", results_display, false)

  while true
    puts "(R)etry failed jobs"
    puts "(A)bort chimp run"
    puts "(I)gnore errors and continue"
    command = gets()

    if command =~ /^a/i
      puts "Aborting!"
      exit 1
    elsif command =~ /^i/i
      puts "Ignoring errors and continuing"
      exit 0
    elsif command =~ /^r/i
      puts "Retrying..."
      ChimpQueue.instance.group[group].requeue_failed_jobs!
      return false
    end
  end
end