Class: BmcDaemonLib::Conf

Inherits:
Object
  • Object
show all
Extended by:
Chamber
Defined in:
lib/bmc-daemon-lib/conf.rb

Constant Summary collapse

PIDFILE_DIR =
"/tmp/"

Class Attribute Summary collapse

Class Method Summary collapse

Class Attribute Details

.app_envObject

Returns the value of attribute app_env.



18
19
20
# File 'lib/bmc-daemon-lib/conf.rb', line 18

def app_env
  @app_env
end

.app_libsObject (readonly)

Returns the value of attribute app_libs.



20
21
22
# File 'lib/bmc-daemon-lib/conf.rb', line 20

def app_libs
  @app_libs
end

.app_nameObject (readonly)

Returns the value of attribute app_name.



21
22
23
# File 'lib/bmc-daemon-lib/conf.rb', line 21

def app_name
  @app_name
end

.app_rootObject (readonly)

Returns the value of attribute app_root.



19
20
21
# File 'lib/bmc-daemon-lib/conf.rb', line 19

def app_root
  @app_root
end

.app_specObject (readonly)

Returns the value of attribute app_spec.



24
25
26
# File 'lib/bmc-daemon-lib/conf.rb', line 24

def app_spec
  @app_spec
end

.app_startedObject (readonly)

Returns the value of attribute app_started.



23
24
25
# File 'lib/bmc-daemon-lib/conf.rb', line 23

def app_started
  @app_started
end

.app_verObject (readonly)

Returns the value of attribute app_ver.



22
23
24
# File 'lib/bmc-daemon-lib/conf.rb', line 22

def app_ver
  @app_ver
end

.filesObject (readonly)

Returns the value of attribute files.



25
26
27
# File 'lib/bmc-daemon-lib/conf.rb', line 25

def files
  @files
end

.hostObject (readonly)

Returns the value of attribute host.



26
27
28
# File 'lib/bmc-daemon-lib/conf.rb', line 26

def host
  @host
end

Class Method Details

.add_config(path) ⇒ Object



278
279
280
281
282
283
284
285
286
287
288
289
# File 'lib/bmc-daemon-lib/conf.rb', line 278

def self.add_config path
  # Skip if path is not readable
  return unless path && File.readable?(path)

  # Check if Chamber's behaviour may cause problems with hyphens
  if File.basename(path).include?'-'
    log :conf, "WARNING: files containting dashes may cause problems with Chamber"
  end

  # Store the files
  @files << File.expand_path(path) 
end

.at(*path) ⇒ Object

Direct access to any depth



108
109
110
111
# File 'lib/bmc-daemon-lib/conf.rb', line 108

def self.at *path
  ensure_init
  path.reduce(Conf) { |m, key| m && m[key.to_s] }
end

.dumpObject



102
103
104
105
# File 'lib/bmc-daemon-lib/conf.rb', line 102

def self.dump
  ensure_init
  to_hash.to_yaml(indent: 4, useheader: true, useversion: false )
end

.ensure_initObject



310
311
312
313
314
# File 'lib/bmc-daemon-lib/conf.rb', line 310

def self.ensure_init
  unless @initialized
    fail ConfigInitiRequired, "ensure_init: Conf.init(app_root) should be invoked beforehand"
  end
end

.feature?(name) ⇒ Boolean

Returns:

  • (Boolean)


139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
# File 'lib/bmc-daemon-lib/conf.rb', line 139

def self.feature? name
  ensure_init

  # Guess if the specific feature si available
  case name
  when :newrelic
    return false if Gem.datadir('newrelic_rpm').nil?
    return false if self.at(:newrelic, :enabled) == false
    return false if self.at(:newrelic, :disabled) == true
    return self.at(:newrelic, :license) || false
  when :rollbar
    return false if Gem.datadir('rollbar').nil?
    return false if self.at(:rollbar, :enabled) == false
    return false if self.at(:rollbar, :disabled) == true
    return self.at(:rollbar, :token) || false
  end
  return false
