Class: Synapse::ConfigGenerator::Nginx

Inherits:
BaseGenerator
  • Object
show all
Includes:
Logging
Defined in:
lib/synapse/config_generator/nginx.rb

Constant Summary collapse

NAME =
'nginx'.freeze

Instance Method Summary collapse

Constructor Details

#initialize(opts) ⇒ Nginx

Returns a new instance of Nginx.



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
# File 'lib/synapse/config_generator/nginx.rb', line 12

def initialize(opts)
  %w{main events}.each do |req|
    if !opts.fetch('contexts', {}).has_key?(req)
      raise ArgumentError, "nginx requires a contexts.#{req} section"
    end
  end

  @opts = opts
  @contexts = opts['contexts']
  @opts['do_writes'] = true unless @opts.key?('do_writes')
  @opts['do_reloads'] = true unless @opts.key?('do_reloads')

  req_pairs = {
    'do_writes' => ['config_file_path', 'check_command'],
    'do_reloads' => ['reload_command', 'start_command'],
  }

  req_pairs.each do |cond, reqs|
    if opts[cond]
      unless reqs.all? {|req| opts[req]}
        missing = reqs.select {|req| not opts[req]}
        raise ArgumentError, "the `#{missing}` option(s) are required when `#{cond}` is true"
      end
    end
  end

  # how to restart nginx
  @restart_interval = @opts.fetch('restart_interval', 2).to_i
  @restart_jitter = @opts.fetch('restart_jitter', 0).to_f
  @restart_required = true
  @has_started = false

  # virtual clock bookkeeping for controlling how often nginx restarts
  @time = 0
  @next_restart = @time

  # a place to store the parsed nginx config from each watcher
  @watcher_configs = {}
end

Instance Method Details

#construct_name(backend) ⇒ Object

used to build unique, consistent nginx names for backends



291
292
293
294
295
296
297
298
# File 'lib/synapse/config_generator/nginx.rb', line 291

def construct_name(backend)
  name = "#{backend['host']}:#{backend['port']}"
  if backend['name'] && !backend['name'].empty?
    name = "#{backend['name']}_#{name}"
  end

  return name
end

#generate_base_configObject

generates the global and defaults sections of the config file



126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
# File 'lib/synapse/config_generator/nginx.rb', line 126

def generate_base_config
  base_config = ["# auto-generated by synapse at #{Time.now}\n"]

  # The "main" context is special and is the top level
  @contexts['main'].each do |option|
    base_config << "#{option};"
  end
  base_config << "\n"

  # http and streams are generated separately
  @contexts.keys.select{|key| !(["main", "http", "stream"].include?(key))}.each do |context|
    base_config << "#{context} {"
    @contexts[context].each do |option|
      base_config << "\t#{option};"
    end
    base_config << "}\n"
  end
  return base_config
end

#generate_config(watchers) ⇒ Object

generates a new config based on the state of the watchers



86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
# File 'lib/synapse/config_generator/nginx.rb', line 86

def generate_config(watchers)
  new_config = generate_base_config

  http, stream = [], []
  watchers.each do |watcher|
    watcher_config = watcher.config_for_generator[name]
    next if watcher_config['disabled']
    # There seems to be no way to have empty TCP listeners ... just
    # don't bind the port at all? ... idk
    next if watcher_config['mode'] == 'tcp' && watcher.backends.empty?

    section = case watcher_config['mode']
      when 'http'
        http
      when 'tcp'
        stream
      else
        raise ArgumentError, "synapse does not understand #{watcher_config['mode']} as a service mode"
    end
    section << generate_server(watcher).flatten
    section << generate_upstream(watcher).flatten
  end

  unless http.empty?
    new_config << 'http {'
    new_config.concat(http.flatten)
    new_config << "}\n"
  end

  unless stream.empty?
    new_config << 'stream {'
    new_config.concat(stream.flatten)
    new_config << "}\n"
  end

  log.debug "synapse: new nginx config: #{new_config}"
  return new_config.flatten.join("\n")
end

#generate_proxy(mode, upstream_name, empty_upstream) ⇒ Object

Nginx has some annoying differences between how upstreams in the http (http) module and the stream (tcp) module address upstreams



180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
# File 'lib/synapse/config_generator/nginx.rb', line 180

def generate_proxy(mode, upstream_name, empty_upstream)
  upstream_name = "http://#{upstream_name}" if mode == 'http'

  case mode
  when 'http'
    if empty_upstream
      value = "\t\t\treturn 503;"
    else
      value = "\t\t\tproxy_pass #{upstream_name};"
    end
    stanza = [
      "\t\tlocation / {",
      value,
      "\t\t}"
    ]
  when 'tcp'
    stanza = [
      "\t\tproxy_pass #{upstream_name};",
    ]
  else
    []
  end
end

#generate_server(watcher) ⇒ Object



146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
# File 'lib/synapse/config_generator/nginx.rb', line 146

