Class: Chef::Knife::NodeSync

Inherits:
Chef::Knife show all
Defined in:
lib/chef/knife/node_sync.rb

Overview

NodeSync class

Instance Method Summary collapse

Instance Method Details

#compare(node, chef_node, local_node) ⇒ Object



45
46
47
48
49
50
51
# File 'lib/chef/knife/node_sync.rb', line 45

def compare(node, chef_node, local_node)
  msg = "--> Checking #{node}".ljust(50)
  chef_node = chef_node.select { |k, _| local_node.key?(k) }
  opts = config[:abbrev] ? {} : { array_path: true }
  diff = ::HashDiff.diff(chef_node, local_node, opts)
  diff.empty? ? show_success(msg) : show_error(msg, diff)
end

#find_node_file(node) ⇒ Object



53
54
55
56
57
58
59
60
61
62
# File 'lib/chef/knife/node_sync.rb', line 53

def find_node_file(node)
  config_path = Chef::Config[:node_path]
  node_paths = config_path.is_a?(String) ? [config_path] : config_path
  node_paths.map do |node_path|
    path_glob =
      File.join(Chef::Util::PathHelper.escape_glob_dir(node_path), '**')
    path_glob << "/#{node.gsub(/[_-]/, '{-,_}')}.{json,rb}"
    Dir.glob(path_glob)
  end.flatten
end

#loaderObject



41
42
43
# File 'lib/chef/knife/node_sync.rb', line 41

def loader
  @loader ||= Core::ObjectLoader.new(Chef::Node, ui)
end

#node_from_chef(node) ⇒ Object



64
65
66
67
68
# File 'lib/chef/knife/node_sync.rb', line 64

def node_from_chef(node)
  Chef::Node.load(node).to_hash
rescue Net::HTTPServerException
  ui.error("Node '#{node}' could not be found on chef server")
end

#node_from_file(node) ⇒ Object



70
71
72
73
74
75
76
77
78
79
# File 'lib/chef/knife/node_sync.rb', line 70

def node_from_file(node)
  files = find_node_file(node)
  if files.empty?
    ui.error("Node '#{node}' could not be found on disk")
  elsif files.count > 1
    ui.error("Duplicate file node for '#{node}'")
  else
    loader.object_from_file(files.first).to_hash
  end
end

#runObject



81
82
83
84
85
86
87
88
89
90
# File 'lib/chef/knife/node_sync.rb', line 81

def run
  nodes = name_args.empty? ? Chef::Node.list.keys : name_args
  nodes.each do |node|
    chef_node = node_from_chef(node)
    local_node = node_from_file(node)
    next if chef_node.nil? || local_node.nil?

    compare(node, chef_node, local_node)
  end
end

#show_error(msg, diff) ⇒ Object



96
97
98
99
# File 'lib/chef/knife/node_sync.rb', line 96

def show_error(msg, diff)
  ui.info(msg + ui.color('difference(s) found', :yellow))
  pp(diff) if config[:diff]
end

#show_success(msg) ⇒ Object



92
93
94
# File 'lib/chef/knife/node_sync.rb', line 92

def show_success(msg)
  ui.info(msg + ui.color('properly synchronized.', :green))
end