end

.generate(what) ⇒ Object

Defaults generators



159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
# File 'lib/bmc-daemon-lib/conf.rb', line 159

def self.generate what
  ensure_init
  return case what

  when :user_agent
    "#{@app_name}/#{@app_ver}" if @app_name && @app_ver

  when :config_defaults
    "#{@app_root}/defaults.yml" if @app_root

  when :config_etc
    "/etc/#{@app_name}.yml" if @app_name

  when :process_name
    parts = [@app_name, @app_env]
    parts << self[:port] if self[:port]
    parts.join('-')

  when :pidfile
    process_name = self.generate(:process_name)
    File.expand_path "#{process_name}.pid", PIDFILE_DIR

  when :config_message
    config_defaults = self.generate(:config_defaults)
    config_etc = self.generate(:config_etc)

    "A default configuration is available (#{config_defaults}) and can be copied to the default location (#{config_etc}): \n sudo cp #{config_defaults} #{config_etc}"
  end
end

.init(app_root) ⇒ Object



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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
# File 'lib/bmc-daemon-lib/conf.rb', line 29

def self.init app_root
  # Permanent flags
  @initialized  = true
  @app_started  = Time.now

  # Default values
  @files        ||= []
  @app_name     ||= "app_name"
  @app_env      ||= "production"
  @host         ||= `hostname`.to_s.chomp.split(".").first

  # Store and clean app_root
  @app_root = File.expand_path(app_root)
  gemspec_path = "#{@app_root}/*.gemspec"

  # Try to find any gemspec file
  matches   = Dir[gemspec_path]
  fail ConfigGemspecMissing, "gemspec file not found: #{gemspec_path}" if matches.size < 1
  fail ConfigGemspecNotUnique, "gemspec file not found: #{gemspec_path}" if matches.size > 1

  # Load Gemspec (just the only match)
  @spec     = Gem::Specification::load(matches.first)
  fail ConfigGemspecInvalid, "gemspec not readable: #{gemspec_path}" unless @spec

  # Extract useful information from gemspec
  @app_name = @spec.name.to_s
  @app_ver  = @spec.version.to_s
  fail ConfigMissingParameter, "gemspec: missing name" unless @app_name
  fail ConfigMissingParameter, "gemspec: missing version" unless @app_ver

  # Now we know app_name, initalize app_libs
  @app_libs = File.expand_path("lib/#{@app_name}/", @app_root)

  # By default, Newrelic is disabled
  ENV["NEWRELIC_AGENT_ENABLED"] = "false"

  # Add other config files
  add_config generate(:config_defaults)
  add_config generate(:config_etc)

  # Return something
  return @app_name
end

.load_filesObject



274
275
276
# File 'lib/bmc-daemon-lib/conf.rb', line 274

def self.load_files
  load files: @files, namespaces: { environment: @app_env }
end

.log(origin, message) ⇒ Object



248
249
250
251
252
253
254
255
# File 'lib/bmc-daemon-lib/conf.rb', line 248

def self.log origin, message
  printf(
    "%s %-14s %s \n",
    Time.now.strftime("%Y-%m-%d %H:%M:%S"),
    origin,
    message
    )
end

.logfile(pipe) ⇒ Object



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
# File 'lib/bmc-daemon-lib/conf.rb', line 113

def self.logfile pipe
  # Build logfile from Conf
  logfile = self.logfile_path(pipe)
  return nil if logfile.nil?

  # Check that we'll be able to create logfiles
  if File.exists?(logfile)
    # File is there, is it writable ?
    unless File.writable?(logfile)
      log :conf, "logging [#{pipe}] disabled: file not writable [#{logfile}]"
      return nil
    end
  else
    # No file here, can we create it ?
    logdir = File.dirname(logfile)
    unless File.writable?(logdir)
      log :conf, "logging [#{pipe}] disabled: directory not writable [#{logdir}]"
      return nil
    end
  end

  # OK, return a clean file path
  log :conf, "logging [#{pipe}] to [#{logfile}]"
  return logfile
