Advertisement
Guest User

Untitled

a guest
Oct 16th, 2018
80
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Ruby 5.72 KB | None | 0 0
  1. #### cookbooks/cook_book_one/libraries/partial_search-lib.rb
  2.  
  3. require 'chef/config'
  4. require 'chef/server_api'
  5. require 'chef/http'
  6. require 'uri'
  7. # These are needed so that JSON can inflate search results
  8.  
  9. require 'chef/node'
  10. require 'chef/role'
  11. require 'chef/environment'
  12. require 'chef/data_bag'
  13. require 'chef/data_bag_item'
  14.  
  15. class Chef
  16.   class PartialSearch
  17.  
  18.     attr_accessor :rest
  19.  
  20.     def initialize(url=nil)
  21.       @rest = ::Chef::ServerAPI.new(url || ::Chef::Config[:chef_server_url])
  22.     end
  23.  
  24.     # Search Solr for objects of a given type, for a given query. If you give
  25.     # it a block, it will handle the paging for you dynamically.
  26.     def search(type, query='*:*', args={}, &block)
  27.       raise ArgumentError, "Type must be a string or a symbol!" unless (type.kind_of?(String) || type.kind_of?(Symbol))
  28.  
  29.       sort = args.include?(:sort) ? args[:sort] : 'X_CHEF_id_CHEF_X asc'
  30.       start = args.include?(:start) ? args[:start] : 0
  31.       rows = args.include?(:rows) ? args[:rows] : 1000
  32.       query_string = "search/#{type}?q=#{escape(query)}&sort=#{escape(sort)}&start=#{escape(start)}&rows=#{escape(rows)}"
  33.       if args[:keys]
  34.         response = @rest.post(query_string, args[:keys])
  35.         response_rows = response['rows'].map { |row| row['data'] }
  36.       else
  37.         response = @rest.get(query_string)
  38.         response_rows = response['rows']
  39.       end
  40.       if block
  41.         response_rows.each { |o| block.call(o) unless o.nil?}
  42.         unless (response["start"] + response_rows.length) >= response["total"]
  43.           nstart = response["start"] + rows
  44.           args_hash = {
  45.             :keys => args[:keys],
  46.             :sort => sort,
  47.             :start => nstart,
  48.             :rows => rows
  49.           }
  50.           search(type, query, args_hash, &block)
  51.         end
  52.         true
  53.       else
  54.         [ response_rows, response["start"], response["total"] ]
  55.       end
  56.     end
  57.  
  58.     def list_indexes
  59.       response = @rest.get("search")
  60.     end
  61.  
  62.     private
  63.       def escape(s)
  64.         s && URI.escape(s.to_s)
  65.       end
  66.   end
  67. end
  68.  
  69. # partial_search(type, query, options, &block)
  70. #    
  71. # Searches for nodes, roles, etc. and returns the results.  This method may
  72. # perform more than one search request, if there are a large number of results.
  73. #
  74. # ==== Parameters
  75. # * +type+: index type (:role, :node, :client, :environment, data bag name)
  76. # * +query+: SOLR query.  "*:*", "role:blah", "not role:blah", etc.  Defaults to '*:*'
  77. # * +options+: hash with options:
  78. # ** +:start+: First row to return (:start => 50, :rows => 100 means "return the
  79. #               50th through 150th result")
  80. # ** +:rows+: Number of rows to return.  Defaults to 1000.
  81. # ** +:sort+: a SOLR sort specification.  Defaults to 'X_CHEF_id_CHEF_X asc'.
  82. # ** +:keys+: partial search keys.  If this is not specified, the search will
  83. #             not be partial.
  84. #
  85. # ==== Returns
  86. #
  87. # This method returns an array of search results.  Partial search results will
  88. # be JSON hashes with the structure specified in the +keys+ option.  Other
  89. # results include +Chef::Node+, +Chef::Role+, +Chef::Client+, +Chef::Environment+,
  90. # +Chef::DataBag+ and +Chef::DataBagItem+ objects, depending on the search type.
  91. #
  92. # If a block is specified, the block will be called with each result instead of
  93. # returning an array.  This method will not block if it returns
  94. #
  95. # If start or row is specified, and no block is given, the result will be a
  96. # triple containing the list, the start and total:
  97. #
  98. #     [ [ row1, row2, ... ], start, total ]
  99. #
  100. # ==== Example
  101. #
  102. #     partial_search(:node, 'role:webserver',
  103. #                    keys: {
  104. #                      name: [ 'name' ],
  105. #                      ip: [ 'amazon', 'ip', 'public' ]
  106. #                    }
  107. #     ).each do |node|
  108. #       puts "#{node[:name]}: #{node[:ip]}"
  109. #     end
  110. #
  111. def partial_search(type, query='*:*', *args, &block)
  112.   # Support both the old (positional args) and new (hash args) styles of calling
  113.   if args.length == 1 && args[0].is_a?(Hash)
  114.     args_hash = args[0]
  115.   else
  116.     args_hash = {}
  117.     args_hash[:sort] = args[0] if args.length >= 1
  118.     args_hash[:start] = args[1] if args.length >= 2
  119.     args_hash[:rows] = args[2] if args.length >= 3
  120.   end
  121.   # If you pass a block, or have the start or rows arguments, do raw result parsing
  122.   if Kernel.block_given? || args_hash[:start] || args_hash[:rows]
  123.     Chef::PartialSearch.new.search(type, query, args_hash, &block)
  124.   # Otherwise, do the iteration for the end user
  125.   else
  126.     results = Array.new
  127.     Chef::PartialSearch.new.search(type, query, args_hash) do |o|
  128.       results << o
  129.     end
  130.     results
  131.   end
  132. end
  133.  
  134.  
  135.  
  136. #### cookbooks/cook_book_two/recipes/setbroker.rb
  137.  
  138. ## Dinamically setting broker ##
  139. ruby_block "add-known-hosts" do
  140.     block do
  141.       search = "chef_environment:#{node.environment()} AND role:com_broker_gr "
  142.       broker_list = {}
  143.       broker_fqdn_ip_list = {}
  144.       partial_search(:node, search, :key => {'ipaddress' => ['ipaddress'], 'fqdn' => ['fqdn'], 'zone' => ['zone']}).each do |broker|
  145.         broker_list[broker['zone']] ||= []
  146.         broker_list[broker['zone']] << broker['fqdn']
  147.         broker_fqdn_ip_list[broker['zone']] ||= {}
  148.         broker_fqdn_ip_list[broker['zone']][broker['fqdn']] = broker['ipaddress']
  149.       end
  150.       if broker_list.empty?
  151.         raise "Unable to automaticaly define broker list"
  152.       else
  153.         broker_list.each do |zone,fqdn_list|
  154.           if fqdn_list.empty?
  155.             raise "Broker list for #{zone} zone is empty!"
  156.           else
  157.             node.override['reach-com_broker']['hosts'][zone] = fqdn_list.sort
  158.           end
  159.         end
  160.         node.override['reach-com_broker']['hosts_addr'] = broker_fqdn_ip_list
  161.       end
  162.     end
  163.     action :run
  164. end
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement