一个拆分haproxy serverlist的小脚本
公司对haproxy进行了配置的拆分,将每个backend的serverlist独立拆分成一个静态文件,对每个静态文件可以独立修改..现有的haproxy.cfg配置文件数量很多且每个文件的内容也非常的多, 人工拆分太苦逼, 因此写过一个小脚本用来完成这项任务.
今天在浏览系统文件夹的时候, 将此程序最初的一个版本贴上...
#!/usr/bin/ruby
# 2014/05/24
# coding by kevin
hacfg=ARGV
if ARGV.empty?
puts 'Please input haproxy.cfg parameter'
exit
end
if ! File.exists?(hacfg)
puts 'File not exists,please check'
exit
end
if ! File.directory?('backend.d')
Dir::mkdir('backend.d')
end
file = File.readlines(hacfg).to_s
file.gsub!("\t"," ")
#解析backend
area = file.scan(/^(backend.*(\s+ .*)+)/)
#对提取的backend解析serverlist
area.each do |i|
i.pop
n = i.to_s
t = i.to_s
conent = n.split("\n")
name = conent.split(" ")
#解析server条目写入到backend.d目录
serverlist = n.scan(/\s?#?\s?server .*/)
f = File.open("backend.d/#{name}","w")
if conent.to_s =~ /(\s+source\s+\d+\.\d+\.\d+\.\d+|\s+backup\Z|\s+id\s+\w+)/
puts name
puts " have key word...so next..."
next
end
serverlist.each do |line|
ip = line.scan(/(\d+\.\d+\.\d+\.\d+):/)
port = line.scan(/\d+\.\d+\.\d+\.\d+\:(\d+)/)
weight = line.scan(/weight\s+(\d+)/)
maxconn = line.scan(/maxconn\s+(\d+)/)
check_inter = line.scan(/check inter\s+(\d+)/)
fall = line.scan(/fall\s+(\d+)/)
source = line.scan(/source/)
backup = line.scan(/backup/)
if ip.empty? or ip.nil?
puts "#{name} serverlist发现有ip 获取为空,请检查"
exit
end
if port.empty? or port.nil?
puts "#{name} serverlist发现有port 获取为空,请检查"
exit
end
if weight.empty? or weight.nil?
puts "#{name} serverlist发现有weight 获取为空,请检查"
exit
end
if maxconn.empty? or maxconn.nil?
puts "#{name} serverlist发现有maxconn 获取为空,请检查"
exit
end
if check_inter.empty? or check_inter.nil?
puts "#{name} serverlist发现有check inter 获取为空,请检查"
exit
end
if fall.empty? or fall.nil?
puts "#{name} serverlist发现有fall 获取为空,请检查"
exit
end
if ! source.empty?
puts " notice : have key words < source >"
end
if ! backup.empty?
puts " notice : have key words < backup >"
end
if line !~ /\#/
f.puts("#{ip},#{port},#{weight},#{maxconn},#{check_inter},#{fall}")
end
if serverlist ==line
t.gsub!(/( )+#{line}/," option server_from_file\n server_file #{name}")
else
t.gsub!(/#{line}/,'kevin')
end
end
f.close
file.gsub!("#{n}","#{t}")
end
f = File.open("haproxy.cfg.aa","w")
f.puts(file)
f.close
a = File.readlines("haproxy.cfg.aa")
file = a.delete_if{|i| i =~ /kevin/ }
f = File.open("haproxy.cfg.aa","w")
f.puts(file)
f.close
页:
[1]