Class: Skylight::Core::Config

Inherits:
Object
  • Object
show all
Includes:
Util::Logging
Defined in:
lib/skylight/core/config.rb

Constant Summary collapse

MUTEX =

This constant is part of a private API. You should avoid using this constant if possible, as it may be removed or be changed in the future.

Mutex.new

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Methods included from Util::Logging

#config_for_logging, #debug, #error, #fmt, #info, #log, #log_context, #log_env_prefix, #raise_on_error?, #t, #trace, #trace?, #warn

Constructor Details

#initialize(*args) ⇒ Config

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

Returns a new instance of Config.



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
# File 'lib/skylight/core/config.rb', line 94

def initialize(*args)
  attrs = {}

  if Hash === args.last
    attrs = args.pop.dup
  end

  @values   = {}
  @priority = {}
  @regexp   = nil
  @alert_logger = nil
  @logger = nil

  p = attrs.delete(:priority)

  if @environment = args[0]
    @regexp = /^#{Regexp.escape(@environment)}\.(.+)$/
  end

  attrs.each do |k, v|
    self[k] = v
  end

  if p
    p.each do |k, v|
      @priority[self.class.remap_key(k)] = v
    end
  end
end

Instance Attribute Details

#environmentObject (readonly)

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.



91
92
93
# File 'lib/skylight/core/config.rb', line 91

def environment
  @environment
end

Class Method Details

.default_valuesObject

Default values for Skylight configuration keys



48
49
50
51
52
53
54
55
56
57
58
# File 'lib/skylight/core/config.rb', line 48

def self.default_values
  {
    :log_file             => '-'.freeze,
    :log_level            => 'INFO'.freeze,
    :alert_log_file       => '-'.freeze,
    :log_sql_parse_errors => true,
    :enable_segments      => true,
    :enable_sidekiq       => false,
    :'heroku.dyno_info_path' => '/etc/heroku/dyno'
  }
end

.env_matcherObject



20
# File 'lib/skylight/core/config.rb', line 20

def self.env_matcher; /^(?:SK|SKYLIGHT)_(.+)$/ end

.env_prefixObject



21
# File 'lib/skylight/core/config.rb', line 21

def self.env_prefix; "SKYLIGHT_" end

.env_to_keyObject

Map environment variable keys with Skylight configuration keys



24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
# File 'lib/skylight/core/config.rb', line 24

def self.env_to_key
  {
    # == Logging ==
    'LOG_FILE'       => :log_file,
    'LOG_LEVEL'      => :log_level,
    'ALERT_LOG_FILE' => :alert_log_file,
    'LOG_SQL_PARSE_ERRORS' => :log_sql_parse_errors,

    # == Proxy ==
    'PROXY_URL' => :proxy_url,

    # == Instrumenter ==
    "ENABLE_SEGMENTS" => :enable_segments,
    "ENABLE_SIDEKIQ" => :enable_sidekiq,

    # == User config settings ==
    "USER_CONFIG_PATH" => :'user_config_path',

    # == Heroku settings ==
    "HEROKU_DYNO_INFO_PATH" => :'heroku.dyno_info_path'
  }
end

.legacy_keysObject

Maps legacy config keys to new config keys



80
81
82
83
# File 'lib/skylight/core/config.rb', line 80

def self.legacy_keys
  # No legacy keys for now
  {}
end

.load(opts = {}, env = ENV) ⇒ Object



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
149
150
151
152
153
154
155
156
157
# File 'lib/skylight/core/config.rb', line 124

def self.load(opts = {}, env = ENV)
  attrs   = {}
  version = nil

  path = opts.delete(:file)
  environment = opts.delete(:environment)

  if path
    error = nil
    begin
      attrs = YAML.load(ERB.new(File.read(path)).result)
      error = "empty file" unless attrs
      error = "invalid format" if attrs && !attrs.is_a?(Hash)
    rescue Exception => e
      error = e.message
    end

    raise ConfigError, "could not load config file; msg=#{error}" if error

    version = File.mtime(path).to_i
  end

  if env
    attrs[:priority] = remap_env(env)
  end

  config = new(environment, attrs)

  opts.each do |k, v|
    config[k] = v
  end

  config
end

.log_nameObject



17
# File 'lib/skylight/core/config.rb', line 17

def self.log_name; "Skylight" end

.native_env_keysObject



71
72
73
74
75
76
77
# File 'lib/skylight/core/config.rb', line 71

def self.native_env_keys
  [
    :version,
    :root,
    :proxy_url
  ]
end

.remap_env(env) ⇒ Object

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.



