Chef converge

 === Parameters
 ohai(Ohai):: Ohai instance to be used by Chef

 === Return
 true:: Always return true
488403
def converge(ohai)
      begin
        # When the run_list consists solely of RightScripts, adding error or report
        # handlers is not possible. Suppress these extra features as they can
        # be confusing to users. Also makes for cleaner logs.
        if @only_scripts
          ::Chef::Client.clear_notifications
        end

        if @cookbooks.size > 0
          @audit.create_new_section('Converging')
        else
          @audit.create_new_section('Preparing execution')
        end

        log_desc = "Log level is #{Log.level_to_sym(CookState.log_level)}"
        if CookState.dev_log_level
          log_desc << " (overridden by #{CookState::LOG_LEVEL_TAG}=#{CookState.dev_log_level})"
        end
        log_desc << '.'
        @audit.append_info(log_desc)
        @audit.append_info('The download once flag is set.') if CookState.download_once?

        @audit.append_info("Run list for thread #{@thread_name.inspect} contains #{@run_list.size} items.")
        @audit.append_info(@run_list.join(', '))

        attribs = { 'run_list' => @run_list }
        attribs.merge!(@attributes) if @attributes
        c      = Chef::Client.new(attribs)
        c.ohai = ohai
        audit_time do
          # Ensure that Ruby subprocesses invoked by Chef do not inherit our
          # RubyGems/Bundler environment.
          without_bundler_env do
            c.run
          end
        end
      rescue SystemExit => e
        # exit is expected in case where a script has invoked rs_shutdown
        # (command line tool or Chef resource). exit is considered to be
        # unexpected if rs_shutdown has not been called. note that it is
        # possible, but not a 'best practice', for a recipe (but not a
        # RightScript) to call rs_shutdown as an external command line utility
        # without calling exit (i.e. request a deferred reboot) and continue
        # running recipes until the list of recipes is complete. in this case,
        # the shutdown occurs after subsequent recipes have finished. the best
        # practice for a recipe is to use the rs_shutdown chef resource which
        # calls exit when appropriate.
        shutdown_request = RightScale::ShutdownRequestProxy.instance
        if shutdown_request.continue?
          report_failure('Execution failed due to rs_shutdown not being called before exit', chef_error(e))
          Log.debug(Log.format("Execution failed", e, :trace))
        else
          Log.info("Shutdown requested by script: #{shutdown_request}")
        end
      rescue Exception => e
        report_failure('Execution failed', chef_error(e))
        Log.debug(Log.format("Execution failed", e, :trace))
      ensure
        # kill the chef node provider
        RightScale::Windows::ChefNodeServer.instance.stop rescue nil if RightScale::Platform.windows?
      end
      report_success(c.node) if @ok
      true
    end
550383
public boolean iterate() {
		boolean converged;
		switch( mode ) {
			case COMPUTE_DERIVATIVES:
				totalFullSteps++;
				converged = updateDerivates();
				if( !converged ) {
					totalSelectSteps++;
					converged = computeStep();
				}
				break;

			case DETERMINE_STEP:
				totalSelectSteps++;
				converged = computeStep();
				break;

			case CONVERGED:
				return true;

			default:
				throw new RuntimeException("BUG! mode="+mode);
		}

		if( converged ) {
			mode = Mode.CONVERGED;
			return true;
		} else {
			return false;
		}
	}
242468
def sync_node(node):
    
    if node.get('dummy') or 'dummy' in node.get('tags', []):
        lib.print_header("Skipping dummy: {0}".format(env.host))
        return False
    current_node = lib.get_node(node['name'])
    # Always configure Chef Solo
    solo.configure(current_node)
    ipaddress = _get_ipaddress(node)
    # Everything was configured alright, so save the node configuration
    # This is done without credentials, so that we keep the node name used
    # by the user and not the hostname or IP translated by .ssh/config
    filepath = save_config(node, ipaddress)
    try:
        # Synchronize the kitchen directory
        _synchronize_node(filepath, node)
        # Execute Chef Solo
        _configure_node()
    finally:
        _node_cleanup()
    return True
592132
def is_converged(self):
        '''
        '''

        # Check for cached result
        if self._converged is None:
            self._converged = self._is_converged()
        return Property(scalars=[Scalar(value=self._converged)])
798086
def check_chef_env(chef_env_name)
      return unless chef_env_name
      Chef::Environment.load(chef_env_name) if chef_env_name
    rescue Net::HTTPServerException => e
      raise unless e.to_s =~ /^404/
      ui.info 'Creating chef environment ' + chef_env_name
      chef_env = Chef::Environment.new
      chef_env.name(chef_env_name)
      chef_env.create
      chef_env
    end
669352
def _bin_op(instance, opnode, op, other, context, reverse=False):
    
    if reverse:
        method_name = protocols.REFLECTED_BIN_OP_METHOD[op]
    else:
        method_name = protocols.BIN_OP_METHOD[op]
    return functools.partial(
        _invoke_binop_inference,
        instance=instance,
        op=op,
        opnode=opnode,
        other=other,
        context=context,
        method_name=method_name,
    )
