Class: HaproxyApi

Inherits:
Sinatra::Base
  • Object
show all
Defined in:
lib/hapi/application/app.rb

Instance Method Summary collapse

Instance Method Details

#get_configObject



43
44
45
46
# File 'lib/hapi/application/app.rb', line 43

def get_config
  return { 'frontend' => {}, 'backend' => {} } if !File.exists?($mutable_haproxy_config)
  return JSON.parse(File.read($mutable_haproxy_config))
end

#render(config) ⇒ Object



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
94
95
96
97
98
99
100
101
102
103
104
# File 'lib/hapi/application/app.rb', line 49

def render(config)
  content = ""
  f = File.open($haproxy_config, "r")
  in_gen_section = false
  f.each_line do |line|
    if line =~ /HAPROXY_API_GENERATED/
      if in_gen_section 
        in_gen_section = false
      else
        in_gen_section = true          
      end
    else
      if !in_gen_section
         content += line
      end       
    end      
  end
  f.close

  content += "# HAPROXY_API_GENERATED - START\n"
  
  config['frontend'].each_pair do |name, frontend|
    content += "frontend #{name}\n"
    content += "  bind 0.0.0.0:#{frontend['port']}\n"
    content += "  default_backend #{name}-backend\n"
    content += "\n"
  end

  config['backend'].each_pair do |name, backend|
    content += "backend #{name}\n"
    content += "  balance #{backend['lbmethod']}\n"
    
    if backend.has_key?('options')
      backend['options'].each_pair do |k,v|
        content += "  option #{k} #{v}\n"
      end
    end
    
    port = backend['port']
    server_options = ""
    if backend.has_key?('server_options')
      backend['server_options'].each_pair do |k,v|
        server_options += "#{k} #{v} "
      end
    end

    backend['servers'].each do |server|
      content += "  server #{server}:#{port} #{server}:#{port} #{server_options} \n"      
    end
    content += "\n"        
  end

  content += "# HAPROXY_API_GENERATED - END\n"
        
  return content
end

#set_config(config) ⇒ Object



107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
# File 'lib/hapi/application/app.rb', line 107

def set_config(config)
  ts = Time.now.to_i
  `cp #{$haproxy_config} #{$haproxy_config}.#{ts}`
  content = render config
  File.open($mutable_haproxy_config, 'w') { |file| file.write(JSON.dump(config)) }
  File.open($haproxy_config, 'w') { |file| file.write(content) }        
  
  result = `/usr/sbin/haproxy -c -f #{$haproxy_config}`
  if $?.to_i == 0
    puts `systemctl restart haproxy`
  else
    puts "rolling back config - got:"
    puts result
    `cp #{$haproxy_config}.#{ts} #{$haproxy_config}`
    return status(500)
  end
end