165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
# File 'lib/skylight/core/config.rb', line 165

def self.remap_env(env)
  ret = {}

  return ret unless env

  # Only set if it exists, we don't want to set to a nil value
  if proxy_url = Util::Proxy.detect_url(env)
    ret[:proxy_url] = proxy_url
  end

  env.each do |k, val|
    next unless k =~ env_matcher

    if key = env_to_key[$1]
      ret[key] =
        case val
        when /^false$/i      then false
        when /^true$/i       then true
        when /^(nil|null)$/i then nil
        when /^\d+$/         then val.to_i
        when /^\d+\.\d+$/    then val.to_f
        else val
        end
    end
  end

  ret
end

.remap_key(key) ⇒ Object



159
160
161
162
# File 'lib/skylight/core/config.rb', line 159

def self.remap_key(key)
  key = key.to_sym
  legacy_keys[key] || key
end

.required_keysObject



60
61
62
63
# File 'lib/skylight/core/config.rb', line 60

def self.required_keys
  # Nothing is required in this base class.
  {}
end

.server_validated_keysObject



65
66
67
68
69
# File 'lib/skylight/core/config.rb', line 65

def self.server_validated_keys
  # Nothing is validated for now, but this is a list of symbols
  # for the key we want to validate.
  []
end

.service_nameObject



18
# File 'lib/skylight/core/config.rb', line 18

def self.service_name; log_name end

.support_emailObject



19
# File 'lib/skylight/core/config.rb', line 19

def self.support_email; "[email protected]" end

.validatorsObject



85
86
87
88
# File 'lib/skylight/core/config.rb', line 85

def self.validators
  # None for now
  {}
end

Instance Method Details

#alert_loggerObject



388
389
390
391
392
393
394
395
396
397
398
399
400
# File 'lib/skylight/core/config.rb', line 388

def alert_logger
  @alert_logger ||= MUTEX.synchronize do
    unless l = @alert_logger
      out = get(:alert_log_file)
      out = Util::AlertLogger.new(load_logger) if out == '-'

      l = create_logger(out)
      l.level = Logger::DEBUG
    end

    l
  end
end

#alert_logger=(logger) ⇒ Object



402
403
404
# File 'lib/skylight/core/config.rb', line 402

def alert_logger=(logger)
  @alert_logger = logger
end

#check_file_permissions(file, key) ⇒ Object



215
216
217
218
219
220
221
222
223
224
225
226
227
228
# File 'lib/skylight/core/config.rb', line 215

def check_file_permissions(file, key)
  file_root = File.dirname(file)

  # Try to make the directory, don't blow up if we can't. Our writable? check will fail later.
  FileUtils.mkdir_p file_root rescue nil

  if File.exist?(file) && !FileTest.writable?(file)
    raise ConfigError, "File `#{file}` is not writable. Please set #{key} in your config to a writable path"
  end

  unless FileTest.writable?(file_root)
    raise ConfigError, "Directory `#{file_root}` is not writable. Please set #{key} in your config to a writable path"
  end
end

#check_logfile_permissions(log_file, key) ⇒ Object



230
231
232
233
234
# File 'lib/skylight/core/config.rb', line 230

def check_logfile_permissions(log_file, key)
  return if log_file == '-' # STDOUT
  log_file = File.expand_path(log_file, root)
  check_file_permissions(log_file, key)
end

#duration_ms(key, default = nil) ⇒ Object



295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
# File 'lib/skylight/core/config.rb', line 295

def duration_ms(key, default = nil)
  if (v = self[key]) && v.to_s =~ /^\s*(\d+)(s|sec|ms|micros|nanos)?\s*$/
    v = $1.to_i
    case $2
    when "ms"
      v
    when "micros"
      v / 1_000
    when "nanos"
      v / 1_000_000
    else # "s", "sec", nil
      v * 1000
    end
  else
    default
  end
end

#enable_segments?Boolean

Returns:

  • (Boolean)


406
407
408
# File 'lib/skylight/core/config.rb', line 406

def enable_segments?
  !!get(:enable_segments)
end

#enable_sidekiq?Boolean

Returns:

  • (Boolean)


410
411
412
# File 'lib/skylight/core/config.rb', line 410

def enable_sidekiq?
  !!get(:enable_sidekiq)
end

#gcObject

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.



351
352
353
# File 'lib/skylight/core/config.rb', line 351

def gc
  @gc ||= GC.new(self, get('gc.profiler', VM::GC.new))
end

#get(key, default = nil, &blk) ⇒ Object Also known as: []