def generate_server(watcher)
  watcher_config = watcher.config_for_generator[name]
  unless watcher_config.has_key?('port')
    log.debug "synapse: not generating server stanza for watcher #{watcher.name} because it has no port defined"
    return []
  else
    port = watcher_config['port']
  end

  listen_address = (
    watcher_config['listen_address'] ||
    opts['listen_address'] ||
    'localhost'
  )

  listen_line= [
    "\t\tlisten",
    "#{listen_address}:#{port};",
    watcher_config['listen_options']
  ].compact.join(' ')


  upstream_name = watcher_config.fetch('upstream_name', watcher.name)
  stanza = [
    "\tserver {",
    listen_line,
    watcher_config['server'].map {|c| "\t\t#{c};"},
    generate_proxy(watcher_config['mode'], upstream_name, watcher.backends.empty?),
    "\t}",
  ]
end

#generate_upstream(watcher) ⇒ Object



204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
# File 'lib/synapse/config_generator/nginx.rb', line 204

def generate_upstream(watcher)
  backends = {}
  watcher_config = watcher.config_for_generator[name]
  upstream_name = watcher_config.fetch('upstream_name', watcher.name)

  watcher.backends.each {|b| backends[construct_name(b)] = b}

  # nginx doesn't like upstreams with no backends?
  return [] if backends.empty?

  keys = case watcher_config['upstream_order']
  when 'asc'
    backends.keys.sort
  when 'desc'
    backends.keys.sort.reverse
  when 'no_shuffle'
    backends.keys
  else
    backends.keys.shuffle
  end

  stanza = [
    "\tupstream #{upstream_name} {",
    watcher_config['upstream'].map {|c| "\t\t#{c};"},
    keys.map {|backend_name|
      backend = backends[backend_name]
      b = "\t\tserver #{backend['host']}:#{backend['port']}"
      b = "#{b} #{watcher_config['server_options']}" if watcher_config['server_options']
      "#{b};"
    },
    "\t}"
  ]
end

#normalize_watcher_provided_config(service_watcher_name, service_watcher_config) ⇒ Object



52
53
54
55
56
57
58
59
60
61
62
63
64
# File 'lib/synapse/config_generator/nginx.rb', line 52

def normalize_watcher_provided_config(service_watcher_name, service_watcher_config)
  service_watcher_config = super(service_watcher_name, service_watcher_config)
  defaults = {
    'mode' => 'http',
    'upstream' => [],
    'server' => [],
    'disabled' => false,
  }
  unless service_watcher_config.include?('port')
    log.warn "synapse: service #{service_watcher_name}: nginx config does not include a port; only upstream sections for the service will be created; you must move traffic there manually using server sections"
  end
  defaults.merge(service_watcher_config)
end

#restartObject

restarts nginx if the time is right



263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
# File 'lib/synapse/config_generator/nginx.rb', line 263

def restart
  if @time < @next_restart
    log.info "synapse: at time #{@time} waiting until #{@next_restart} to restart"
    return
  end

  @next_restart = @time + @restart_interval
  @next_restart += rand(@restart_jitter * @restart_interval + 1)

  # do the actual restart
  unless @has_started
    log.info "synapse: attempting to run #{opts['start_command']} to get nginx started"
    log.info 'synapse: this can fail if nginx is already running'
    res = `#{opts['start_command']}`.chomp
    @has_started = true
  end

  res = `#{opts['reload_command']}`.chomp
  unless $?.success?
    log.error "failed to reload nginx via #{opts['reload_command']}: #{res}"
    return
  end
  log.info "synapse: restarted nginx"

  @restart_required = false
end

#tick(watchers) ⇒ Object



66
67
68
69
70
71
72
# File 'lib/synapse/config_generator/nginx.rb', line 66

def tick(watchers)
  @time += 1

  # We potentially have to restart if the restart was rate limited
  # in the original call to update_config
  restart if opts['do_reloads'] && @restart_required
end

#update_config(watchers) ⇒ Object



74
75
76
77
78
79
80
81
82
83
# File 'lib/synapse/config_generator/nginx.rb', line 74

def update_config(watchers)
  # generate a new config
  new_config = generate_config(watchers)

  # if we write config files, lets do that and then possibly restart
  if opts['do_writes']
    @restart_required = write_config(new_config)
    restart if opts['do_reloads'] && @restart_required
  end
end

#write_config(new_config) ⇒ Object

writes the config



239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
# File 'lib/synapse/config_generator/nginx.rb', line 239

def write_config(new_config)
  begin
    old_config = File.read(opts['config_file_path'])
  rescue Errno::ENOENT => e
    log.info "synapse: could not open nginx config file at #{opts['config_file_path']}"
    old_config = ""
  end

  if old_config == new_config
    return false
  else
    File.open(opts['config_file_path'],'w') {|f| f.write(new_config)}
    check = `#{opts['check_command']}`.chomp
    unless $?.success?
      log.error "synapse: nginx configuration is invalid according to #{opts['check_command']}!"
      log.error 'synapse: not restarting nginx as a result'
      return false
    end

    return true
  end
end