830487
def doOverlap(bbox1, bbox2):
    
    if bbox1[2] < bbox2[0] or bbox2[2] < bbox1[0]:
        return False
    if bbox1[3] < bbox2[1] or bbox2[3] < bbox1[1]:
        return False
    return True
10750
def report_success(node)
      ChefState.merge_attributes(node.normal_attrs) if node
      remove_right_script_params_from_chef_state
      patch = ::RightSupport::Data::HashTools.deep_create_patch(@inputs, ChefState.attributes)
      # We don't want to send back new attributes (ohai etc.)
      patch[:right_only] = { }
      @inputs_patch      = patch
      EM.next_tick { succeed }
      true
    end
111535
def configure(current_node=None):
    """"""
    current_node = current_node or {}
    # Ensure that the /tmp/chef-solo/cache directory exist
    cache_dir = "{0}/cache".format(env.node_work_path)
    # First remote call, could go wrong
    try:
        cache_exists = exists(cache_dir)
    except EOFError as e:
        abort("Could not login to node, got: {0}".format(e))
    if not cache_exists:
        with settings(hide('running', 'stdout'), warn_only=True):
            output = sudo('mkdir -p {0}'.format(cache_dir))
        if output.failed:
            error = "Could not create {0} dir. ".format(env.node_work_path)
            error += "Do you have sudo rights?"
            abort(error)
    # Change ownership of /tmp/chef-solo/ so that we can rsync
    with hide('running', 'stdout'):
        with settings(warn_only=True):
            output = sudo(
                'chown -R {0} {1}'.format(env.user, env.node_work_path))
        if output.failed:
            error = "Could not modify {0} dir. ".format(env.node_work_path)
            error += "Do you have sudo rights?"
            abort(error)
    # Set up chef solo configuration
    logging_path = os.path.dirname(LOGFILE)
    if not exists(logging_path):
        sudo('mkdir -p {0}'.format(logging_path))
    if not exists('/etc/chef'):
        sudo('mkdir -p /etc/chef')
    # Set parameters and upload solo.rb template
    reversed_cookbook_paths = cookbook_paths[:]
    reversed_cookbook_paths.reverse()
    cookbook_paths_list = '[{0}]'.format(', '.join(
        ['"{0}/{1}"'.format(env.node_work_path, x)
            for x in reversed_cookbook_paths]))
    data = {
        'node_work_path': env.node_work_path,
        'cookbook_paths_list': cookbook_paths_list,
        'environment': current_node.get('chef_environment', '_default'),
        'verbose': "true" if env.verbose else "false",
        'http_proxy': env.http_proxy,
        'https_proxy': env.https_proxy
    }
    with settings(hide('everything')):
        try:
            upload_template('solo.rb.j2', '/etc/chef/solo.rb',
                            context=data, use_sudo=True, backup=False,
                            template_dir=BASEDIR, use_jinja=True, mode=0400)
        except SystemExit:
            error = ("Failed to upload '/etc/chef/solo.rb'\nThis "
                     "can happen when the deployment user does not have a "
                     "home directory, which is needed as a temporary location")
            abort(error)
    with hide('stdout'):
        sudo('chown root:$(id -g -n root) {0}'.format('/etc/chef/solo.rb'))
1042086
def deploy_chef(ask="yes", version="11"):
    """"""
    env.host_string = lib.get_env_host_string()
    if ask == "no" or littlechef.noninteractive:
        print("Deploying Chef using omnibus installer version: ...".format(version))
    else:
        message = ('\nAre you sure you want to install Chef version:'
                   '{0} on node {1}?'.format(version, env.host_string))
        if not confirm(message):
            abort('Aborted by user')

    lib.print_header("Configuring Chef Solo on {0}".format(env.host_string))

    if not __testing__:
        solo.install(version)
        solo.configure()

        # Build a basic node file if there isn't one already
        # with some properties from ohai
        with settings(hide('stdout'), warn_only=True):
            output = sudo('ohai -l warn')
        if output.succeeded:
            try:
                ohai = json.loads(output)
            except ValueError:
                abort("Could not parse ohai's output"
                      ":\n  {0}".format(output))
            node = {"run_list": []}
            for attribute in ["ipaddress", "platform", "platform_family",
                              "platform_version"]:
                if ohai.get(attribute):
                    node[attribute] = ohai[attribute]
            chef.save_config(node)
