Class: Chef::Client
- Inherits:
-
Object
- Object
- Chef::Client
- Extended by:
- Mixin::Deprecation, Forwardable
- Defined in:
- lib/chef/client.rb
Overview
== Chef::Client The main object in a Chef run. Preps a Chef::Node and Chef::RunContext, syncs cookbooks if necessary, and triggers convergence.
Direct Known Subclasses
Constant Summary collapse
- CRYPT_EXPORTABLE =
0x00000001
- CERT_SYSTEM_STORE_LOCAL_MACHINE =
adding these certstore 65536 == 0x00010000 == CurrentUser certstore 131072 == 0x00020000 == LocalMachine Reference: https://github.com/chef/win32-certstore/blob/main/lib/win32/certstore/mixin/crypto.rb#L90
0x00020000
- CERT_SYSTEM_STORE_CURRENT_USER =
0x00010000
- CERT_SYSTEM_STORE_SERVICES =
0x00050000
- CERT_SYSTEM_STORE_USERS =
0x00060000
- STDOUT_FD =
This constant is part of a private API. You should avoid using this constant if possible, as it may be removed or be changed in the future.
IO stream that will be used as 'STDOUT' for formatters. Formatters are configured during
initialize
, so this provides a convenience for setting alternative IO stream during tests. STDOUT
- STDERR_FD =
This constant is part of a private API. You should avoid using this constant if possible, as it may be removed or be changed in the future.
IO stream that will be used as 'STDERR' for formatters. Formatters are configured during
initialize
, so this provides a convenience for setting alternative IO stream during tests. STDERR
Instance Attribute Summary collapse
-
#events ⇒ EventDispatch::Dispatcher
readonly
The event dispatcher for the Chef run, including any configured output formatters and event loggers.
-
#json_attribs ⇒ Hash
readonly
Extra node attributes that were applied to the node.
-
#local_context ⇒ Object
readonly
Returns the value of attribute local_context.
-
#logger ⇒ Object
readonly
Returns the value of attribute logger.
-
#ohai ⇒ Ohai::System
readonly
The ohai system used by this client.
-
#run_context ⇒ Chef::RunContext
readonly
The run context of the Chef run.
-
#run_status ⇒ Chef::RunStatus
readonly
The status of the Chef run.
-
#runner ⇒ Chef::Runner
The runner used to converge.
Class Method Summary collapse
-
.clear_notifications ⇒ Object
private
Clears all listeners for client run status events.
- .generate_pfx_package(cert_name, date) ⇒ Object
- .import_pfx_to_store(new_pfx) ⇒ Object
-
.run_completed_successfully_notifications ⇒ Array<Proc>
private
Listeners to be run when the client run completes successfully.
-
.run_failed_notifications ⇒ Array<Proc>
private
Listeners to be run when the client run fails.
-
.run_start_notifications ⇒ Array<Proc>
private
Listeners to be run when the client run starts.
- .update_key_and_register(cert_name, expiring_cert = nil) ⇒ Object
-
.when_run_completes_successfully(¬ification_block) {|run_status| ... } ⇒ Object
Add a listener for the 'client run success' event.
-
.when_run_fails(¬ification_block) {|run_status| ... } ⇒ Object
Add a listener for the 'client run failed' event.
-
.when_run_starts(¬ification_block) {|run_status| ... } ⇒ Object
Add a listener for the 'client run started' event.
Instance Method Summary collapse
-
#build_node ⇒ Chef::Node
private
Mutates the
node
object to prepare it for the chef run. -
#check_certstore_for_key(cert_name) ⇒ Object
In the brave new world of No Certs On Disk, we want to put the pem file into Keychain or the Certstore But is it already there? We're solving the multi-user scenario where both a system/admin user can run on the box but also someone without admin rights can also run correctly locally.
- #configure_event_loggers ⇒ Object private
- #configure_formatters ⇒ Object private
-
#converge(run_context) ⇒ Object
private
Converges all compiled resources.
-
#converge_and_save(run_context) ⇒ Object
private
Converge the node via and then save it if successful.
- #create_new_key_and_register(cert_name) ⇒ Object
-
#do_windows_admin_check ⇒ Object
private
Check if the user has Administrator privileges on windows.
-
#expanded_run_list ⇒ Chef::RunListExpansion
Expands the run list.
- #formatters_for_run ⇒ Object private
- #generate_pfx_package(cert_name, date) ⇒ Object
- #import_pfx_to_store(new_pfx) ⇒ Object
-
#initialize(json_attribs = nil, args = {}) ⇒ Client
constructor
Creates a new Chef::Client.
-
#load_node ⇒ Chef::Node
private
Instantiates a Chef::Node object, possibly loading the node's prior state when using chef-client.
-
#load_required_recipe(rest, run_context) ⇒ Object
private
Adds a required recipe as specified by the Chef Server.
-
#node ⇒ Chef::Node
The node represented by this client.
- #node=(value) ⇒ Object
-
#node_name ⇒ Object
private
Figure out the node name we are working with.
-
#policy_builder ⇒ Chef::PolicyBuilder::Policyfile, Chef::PolicyBuilder::ExpandNodeObject
private
The PolicyBuilder strategy for figuring out run list and cookbooks.
-
#register(client_name = node_name, config = Chef::Config) ⇒ Chef::ServerAPI
private
Determine our private key and set up the connection to the Chef server.
-
#rest ⇒ Object
private
Standard rest object for talking to the Chef Server.
-
#rest_clean ⇒ Object
private
A rest object with validate_utf8 set to false.
-
#run ⇒ Object
Do a full run for this Chef::Client.
-
#run_completed_successfully ⇒ Object
private
Callback to fire notifications that the run completed successfully.
-
#run_failed ⇒ Object
private
Callback to fire notifications that the Chef run failed.
-
#run_ohai ⇒ Object
private
Run ohai plugins.
-
#run_started ⇒ Object
private
Callback to fire notifications that the Chef run is starting.
-
#save_updated_node ⇒ Object
private
Save the updated node to Chef.
-
#setup_run_context ⇒ Object
private
Sets up the run context.
-
#setup_targetmode ⇒ Object
private
Setup conditions for Target Mode.
-
#sync_cookbooks ⇒ Object
private
Sync cookbooks to local cache.
- #update_key_and_register(cert_name) ⇒ Object
Methods included from Mixin::Deprecation
deprecated_attr, deprecated_attr_reader, deprecated_attr_writer, deprecated_ivar
Constructor Details
#initialize(json_attribs = nil, args = {}) ⇒ Client
Creates a new Chef::Client.
168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 |
# File 'lib/chef/client.rb', line 168 def initialize(json_attribs = nil, args = {}) @json_attribs = json_attribs || {} @logger = args.delete(:logger) || Chef::Log.with_child @ohai = Ohai::System.new(logger: logger) event_handlers = configure_formatters + configure_event_loggers event_handlers += Array(Chef::Config[:event_handlers]) @events = EventDispatch::Dispatcher.new(*event_handlers) # @todo it seems like a bad idea to be deletin' other peoples' hashes. @override_runlist = args.delete(:override_runlist) @specific_recipes = args.delete(:specific_recipes) @run_status = Chef::RunStatus.new(nil, events) if new_runlist = args.delete(:runlist) @json_attribs["run_list"] = new_runlist end end |
Instance Attribute Details
#events ⇒ EventDispatch::Dispatcher (readonly)
The event dispatcher for the Chef run, including any configured output formatters and event loggers.
TODO add stdout, stderr, and default formatters to Chef::Config so the defaults aren't calculated here. Remove force_logger and force_formatter from this code.
151 152 153 |
# File 'lib/chef/client.rb', line 151 def events @events end |
#json_attribs ⇒ Hash (readonly)
Extra node attributes that were applied to the node.
129 130 131 |
# File 'lib/chef/client.rb', line 129 def json_attribs @json_attribs end |
#local_context ⇒ Object (readonly)
Returns the value of attribute local_context.
78 79 80 |
# File 'lib/chef/client.rb', line 78 def local_context @local_context end |
#logger ⇒ Object (readonly)
Returns the value of attribute logger.
153 154 155 |
# File 'lib/chef/client.rb', line 153 def logger @logger end |
#ohai ⇒ Ohai::System (readonly)
The ohai system used by this client.
115 116 117 |
# File 'lib/chef/client.rb', line 115 def ohai @ohai end |
#run_context ⇒ Chef::RunContext (readonly)
The run context of the Chef run.
95 96 97 |
# File 'lib/chef/client.rb', line 95 def run_context @run_context end |
#run_status ⇒ Chef::RunStatus (readonly)
The status of the Chef run.
88 89 90 |
# File 'lib/chef/client.rb', line 88 def run_status @run_status end |
#runner ⇒ Chef::Runner
The runner used to converge.
122 123 124 |
# File 'lib/chef/client.rb', line 122 def runner @runner end |
Class Method Details
.clear_notifications ⇒ Object
This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.
Clears all listeners for client run status events.
Primarily for testing purposes.
969 970 971 972 973 |
# File 'lib/chef/client.rb', line 969 def clear_notifications @run_start_notifications = nil @run_completed_successfully_notifications = nil @run_failed_notifications = nil end |
.generate_pfx_package(cert_name, date) ⇒ Object
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 |
# File 'lib/chef/client.rb', line 697 def self.generate_pfx_package(cert_name, date) require "openssl" unless defined?(OpenSSL) key = OpenSSL::PKey::RSA.new(2048) public_key = key.public_key subject = "CN=#{cert_name}" cert = OpenSSL::X509::Certificate.new cert.subject = cert.issuer = OpenSSL::X509::Name.parse(subject) cert.not_before = Time.now cert.not_after = Time.parse(date) cert.public_key = public_key cert.serial = 0x0 cert.version = 2 ef = OpenSSL::X509::ExtensionFactory.new ef.subject_certificate = cert ef.issuer_certificate = cert cert.extensions = [ ef.create_extension("subjectKeyIdentifier", "hash"), ef.create_extension("keyUsage", "digitalSignature,keyEncipherment", true), ] cert.add_extension(ef.create_ext_from_string("extendedKeyUsage=critical,serverAuth,clientAuth")) cert.sign key, OpenSSL::Digest.new("SHA256") password = ::Chef::HTTP::Authenticator.get_cert_password pfx = OpenSSL::PKCS12.create(password, subject, key, cert) pfx end |
.import_pfx_to_store(new_pfx) ⇒ Object
824 825 826 827 828 829 830 831 832 833 834 835 836 837 |
# File 'lib/chef/client.rb', line 824 def self.import_pfx_to_store(new_pfx) password = ::Chef::HTTP::Authenticator.get_cert_password require "win32-certstore" tempfile = Tempfile.new("#{Chef::Config[:node_name]}.pfx") File.open(tempfile, "wb") { |f| f.print new_pfx.to_der } # Need to determine where to store the key if Chef::Config[:auth_key_registry_type] == "user" win32certstore = ::Win32::Certstore.open("MY", store_location: CERT_SYSTEM_STORE_CURRENT_USER) else win32certstore = ::Win32::Certstore.open("MY") end win32certstore.add_pfx(tempfile, password, CRYPT_EXPORTABLE) tempfile.unlink end |
.run_completed_successfully_notifications ⇒ Array<Proc>
This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.
Listeners to be run when the client run completes successfully.
997 998 999 |
# File 'lib/chef/client.rb', line 997 def run_completed_successfully_notifications @run_completed_successfully_notifications ||= [] end |
.run_failed_notifications ⇒ Array<Proc>
This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.
Listeners to be run when the client run fails.
1008 1009 1010 |
# File 'lib/chef/client.rb', line 1008 def run_failed_notifications @run_failed_notifications ||= [] end |
.run_start_notifications ⇒ Array<Proc>
This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.
Listeners to be run when the client run starts.
986 987 988 |
# File 'lib/chef/client.rb', line 986 def run_start_notifications @run_start_notifications ||= [] end |
.update_key_and_register(cert_name, expiring_cert = nil) ⇒ Object
732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 |
# File 'lib/chef/client.rb', line 732 def self.update_key_and_register(cert_name, expiring_cert = nil) # Chef client and node objects exist on Chef Server already # Create a new public/private keypair in secure storage # and register the new public cert with Chef Server require "time" unless defined?(Time) autoload :URI, "uri" node = Chef::Config[:node_name] end_date = Time.new + (3600 * 24 * 90) end_date = end_date.utc.iso8601 new_cert_name = Time.now.utc.iso8601 payload = { name: new_cert_name, clientname: node, public_key: "", expiration_date: end_date, } new_pfx = generate_pfx_package(cert_name, end_date) payload[:public_key] = new_pfx.certificate.public_key.to_pem base_url = "#{Chef::Config[:chef_server_url]}" @tmpdir = Dir.mktmpdir file_path = File.join(@tmpdir, "#{node}.pem") # The pfx files expire every 90 days. # We check them in /http/authenticator to see if they are expiring when we extract the private key # If they are, we come here to update Chef Server with a new public key if expiring_cert File.open(file_path, "w") { |f| f.write expiring_cert.key.to_pem } signing_cert = file_path client = Chef::ServerAPI.new(base_url, client_name: Chef::Config[:node_name], signing_key_filename: signing_cert ) File.delete(file_path) else client = Chef::ServerAPI.new(base_url, client_name: Chef::Config[:node_name], signing_key_filename: Chef::Config[:client_key] ) end # Get the list of keys for this client # Then add the new key we just created # Then we delete the old one. cert_list = client.get(base_url + "/clients/#{node}/keys") client.post(base_url + "/clients/#{node}/keys", payload) # We want to remove the old key for various reasons # In the case where more than 1 certificate is returned we assume # there is some special condition applied to the client so we won't delete the old # certificates if cert_list.count < 2 cert_hash = cert_list.reduce({}, :merge!) old_cert_name = cert_hash["name"] new_key = new_pfx.key.to_pem File.open(file_path, "w") { |f| f.write new_key } client = Chef::ServerAPI.new(base_url, client_name: Chef::Config[:node_name], signing_key_filename: file_path) client.delete(base_url + "/clients/#{node}/keys/#{old_cert_name}") File.delete(file_path) end import_pfx_to_store(new_pfx) end |
.when_run_completes_successfully(¬ification_block) {|run_status| ... } ⇒ Object
Add a listener for the 'client run success' event.
948 949 950 |
# File 'lib/chef/client.rb', line 948 def when_run_completes_successfully(¬ification_block) run_completed_successfully_notifications << notification_block end |
.when_run_fails(¬ification_block) {|run_status| ... } ⇒ Object
Add a listener for the 'client run failed' event.
958 959 960 |
# File 'lib/chef/client.rb', line 958 def when_run_fails(¬ification_block) run_failed_notifications << notification_block end |
.when_run_starts(¬ification_block) {|run_status| ... } ⇒ Object
Add a listener for the 'client run started' event.
938 939 940 |
# File 'lib/chef/client.rb', line 938 def when_run_starts(¬ification_block) run_start_notifications << notification_block end |
Instance Method Details
#build_node ⇒ Chef::Node
This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.
Mutates the node
object to prepare it for the chef run.
466 467 468 469 470 |
# File 'lib/chef/client.rb', line 466 def build_node policy_builder.build_node run_status.node = node node end |
#check_certstore_for_key(cert_name) ⇒ Object
In the brave new world of No Certs On Disk, we want to put the pem file into Keychain or the Certstore But is it already there? We're solving the multi-user scenario where both a system/admin user can run on the box but also someone without admin rights can also run correctly locally.
683 684 685 686 687 688 689 690 691 |
# File 'lib/chef/client.rb', line 683 def check_certstore_for_key(cert_name) require "win32-certstore" if Chef::Config[:auth_key_registry_type] == "user" win32certstore = ::Win32::Certstore.open("MY", store_location: CERT_SYSTEM_STORE_CURRENT_USER) else win32certstore = ::Win32::Certstore.open("MY") end win32certstore.search("#{cert_name}") end |
#configure_event_loggers ⇒ Object
This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.
365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 |
# File 'lib/chef/client.rb', line 365 def configure_event_loggers if Chef::Config.disable_event_logger [] else Chef::Config.event_loggers.map do |evt_logger| case evt_logger when Symbol Chef::EventLoggers.new(evt_logger) when Class evt_logger.new else end end end end |
#configure_formatters ⇒ Object
This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.
338 339 340 341 342 343 344 345 346 347 348 |
# File 'lib/chef/client.rb', line 338 def configure_formatters formatters_for_run.map do |formatter_name, output_path| if output_path.nil? Chef::Formatters.new(formatter_name, STDOUT_FD, STDERR_FD) elsif output_path.is_a?(String) io = File.open(output_path, "a+") io.sync = true Chef::Formatters.new(formatter_name, io, io) end end end |
#converge(run_context) ⇒ Object
This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.
Converges all compiled resources.
Fires the converge_start, converge_complete and converge_failed events.
If the exception :end_client_run_early
is thrown during convergence, it
does not mark the run complete or failed, and returns nil
858 859 860 861 862 863 864 865 866 867 868 869 870 871 |
# File 'lib/chef/client.rb', line 858 def converge(run_context) catch(:end_client_run_early) do events.converge_start(run_context) logger.debug("Converging node #{node_name}") @runner = Chef::Runner.new(run_context) @runner.converge events.converge_complete rescue Exception => e events.converge_failed(e) raise e end end |
#converge_and_save(run_context) ⇒ Object
This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.
Converge the node via and then save it if successful.
If converge() raises it is important that save_updated_node is bypassed.
882 883 884 885 |
# File 'lib/chef/client.rb', line 882 def converge_and_save(run_context) converge(run_context) save_updated_node end |
#create_new_key_and_register(cert_name) ⇒ Object
792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 |
# File 'lib/chef/client.rb', line 792 def create_new_key_and_register(cert_name) require "time" unless defined?(Time) autoload :URI, "uri" node = Chef::Config[:node_name] d = Time.now if d.month == 10 || d.month == 11 || d.month == 12 end_date = Time.new(d.year + 1, d.month - 9, d.day, d.hour, d.min, d.sec).utc.iso8601 else end_date = Time.new(d.year, d.month + 3, d.day, d.hour, d.min, d.sec).utc.iso8601 end payload = { name: node, clientname: node, public_key: "", expiration_date: end_date, } new_pfx = generate_pfx_package(cert_name, end_date) payload[:public_key] = new_pfx.certificate.public_key.to_pem base_url = "#{Chef::Config[:chef_server_url]}" client = Chef::ServerAPI.new(base_url, client_name: Chef::Config[:validation_client_name], signing_key_filename: Chef::Config[:validation_key]) client.post(base_url + "/clients", payload) Chef::Log.trace("Updated client data: #{client.inspect}") import_pfx_to_store(new_pfx) end |
#do_windows_admin_check ⇒ Object
This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.
Check if the user has Administrator privileges on windows.
Throws an error if the user is not an admin, and
Chef::Config.fatal_windows_admin_check
is true.
911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 |
# File 'lib/chef/client.rb', line 911 def do_windows_admin_check if ChefUtils.windows? logger.trace("Checking for administrator privileges....") if !has_admin_privileges? = "#{ChefUtils::Dist::Infra::CLIENT} doesn't have administrator privileges on node #{node_name}." if Chef::Config[:fatal_windows_admin_check] logger.fatal() logger.fatal("fatal_windows_admin_check is set to TRUE.") raise Chef::Exceptions::WindowsNotAdmin, else logger.warn("#{} This might cause unexpected resource failures.") end else logger.trace("#{ChefUtils::Dist::Infra::CLIENT} has administrator privileges on node #{node_name}.") end end end |
#expanded_run_list ⇒ Chef::RunListExpansion
Expands the run list.
894 895 896 |
# File 'lib/chef/client.rb', line 894 def policy_builder. end |
#formatters_for_run ⇒ Object
This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.
351 352 353 354 355 356 357 358 359 360 361 362 |
# File 'lib/chef/client.rb', line 351 def formatters_for_run return Chef::Config.formatters unless Chef::Config.formatters.empty? [ Chef::Config[:log_location] ].flatten.map do |log_location| log_location = nil if log_location == STDOUT if !Chef::Config[:force_logger] || Chef::Config[:force_formatter] [:doc, log_location] else [:null] end end end |
#generate_pfx_package(cert_name, date) ⇒ Object
693 694 695 |
# File 'lib/chef/client.rb', line 693 def generate_pfx_package(cert_name, date) self.class.generate_pfx_package(cert_name, date) end |
#import_pfx_to_store(new_pfx) ⇒ Object
820 821 822 |
# File 'lib/chef/client.rb', line 820 def import_pfx_to_store(new_pfx) self.class.import_pfx_to_store(new_pfx) end |
#load_node ⇒ Chef::Node
This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.
Instantiates a Chef::Node object, possibly loading the node's prior state when using chef-client. Sets Chef.node to the new node.
450 451 452 453 454 455 |
# File 'lib/chef/client.rb', line 450 def load_node policy_builder.load_node run_status.node = policy_builder.node Chef.set_node(policy_builder.node) node end |
#load_required_recipe(rest, run_context) ⇒ Object
This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.
Adds a required recipe as specified by the Chef Server
TODO: @rest doesn't appear to be used anywhere outside of client.register except for here. If it's common practice to create your own rest client, perhaps we should do that here but it seems more appropriate to reuse one that we know is already created. for ease of testing, we'll pass the existing rest client in as a parameter
514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 |
# File 'lib/chef/client.rb', line 514 def load_required_recipe(rest, run_context) required_recipe_contents = rest.get("required_recipe") logger.info("Required Recipe found, loading it") Chef::FileCache.store("required_recipe", required_recipe_contents) required_recipe_file = Chef::FileCache.load("required_recipe", false) # TODO: add integration tests with resource reporting turned on # (presumably requires changes to chef-zero) # # Chef::Recipe.new takes a cookbook name and a recipe name along # with the run context. These names are eventually used in the # resource reporter, and if the cookbook name cannot be found in the # cookbook collection then we will fail with an exception. Cases where # we currently also fail: # - specific recipes # - chef-apply would fail if resource reporting was enabled # recipe = Chef::Recipe.new(nil, nil, run_context) recipe.from_file(required_recipe_file) run_context rescue Net::HTTPClientException => e case e.response when Net::HTTPNotFound logger.trace("Required Recipe not configured on the server, skipping it") else raise end end |
#node ⇒ Chef::Node
The node represented by this client.
102 103 104 |
# File 'lib/chef/client.rb', line 102 def node run_status.node end |
#node=(value) ⇒ Object
106 107 108 |
# File 'lib/chef/client.rb', line 106 def node=(value) run_status.node = value end |
#node_name ⇒ Object
This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.
Figure out the node name we are working with.
It tries these, in order:
- Chef::Config.node_name
- ohai[:fqdn]
- ohai[:machinename]
- ohai[:hostname]
617 618 619 620 621 622 623 624 |
# File 'lib/chef/client.rb', line 617 def node_name name = Chef::Config[:node_name] || ohai[:fqdn] || ohai[:machinename] || ohai[:hostname] Chef::Config[:node_name] = name raise Chef::Exceptions::CannotDetermineNodeName unless name name end |
#policy_builder ⇒ Chef::PolicyBuilder::Policyfile, Chef::PolicyBuilder::ExpandNodeObject
This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.
The PolicyBuilder strategy for figuring out run list and cookbooks.
550 551 552 |
# File 'lib/chef/client.rb', line 550 def policy_builder @policy_builder ||= Chef::PolicyBuilder::Dynamic.new(node_name, ohai.data, json_attribs, override_runlist, events) end |
#register(client_name = node_name, config = Chef::Config) ⇒ Chef::ServerAPI
This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.
Determine our private key and set up the connection to the Chef server.
Skips registration and fires the skipping_registration
event if
Chef::Config.client_key is unspecified or already exists.
If Chef::Config.client_key does not exist, we register the client with the Chef server and fire the registration_start and registration_completed events.
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 |
# File 'lib/chef/client.rb', line 647 def register(client_name = node_name, config = Chef::Config) if !config[:client_key] events.skipping_registration(client_name, config) logger.trace("Client key is unspecified - skipping registration") elsif ::Chef::Config[:migrate_key_to_keystore] == true && ChefUtils.windows? cert_name = "chef-#{client_name}" result = check_certstore_for_key(cert_name) if result.rassoc("#{cert_name}") logger.trace("Client key #{config[:client_key]} is present in Certificate Store - skipping registration") else create_new_key_and_register(cert_name) logger.trace("New client keys created in the Certificate Store - skipping registration") end events.skipping_registration(client_name, config) elsif File.exist?(config[:client_key]) events.skipping_registration(client_name, config) logger.trace("Client key #{config[:client_key]} is present - skipping registration") else events.registration_start(node_name, config) logger.info("Client key #{config[:client_key]} is not present - registering") Chef::ApiClient::Registration.new(node_name, config[:client_key]).run events.registration_completed end rescue Exception => e # TODO this should probably only ever fire if we *started* registration. # Move it to the block above. # TODO: munge exception so a semantic failure message can be given to the # user events.registration_failed(client_name, e, config) raise end |
#rest ⇒ Object
This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.
Standard rest object for talking to the Chef Server
FIXME: Can we drop this and only use the rest_clean object? Did I add rest_clean only out of some cant-break-a-minor-version paranoia?
387 388 389 390 |
# File 'lib/chef/client.rb', line 387 def rest @rest ||= Chef::ServerAPI.new(Chef::Config[:chef_server_url], client_name: node_name, signing_key_filename: Chef::Config[:client_key]) end |
#rest_clean ⇒ Object
This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.
A rest object with validate_utf8 set to false. This will not throw exceptions on non-UTF8 strings in JSON but will sanitize them so that e.g. POSTs will never fail. Cannot be configured on a request-by-request basis, so we carry around another rest object for it.
398 399 400 401 402 |
# File 'lib/chef/client.rb', line 398 def rest_clean @rest_clean ||= Chef::ServerAPI.new(Chef::Config[:chef_server_url], client_name: node_name, signing_key_filename: Chef::Config[:client_key], validate_utf8: false) end |
#run ⇒ Object
Do a full run for this Chef::Client.
Locks the run while doing its job.
Fires run_start before doing anything and fires run_completed or run_failed when finished. Also notifies client listeners of run_started at the beginning of Compile, and run_completed_successfully or run_failed when all is complete.
Phase 1: Setup
Gets information about the system and the run we are doing.
- Run ohai to collect system information.
- Register / connect to the Chef server (unless in solo mode).
- Retrieve the node (or create a new one).
- Merge in json_attribs, Chef::Config.environment, and override_run_list.
Phase 2: Compile
Decides what we plan to converge by compiling recipes.
- Sync required cookbooks to the local cache.
- Load libraries from all cookbooks.
- Load attributes from all cookbooks.
- Load LWRPs from all cookbooks.
- Load resource definitions from all cookbooks.
- Load recipes in the run list.
- Load recipes from the command line.
Phase 3: Converge
Brings the system up to date.
- Converge the resources built from recipes in Phase 2.
- Save the node.
- Reboot if we were asked to.
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 |
# File 'lib/chef/client.rb', line 241 def run start_profiling runlock = RunLock.new(Chef::Config.lockfile) # TODO feels like acquire should have its own block arg for this runlock.acquire # don't add code that may fail before entering this section to be sure to release lock begin runlock.save_pid events.register(Chef::DataCollector::Reporter.new(events)) events.register(Chef::ActionCollection.new(events)) events.register(Chef::Compliance::Runner.new) run_status.run_id = request_id = Chef::RequestID.instance.request_id @run_context = Chef::RunContext.new(nil, nil, events) run_status.run_context = run_context events.run_start(Chef::VERSION, run_status) logger.info("*** #{ChefUtils::Dist::Infra::PRODUCT} #{Chef::VERSION} ***") logger.info("Platform: #{RUBY_PLATFORM}") logger.info "#{ChefUtils::Dist::Infra::CLIENT.capitalize} pid: #{Process.pid}" logger.info "Targeting node: #{Chef::Config.target_mode.host}" if Chef::Config.target_mode? logger.debug("#{ChefUtils::Dist::Infra::CLIENT.capitalize} request_id: #{request_id}") logger.warn("`enforce_path_sanity` is deprecated, please use `enforce_default_paths` instead!") if Chef::Config[:enforce_path_sanity] ENV["PATH"] = ChefUtils::DSL::DefaultPaths.default_paths if Chef::Config[:enforce_default_paths] || Chef::Config[:enforce_path_sanity] run_ohai unless Chef::Config[:solo_legacy_mode] register # create and save the rest objects in the run_context run_context.rest = rest run_context.rest_clean = rest_clean events.register(Chef::ResourceReporter.new(rest_clean)) end load_node build_node run_status.start_clock logger.info("Starting #{ChefUtils::Dist::Infra::PRODUCT} Run for #{node.name}") run_started do_windows_admin_check Chef.resource_handler_map.lock! Chef.provider_handler_map.lock! setup_run_context setup_targetmode if Chef::Config.target_mode? load_required_recipe(@rest, run_context) unless Chef::Config[:solo_legacy_mode] converge_and_save(run_context) run_status.stop_clock logger.info("#{ChefUtils::Dist::Infra::PRODUCT} Run complete in #{run_status.elapsed_time} seconds") run_completed_successfully events.run_completed(node, run_status) # keep this inside the main loop to get exception backtraces end_profiling # rebooting has to be the last thing we do, no exceptions. Chef::Platform::Rebooter.reboot_if_needed!(node) rescue Exception => run_error # CHEF-3336: Send the error first in case something goes wrong below and we don't know why logger.trace("Re-raising exception: #{run_error.class} - #{run_error.}\n#{run_error.backtrace.join("\n ")}") # If we failed really early, we may not have a run_status yet. Too early for these to be of much use. if run_status run_status.stop_clock run_status.exception = run_error run_failed end events.run_failed(run_error, run_status) Chef::Application.debug_stacktrace(run_error) raise run_error ensure Chef::RequestID.instance.reset_request_id @run_status = nil runlock.release end true end |
#run_completed_successfully ⇒ Object
This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.
Callback to fire notifications that the run completed successfully
421 422 423 424 425 426 |
# File 'lib/chef/client.rb', line 421 def run_completed_successfully success_handlers = self.class.run_completed_successfully_notifications success_handlers.each do |notification| notification.call(run_status) end end |
#run_failed ⇒ Object
This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.
Callback to fire notifications that the Chef run failed
433 434 435 436 437 438 |
# File 'lib/chef/client.rb', line 433 def run_failed failure_handlers = self.class.run_failed_notifications failure_handlers.each do |notification| notification.call(run_status) end end |
#run_ohai ⇒ Object
This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.
Run ohai plugins. Runs all ohai plugins unless minimal_ohai is specified.
Sends the ohai_completed event when finished.
594 595 596 597 598 599 |
# File 'lib/chef/client.rb', line 594 def run_ohai filter = Chef::Config[:minimal_ohai] ? %w{fqdn machinename hostname platform platform_version ohai_time os os_version init_package} : nil ohai.transport_connection = transport_connection if Chef::Config.target_mode? ohai.all_plugins(filter) events.ohai_completed(node) end |
#run_started ⇒ Object
This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.
Callback to fire notifications that the Chef run is starting
409 410 411 412 413 414 |
# File 'lib/chef/client.rb', line 409 def run_started self.class.run_start_notifications.each do |notification| notification.call(run_status) end events.run_started(run_status) end |
#save_updated_node ⇒ Object
This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.
Save the updated node to Chef.
Does not save if we are in solo mode or using override_runlist.
564 565 566 567 568 569 570 571 572 573 |
# File 'lib/chef/client.rb', line 564 def save_updated_node if Chef::Config[:solo_legacy_mode] # nothing to do elsif policy_builder.temporary_policy? logger.warn("Skipping final node save because override_runlist was given") else logger.debug("Saving the current state of node #{node_name}") node.save end end |
#setup_run_context ⇒ Object
This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.
Sets up the run context.
493 494 495 496 497 498 |
# File 'lib/chef/client.rb', line 493 def setup_run_context @run_context = policy_builder.setup_run_context(specific_recipes, run_context) assert_cookbook_path_not_empty(run_context) run_status.run_context = run_context # backcompat for chefspec run_context end |
#setup_targetmode ⇒ Object
This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.
Setup conditions for Target Mode.
580 581 582 |
# File 'lib/chef/client.rb', line 580 def setup_targetmode TargetIO::FileUtils.mkdir_p(Chef::Config[:file_cache_path]) end |
#sync_cookbooks ⇒ Object
This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.
Sync cookbooks to local cache.
TODO this appears to be unused.
481 482 483 |
# File 'lib/chef/client.rb', line 481 def sync_cookbooks policy_builder.sync_cookbooks end |
#update_key_and_register(cert_name) ⇒ Object
728 729 730 |
# File 'lib/chef/client.rb', line 728 def update_key_and_register(cert_name) self.class.update_key_and_register(cert_name) end |