forked from theforeman/foreman_discovery
-
Notifications
You must be signed in to change notification settings - Fork 0
/
discover_host
executable file
·93 lines (81 loc) · 2.17 KB
/
discover_host
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
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
83
84
85
86
87
88
89
90
91
92
93
#!/usr/bin/env ruby
require 'fileutils'
require 'net/http'
require 'net/https'
require 'uri'
# For comparison
require 'rubygems'
require 'facter'
require 'yaml'
def discover_server
server = (discover_by_pxe or discover_by_dns)
unless server =~ /^http/
server = "http://#{server}"
end
server
end
def discover_by_pxe
begin
contents = File.open("/proc/cmdline", 'r') { |f| f.read }
server_ip = contents.split.map { |x| $1 if x.match(/foreman.ip=(.*)/)}.compact
if server_ip.size == 1
return server_ip.join
else
return false
end
rescue
return false
end
end
def discover_by_dns
begin
contents = File.open("/proc/cmdline", 'r') { |f| f.read }
server_name = contents.split.map { |x| $1 if x.match(/foreman.server=(.*)/)}.compact
server_name = server_name.size == 1 ? server_name.join : 'foreman'
require 'socket'
return TCPSocket.gethostbyname(server_name)[3..-1].first || false
rescue
return false
end
end
def upload
puts "#{Time.now}: Triggering import of facts from Foreman"
ip = Facter.value('ipaddress')
data = ip.nil? ? {} : {'ip' => ip}
begin
uri = URI.parse(discover_server)
http = Net::HTTP.new(uri.host, uri.port)
if uri.scheme == 'https' then
http.use_ssl = true
http.verify_mode = OpenSSL::SSL::VERIFY_NONE
end
req = Net::HTTP::Post.new("/discovers")
req.set_form_data(data)
response = http.request(req)
puts response.body
rescue Exception => e
raise "#{Time.now}: Could not send facts to Foreman: #{e}"
end
end
def write_cache(data)
File.open('/tmp/proxy_cache', 'w') {|f| f.write(data) }
end
def read_cache
File.read('/tmp/proxy_cache')
rescue => e
"empty cache"
end
# Main
$stdout.reopen("/tmp/proxy-discovery.log", "w")
$stderr.reopen("/tmp/proxy-discovery.err", "w")
# loop, but only upload on changes
while true do
uninteresting_facts=/kernel|operatingsystem|osfamily|ruby|path|time|swap|free|filesystem|version|selinux/i
facts = Facter.to_hash.reject! {|k,v| k =~ uninteresting_facts }
unless YAML.load(read_cache) == facts
puts "Fact cache invalid, reloading to foreman"
upload
write_cache(YAML.dump(facts))
end
sleep 60
end