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
51
52
53
# 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 = false
  @has_started = false

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

  # a place to store generated server + upstream stanzas, and watcher
  # revisions so we can save CPU on updates by not re-computing stanzas
  @servers_cache = {}
  @upstreams_cache = {}
  @watcher_revisions = {}
end

Instance Method Details

#construct_name(backend) ⇒ Object

used to build unique, consistent nginx names for backends



334
335
336
337
338
339
340
341
# File 'lib/synapse/config_generator/nginx.rb', line 334

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



151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
# File 'lib/synapse/config_generator/nginx.rb', line 151

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



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
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
# File 'lib/synapse/config_generator/nginx.rb', line 96

def generate_config(watchers)
  new_config = generate_base_config

  http = (@contexts['http'] || []).collect {|option| "\t#{option};"}
  stream = (@contexts['stream'] || []).collect {|option| "\t#{option};"}

  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?


    # Only regenerate if something actually changed. This saves a lot
    # of CPU load for high churn systems
    regenerate = watcher.revision != @watcher_revisions[watcher.name] ||
                 @servers_cache[watcher.name].nil? ||
                 @upstreams_cache[watcher.name].nil?

    if regenerate
      @servers_cache[watcher.name] = generate_server(watcher).flatten
      @upstreams_cache[watcher.name] = generate_upstream(watcher).flatten
      @watcher_revisions[watcher.name] = watcher.revision
    end

    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 << @servers_cache[watcher.name]
    section << @upstreams_cache[watcher.name]
  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



206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
# File 'lib/synapse/config_generator/nginx.rb', line 206

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



171
172
173
174
175
176
177
178
179
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 171

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



230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
# File 'lib/synapse/config_generator/nginx.rb', line 230

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?

  # Note that because we use the config file as the source of truth
  # for whether or not to reload, we want some kind of sorted order
  # by default, in this case we choose asc
  keys = case watcher_config['upstream_order']
  when 'desc'
    backends.keys.sort.reverse
  when 'shuffle'
    backends.keys.shuffle
  when 'no_shuffle'
    backends.keys
  else
    backends.keys.sort
  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



55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
# File 'lib/synapse/config_generator/nginx.rb', line 55

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') || service_watcher_config['disabled']
    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



311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
# File 'lib/synapse/config_generator/nginx.rb', line 311

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)

  # On the very first restart we may need to start
  start unless @has_started

  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

#startObject



297
298
299
300
301
302
303
304
305
306
307
308
# File 'lib/synapse/config_generator/nginx.rb', line 297

def start
  log.info "synapse: attempting to run #{opts['start_command']} to get nginx started"
  log.info 'synapse: this can fail if nginx is already running'
  begin
    `#{opts['start_command']}`.chomp
  rescue Exception => e
    log.warn "synapse: error in NGINX start: #{e.inspect}"
    log.warn e.backtrace
  ensure
    @has_started = true
  end
end

#tick(watchers) ⇒ Object



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

def tick(watchers)
  @time += 1

  # Always ensure we try to start at least once
  # Note that this should only trigger during error cases where for
  # some reason Synapse could not start NGINX during the initial restart
  start if opts['do_reloads'] && !@has_started

  # 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



84
85
86
87
88
89
90
91
92
93
# File 'lib/synapse/config_generator/nginx.rb', line 84

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



268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
# File 'lib/synapse/config_generator/nginx.rb', line 268

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

  # The first line of the config files contain a timestamp, so to prevent
  # un-needed restarts, only compare after that. We do not split on
  # newlines and compare because this is called a lot, and we need to be
  # as CPU efficient as possible.
  old_version =  old_config[(old_config.index("\n") || 0) + 1..-1]
  new_version =  new_config[(new_config.index("\n") || 0) + 1..-1]
  if old_version == new_version
    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