46776
def run # rubocop:disable Metrics/AbcSize, Metrics/PerceivedComplexity
      self.config = Chef::Config.merge!(config)

      # OPTIMIZE: Maybe instead of a flag, infer the graph format from fileext?

      # Parse the configuration options, provide defaults where needed
      output_format = if config[:graphformat]
                        config[:graphformat].to_sym
                      else
                        :png
                      end
      Chef::Log.debug("Output format is: #{output_format}")

      # Determine of a filename has been passed
      filename = if @name_args.size >= 1
                   @name_args[0]
                 else
                   "role-spaghetti.#{output_format}"
                 end
      Chef::Log.debug("Output filename is: #{filename}")

      loaded_roles = loader.find_all_objects(config[:role_path])

      # If we can't find any roles, it's pointless to continue.
      if loaded_roles.empty?
        ui.fatal("No roles were found in role_path: #{config[:role_path]}")
        ui.fatal('Ensure that your knife.rb has the correct path.')
        exit 1
      end

      g = GraphViz.new(:RoleDependencies, type: :digraph,
                                          fontname: 'Verdana', fontsize: 20,
                                          label: "\n\n\nChef Role Dependencies\n",
                                          rankdir: 'LR',
                                          overlap: 'false',
                                          compound: 'true')

      loaded_roles.each do |role_file|
        # Create an absolute path, since some file references include relative paths
        abspath = File.absolute_path(File.join(config[:role_path], role_file))

        # The object_from_file method figures out the ruby/json logic
        role = loader.object_from_file(abspath)

        Chef::Log.debug("Loaded role is: #{role}")

        # OPTIMIZE: Handle environment run_lists

        g.node[:shape] = 'box'
        g.node[:style] = 'rounded'
        g.node[:color] = 'red'
        role_node = g.add_nodes("#{role.name}_role", label: role.name)

        # This logic is to ensure that an embedded role doesn't change color
        role.run_list.each do |rli|
          if rli.role?
            g.node[:shape] = 'box'
            g.node[:style] = 'rounded'
            g.node[:color] = 'red'
            rli_node = g.add_nodes("#{rli.name}_role", label: rli.name)
          else
            g.node[:shape] = 'component'
            g.node[:color] = 'blue'
            rli_node = g.add_nodes(rli.name)
          end

          g.add_edges(role_node, rli_node)
        end
      end

      # Let's write out the graph to a file
      if config[:neatograph]
        g.output(output_format => filename.to_s, :use => 'neato')
      else
        # default to dot
        g.output(output_format => filename.to_s)
      end

      ui.msg("A Role dependency graph has been written to #{filename}")
    end
902997
def cookbook_that_matches_rules(codes)
      recipe = ""
      codes.each do |code|
        if code == "FC002"
          recipe += %q{
            directory "#{node['base_dir']}" do
              action :create
            end
          }
        elsif code == "FC004"
          recipe += %q{
            execute "stop-jetty" do
              command "/etc/init.d/jetty6 stop"
              action :run
            end
          }
        elsif code == "FC005"
          recipe += %q{
            package 'erlang-base' do
              action :upgrade
            end
            package 'erlang-corba' do
              action :upgrade
            end
            package 'erlang-another' do
              action :upgrade
            end
          }
        elsif code == "FC006"
          recipe += %q{
            directory "/var/lib/foo" do
              mode 644
              action :create
            end
          }
        end
      end
      write_recipe(recipe)
      write_file("cookbooks/example/recipes/server.rb", "")
      write_readme("Hello World") # Don't trigger FC011
      write_metadata(%q{
        name 'example'
        maintainer 'A Maintainer'
        maintainer_email 'maintainer@example.com'
        version '0.0.1'
        issues_url 'http://github.com/foo/bar_cookbook/issues'
        source_url 'http://github.com/foo/bar_cookbook'
      }.strip)
    end
1264779
def execute(force=false)
      return false if executed? && !force
      evaluate_recipes
      transaction = apply
    rescue Exception => e
      false
    else
      not transaction.any_failed?
    ensure
      @executed = true
    end
646468
def role_admin?(run_list = nil)
      return false unless run_list.is_a?(Array)
      # => This will Authorize Anyone if the RunList is Empty or the Chef Node does not exist!!!
      run_list.empty? || auth['roles'].any? { |role| run_list.any? { |r| r =~ /role\[#{role}\]/i } }
    end
807870
public function continueRecipe(): callable
    {
        return function (array $with = [], string $nextStep = null): ChefInterface {
            /**
             * @var Chef $this
             */
            $this->updateMyWorkPlan($with);

            while (($callable = $this->getNextStep($nextStep)) instanceof BowlInterface) {
                try {
                    $callable->execute($this, $this->workPlan);
                } catch (\Throwable $error) {
                    $this->position = \count($this->steps) + 1;

                    $this->callErrors($error);
                }

                $nextStep = null;
            }

            return $this;
        };
    }
1192459
function converge(f, g, h, x) {
  if(!isFunction(f) || !isFunction(g) || !isFunction(h)) {
    throw new TypeError('converge: Functions required for first three arguments')
  }

  return curry(f)(g(x), h(x))
}
92143
def _monkey_patch_old_chef!
      require 'chef/event_dispatch/dispatcher'
      instance = self
      orig_method = Chef::EventDispatch::Dispatcher.instance_method(:library_file_loaded)
      Chef::EventDispatch::Dispatcher.send(:define_method, :library_file_loaded) do |filename|
        instance.events = self
        instance.monkey_patched = false
        @subscribers |= [instance]
        Chef::EventDispatch::Dispatcher.send(:define_method, :library_file_loaded, orig_method)
        orig_method.bind(self).call(filename)
      end
    end