end

.logfile_path(pipe) ⇒ Object



291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
# File 'lib/bmc-daemon-lib/conf.rb', line 291

def self.logfile_path pipe
  # Access configuration
  path      = self.at :logs, :path
  specific  = self.at :logs, pipe
  default   = self.at :logs, :default

  # Ignore if explicitely disabled
  return nil if specific == false

  # Fallback on default path if not provided,
  specific ||= default
  specific ||= "default.log"

  # Build logfile_path
  File.expand_path specific.to_s, path.to_s
end

.newrelic_init_app_name(conf) ⇒ Object



259
260
261
262
263
264
265
266
267
268
269
270
271
272
# File 'lib/bmc-daemon-lib/conf.rb', line 259

def self.newrelic_init_app_name conf
  # Ignore if already set
  return if conf[:app_name]

  # Stack all those parts
  stack = []
  stack << (conf[:prefix] || @app_name)
  stack << conf[:platform] if conf[:platform]
  stack << @app_env
  text = stack.join('-')

  # Return a composite appname
  conf[:app_name] = "#{text}; #{text}-#{@host}"
end

.prepare(args = {}) ⇒ Object



73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
# File 'lib/bmc-daemon-lib/conf.rb', line 73

def self.prepare args = {}
  ensure_init

  # Add extra config file and load them all
  add_config args[:config]
  reload!

  # Set Rack env
  ENV["RACK_ENV"] = @app_env.to_s

  # Set up encodings
  Encoding.default_internal = "utf-8"
  Encoding.default_external = "utf-8"

  # Try to access any key to force parsing of the files
  self[:dummy]

rescue Psych::SyntaxError => e
  fail ConfigParseError, e.message
rescue StandardError => e
  fail ConfigOtherError, "#{e.message} \n #{e.backtrace.to_yaml}"
end

.prepare_newrelicObject



189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
# File 'lib/bmc-daemon-lib/conf.rb', line 189

def self.prepare_newrelic
  # Disable if no config present
  return unless self.feature?(:newrelic)

  # Ok, let's start
  log :conf, "prepare NewRelic"
  conf = self[:newrelic]

  # Enable GC profiler
  GC::Profiler.enable

  # Build NewRelic app_name if not provided as-is
  self.newrelic_init_app_name(conf)

  # Set env variables
  ENV["NEW_RELIC_AGENT_ENABLED"] = "true"
  ENV["NEW_RELIC_LOG"] = logfile_path(:newrelic)
  ENV["NEW_RELIC_LICENSE_KEY"] = conf[:license].to_s
  ENV["NEW_RELIC_APP_NAME"] = conf[:app_name].to_s

  # logger_newrelic = Logger.new('/tmp/newrelic.log')
  # logger_newrelic.debug Time.now()
  # Start the agent
  # NewRelic::Agent.manual_start({
  #   agent_enabled: true,
  #   log: logger_newrelic,
  #   env: @app_env,
  #   license_key: conf[:license].to_s,
  #   app_name: conf[:app_name].to_s,
  # })
end

.prepare_rollbarObject



221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
# File 'lib/bmc-daemon-lib/conf.rb', line 221

def self.prepare_rollbar
  # Disable if no config present
  unless self.feature?(:rollbar)
    Rollbar.configure do |config|
      config.enabled = false
    end
    return
  end

  # Ok, let's start
  log :conf, "prepare Rollbar"
  conf = self[:rollbar]

  # Configure
  Rollbar.configure do |config|
    config.enabled = true
    config.access_token = conf[:token].to_s
    config.code_version = @app_version
    config.environment  = @app_env
    config.logger       = LoggerPool.instance.get(:rollbar)
    config.use_async = true
  end

  # Notify startup
  Rollbar.info("[#{@app_ver}] #{@host}")
end

.reload!Object

Reload files



97
98
99
100
# File 'lib/bmc-daemon-lib/conf.rb', line 97

def self.reload!
  ensure_init
  load_files
end