241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
# File 'lib/skylight/core/config.rb', line 241

def get(key, default = nil, &blk)
  key = self.class.remap_key(key)

  return @priority[key] if @priority.key?(key)
  return @values[key]   if @values.key?(key)
  return self.class.default_values[key] if self.class.default_values.key?(key)

  if default
    return default
  elsif blk
    return blk.call(key)
  end

  nil
end

#ignored_endpointsObject

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.



356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
# File 'lib/skylight/core/config.rb', line 356

def ignored_endpoints
  @ignored_endpoints ||=
    begin
      ignored_endpoints = get(:ignored_endpoints)

      # If, for some odd reason you have a comma in your endpoint name, use the
      # YML config instead.
      if ignored_endpoints.is_a?(String)
        ignored_endpoints = ignored_endpoints.split(/\s*,\s*/)
      end

      val = Array(get(:ignored_endpoint))
      val.concat(Array(ignored_endpoints))
      val
    end
end

#key?(key) ⇒ Boolean

Returns:

  • (Boolean)


236
237
238
239
# File 'lib/skylight/core/config.rb', line 236

def key?(key)
  key = self.class.remap_key(key)
  @priority.key?(key) || @values.key?(key)
end

#loggerObject



377
378
379
380
381
382
# File 'lib/skylight/core/config.rb', line 377

def logger
  @logger ||=
    MUTEX.synchronize do
      load_logger
    end
end

#logger=(logger) ⇒ Object



384
385
386
# File 'lib/skylight/core/config.rb', line 384

def logger=(logger)
  @logger = logger
end

#on_heroku?Boolean

Returns:

  • (Boolean)


418
419
420
# File 'lib/skylight/core/config.rb', line 418

def on_heroku?
  File.exist?(get(:'heroku.dyno_info_path'))
end

#rootObject



373
374
375
# File 'lib/skylight/core/config.rb', line 373

def root
  self[:root] || Dir.pwd
end

#send_or_get(v) ⇒ Object



291
292
293
# File 'lib/skylight/core/config.rb', line 291

def send_or_get(v)
  respond_to?(v) ? send(v) : get(v)
end

#set(key, val, scope = nil) ⇒ Object Also known as: []=



259
260
261
262
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
# File 'lib/skylight/core/config.rb', line 259

def set(key, val, scope = nil)
  if scope
    key = [scope, key].join('.')
  end

  if Hash === val
    val.each do |k, v|
      set(k, v, key)
    end
  else
    k = self.class.remap_key(key)

    if validator = self.class.validators[k]
      blk, msg = validator

      unless blk.call(val, self)
        error_msg = "invalid value for #{k} (#{val})"
        error_msg << ", #{msg}" if msg
        raise ConfigError, error_msg
      end
    end

    if @regexp && k =~ @regexp
      @priority[$1.to_sym] = val
    end

    @values[k] = val
  end
end

#to_jsonObject



313
314
315
316
317
318
319
320
# File 'lib/skylight/core/config.rb', line 313

def to_json
  JSON.generate(
    config: {
      priority: @priority,
      values:   @values
    }
  )
end

#to_native_envObject



322
323
324
325
326
327
328
329
330
331
332
333
334
# File 'lib/skylight/core/config.rb', line 322

def to_native_env
  ret = []

  self.class.native_env_keys.each do |key|
    value = send_or_get(key)
    unless value.nil?
      env_key = self.class.env_to_key.key(key) || key.upcase
      ret << "#{self.class.env_prefix}#{env_key}" << cast_for_env(value)
    end
  end

  ret
end

#user_configObject



414
415
416
# File 'lib/skylight/core/config.rb', line 414

def user_config
  @user_config ||= UserConfig.new(self)
end

#validate!Object

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.



195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
# File 'lib/skylight/core/config.rb', line 195

def validate!
  self.class.required_keys.each do |k, v|
    unless get(k)
      raise ConfigError, "#{v} required"
    end
  end

  log_file = self[:log_file]
  alert_log_file = self[:alert_log_file]

  check_logfile_permissions(log_file, "log_file")
  check_logfile_permissions(alert_log_file, "alert_log_file")

  true
end

#validate_with_serverObject



211
212
213
# File 'lib/skylight/core/config.rb', line 211

def validate_with_server
  true
end

#versionObject

Helpers =====


346
347
348
# File 'lib/skylight/core/config.rb', line 346

def version
  VERSION
end

#write(path) ⇒ Object



336
337
338
# File 'lib/skylight/core/config.rb', line 336

def write(path)
  raise "not implemented"
end