omf_base 1.0

Sign up to get free protection for your applications and to get access to all the features.
data/.gitignore ADDED
@@ -0,0 +1,2 @@
1
+ pkg
2
+ .project
data/Gemfile ADDED
@@ -0,0 +1,4 @@
1
+ source "http://rubygems.org"
2
+
3
+ # Specify your gem's dependencies in omf_web.gemspec
4
+ gemspec
data/README.md ADDED
@@ -0,0 +1,10 @@
1
+
2
+ # OMF Base
3
+
4
+ This GEM contains a few commonly used helper classes used in various places inside the
5
+ OMF related libraries. This used to be omf_common, but that by now ballooned into something
6
+ much too big for many other tasks.
7
+
8
+ ## Install
9
+
10
+ gem install omf_base
data/Rakefile ADDED
@@ -0,0 +1,10 @@
1
+ require 'rake/testtask'
2
+ require "bundler/gem_tasks"
3
+
4
+ task :default => :test
5
+
6
+ Rake::TestTask.new do |t|
7
+ t.libs << 'test'
8
+ t.pattern = "test/**/*_spec.rb"
9
+ t.verbose = true
10
+ end
@@ -0,0 +1,90 @@
1
+
2
+ if $0 == __FILE__
3
+ module OMF; module Common; end; end
4
+ end
5
+
6
+ module OMF::Base::YAML
7
+
8
+ class YamlFileNotFound < Exception; end
9
+
10
+ # A method to load YAML files
11
+ #
12
+ # file_name - Name of file to load
13
+ # opts -
14
+ # => :default - value to use if file can't be loaded
15
+ # => :path - array of directories to look for file
16
+ #
17
+ # raise YamlFileNotFound if YAML file can't be found
18
+ #
19
+ def self.load(file_name, opts = {})
20
+ if (file_name.split('.').length == 1)
21
+ file_name = file_name + '.yaml'
22
+ end
23
+
24
+ path = opts[:path] || ['.', File.dirname(__FILE__)]
25
+ begin
26
+ path.each do |d|
27
+ begin
28
+ return _load_file(d + '/' + file_name)
29
+ rescue YamlFileNotFound => ex
30
+ end
31
+ end
32
+ if (default = opts[:default])
33
+ return _symbolize(default)
34
+ end
35
+ raise YamlFileNotFound.new("Can't read YAML file '#{file_name}' in '#{path.join(':')}'")
36
+ end
37
+ end
38
+
39
+ private
40
+
41
+ def self._load_file(file, opts = {})
42
+ begin
43
+ begin
44
+ require 'rbyaml'
45
+ h = RbYAML::load_file(file)
46
+ rescue LoadError => ex
47
+ require 'yaml'
48
+ h = YAML::load_file(file)
49
+ end
50
+ rescue Exception => ex
51
+ unless (h = opts[:default])
52
+ raise YamlFileNotFound.new("Can't read YAML file '#{file}'")
53
+ end
54
+ end
55
+ _symbolize(h)
56
+ end
57
+
58
+
59
+ def self._symbolize(obj)
60
+ if obj.kind_of? Hash
61
+ res = {}
62
+ obj.each do |k, v|
63
+ if k.kind_of? String
64
+ if k.start_with?(":")
65
+ k = k[1 .. -1]
66
+ end
67
+ k = k.to_sym
68
+ end
69
+ res[k] = _symbolize(v)
70
+ end
71
+ return res
72
+ elsif obj.kind_of? Array
73
+ return obj.collect do |el|
74
+ _symbolize(el)
75
+ end
76
+ else
77
+ return obj
78
+ end
79
+ end
80
+ end
81
+
82
+ if $0 == __FILE__
83
+ h = OMF::Base::YAML.load 'foo'#, :default => {':foo' => {:goo=> 3}}
84
+ puts h.inspect
85
+ puts h.keys[0].class
86
+ puts h[:foo].keys[0].class
87
+
88
+ #puts OMF::Base::YAML.load('omf-expctl', :path => ['../../../omf-expctl/etc/omf-expctl']).inspect
89
+
90
+ end
@@ -0,0 +1,187 @@
1
+ #
2
+ # Copyright (c) 2006-2009 National ICT Australia (NICTA), Australia
3
+ #
4
+ # Copyright (c) 2004-2009 WINLAB, Rutgers University, USA
5
+ #
6
+ # Permission is hereby granted, free of charge, to any person obtaining a copy
7
+ # of this software and associated documentation files (the "Software"), to deal
8
+ # in the Software without restriction, including without limitation the rights
9
+ # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10
+ # copies of the Software, and to permit persons to whom the Software is
11
+ # furnished to do so, subject to the following conditions:
12
+ #
13
+ # The above copyright notice and this permission notice shall be included in
14
+ # all copies or substantial portions of the Software.
15
+ #
16
+ # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17
+ # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18
+ # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19
+ # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20
+ # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21
+ # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
22
+ # THE SOFTWARE.
23
+ #
24
+ #
25
+ #
26
+ require 'rubygems'
27
+ require 'date'
28
+ require 'log4r'
29
+ require 'log4r/configurator'
30
+ require 'log4r/yamlconfigurator'
31
+ require 'log4r/outputter/datefileoutputter'
32
+ require 'omf_base/log4r_outputter'
33
+
34
+ #include Log4r
35
+
36
+ module OMF; module Base; end end
37
+
38
+ #
39
+ # An extended object class with support for logging
40
+ #
41
+ module OMF::Base
42
+ module Loggable
43
+ @@logger = nil
44
+ @@rootLoggerName = nil
45
+
46
+
47
+ #
48
+ # Initialize the logger. The 'appName' is used to build some of the defaults.
49
+ # The 'environment' is the name of the root
50
+ # logger. 'AppInstance' and 'appName' are available as parameters
51
+ # in the log configuration file. The 'opts' hash can optionally
52
+ # contain information on how to find a configuration file. The
53
+ # following keys are used:
54
+ #
55
+ # * :environment - Name used for root logger name ['development']
56
+ # * :env - Name of environment variable holding dominant config file
57
+ # * :fileName - Name of config file [#{appName}_log.xml]
58
+ # * :searchPath - Array of directories to look for 'fileName'
59
+ #
60
+ def self.init_log(appName, opts = {})
61
+
62
+ #@@logger = ::Log4r::Logger.new(appName)
63
+ set_environment(opts[:environment] || 'development')
64
+ @@logger = ::Log4r::Logger.new(@@rootLoggerName)
65
+
66
+ configFile = opts[:configFile]
67
+ if (configFile == nil && logEnv = opts[:env])
68
+ configFile = ENV[logEnv]
69
+ end
70
+ if (configFile != nil)
71
+ # Make sure log exists ...
72
+ configFile = File.exists?(configFile) ? configFile : nil
73
+ else
74
+ name = opts[:fileName] || "#{appName}_log4r.yaml"
75
+ if ((searchPath = opts[:searchPath]) != nil)
76
+ searchPath = searchPath.is_a?(Enumerable) ? searchPath : [searchPath]
77
+ logDir = searchPath.find {|dir|
78
+ File.exists?("#{dir}/#{name}")
79
+ }
80
+ #puts "logDir '#{logDir}:#{logDir.class}'"
81
+ configFile = "#{logDir}/#{name}" if logDir != nil
82
+ end
83
+ end
84
+ #puts "config file '#{configFile}'"
85
+ if !(configFile || '').empty?
86
+ ::Log4r::Configurator['appName'] = appName
87
+ begin
88
+ ycfg = YAML.load_file(configFile)
89
+ ::Log4r::YamlConfigurator.decode_yaml(ycfg['log4r'])
90
+ #::Log4r::Configurator.load_xml_file(configFile)
91
+ # rescue ::Log4r::ConfigError => ex
92
+ # @@logger.outputters = ::Log4r::Outputter.stdout
93
+ # # TODO: FIX ME
94
+ # puts("ERROR: Log::Config: #{ex}")
95
+ end
96
+ else
97
+ # set default behavior
98
+ ::Log4r::Logger.global.level = ::Log4r::ALL
99
+ formatter = ::Log4r::PatternFormatter.new(:pattern => "%l %c: %m")
100
+ ::Log4r::StdoutOutputter.new('console', :formatter => formatter)
101
+ @@logger.add 'console'
102
+ #@@logger.outputters = ::Log4r::StdoutOutputter.new('console') #Outputter.stdout
103
+ ##@@logger.outputters = ::Log4r::Outputter.stdout
104
+ end
105
+ end
106
+
107
+ def self.set_environment(root_logger_name)
108
+ if root_logger_name.nil? || root_logger_name.empty?
109
+ # TODO: FIX ME
110
+ puts("ERROR: LObject: Ignoring empty root logger")
111
+ return
112
+ end
113
+ @@rootLoggerName = root_logger_name
114
+ end
115
+
116
+ def self.logger(category)
117
+ raise "Logger not initialized" unless @@logger
118
+
119
+ name = "#{@@rootLoggerName}::#{category}"
120
+ logger = Log4r::Logger[name]
121
+ if logger == nil
122
+ logger = Log4r::Logger.new(name)
123
+ end
124
+ return logger
125
+ end
126
+
127
+ def debug(*message)
128
+ logger = _logger()
129
+ logger.debug(message.join('')) if logger.debug?
130
+ end
131
+
132
+ def info(*message)
133
+ logger = _logger()
134
+ logger.info(message.join('')) if logger.info?
135
+ end
136
+
137
+ def warn(*message)
138
+ logger = _logger()
139
+ logger.warn(message.join('')) if logger.warn?
140
+ end
141
+
142
+ def error(*message)
143
+ logger = _logger()
144
+ logger.error(message.join('')) if logger.error?
145
+ end
146
+
147
+ def fatal(*message)
148
+ logger = _logger()
149
+ logger.fatal(message.join('')) if logger.fatal?
150
+ end
151
+
152
+ def _logger(category = nil)
153
+ unless @logger #&& category.nil?
154
+ cat = self.is_a?(Class) ? self.to_s + 'Class' : self.class.to_s
155
+ if category
156
+ cat = "#{cat}-#{category}"
157
+ end
158
+ @logger = OMF::Base::Loggable.logger(cat)
159
+ end
160
+ return @logger
161
+ end
162
+
163
+ end
164
+
165
+ class LObject
166
+ include Loggable
167
+ extend Loggable
168
+
169
+ def initialize(logCategory = nil)
170
+ _logger(logCategory)
171
+ end
172
+ end
173
+
174
+ end
175
+
176
+ if $0 == __FILE__
177
+ OMF::Base::Loggable.init_log 'foo'
178
+ #puts OMF::Base::Loggable.logger('test').inspect
179
+ o = OMF::Base::LObject.new
180
+ #puts (o.methods - Object.new.methods).sort
181
+ o.debug 'Something happened'
182
+
183
+ o2 = OMF::Base::LObject.new('fancy')
184
+ o2.debug 'Something happened'
185
+
186
+ end
187
+
@@ -0,0 +1,69 @@
1
+
2
+
3
+ require 'log4r/outputter/fileoutputter'
4
+
5
+ module Log4r
6
+ # When daemonizing, the file handler gets closed and we fall over here.
7
+ # The following monkey patch retries once to open the file and write again
8
+ #
9
+ class FileOutputter
10
+
11
+ # def initialize(_name, hash={})
12
+ # raise "#{_name}::#{hash.inspect}"
13
+ # end
14
+
15
+ def write(data)
16
+ #puts ">>> #{data}"
17
+ begin
18
+ @out.print data
19
+ @out.flush
20
+ rescue IOError => ioe # recover from this instead of crash
21
+ # retry once
22
+ unless @retrying
23
+ @retrying = true
24
+ @out = File.new(@filename, (@trunc ? "w" : "a"))
25
+ return write(data)
26
+ end
27
+ Logger.log_internal {"IOError in Outputter '#{@name}'!"}
28
+ Logger.log_internal {ioe}
29
+ close
30
+ rescue NameError => ne
31
+ Logger.log_internal {"Outputter '#{@name}' IO is #{@out.class}!"}
32
+ Logger.log_internal {ne}
33
+ close
34
+ end
35
+ @retrying = false
36
+ end
37
+ end
38
+ end
39
+
40
+ # module OMF; module Common; end end
41
+ #
42
+ # #
43
+ # # An extended object class with support for logging
44
+ # #
45
+ # module OMF::Base
46
+ # module Log4r
47
+ #
48
+ # class DateFileOutputter < ::Log4r::DateFileOutputter
49
+ #
50
+ # def write(data)
51
+ # puts ">>> #{data}"
52
+ # begin
53
+ # @out.print data
54
+ # @out.flush
55
+ # rescue IOError => ioe # recover from this instead of crash
56
+ # Logger.log_internal {"IOError in Outputter '#{@name}'!"}
57
+ # Logger.log_internal {ioe}
58
+ # close
59
+ # rescue NameError => ne
60
+ # Logger.log_internal {"Outputter '#{@name}' IO is #{@out.class}!"}
61
+ # Logger.log_internal {ne}
62
+ # close
63
+ # end
64
+ # end
65
+ # end
66
+ # end
67
+ # end
68
+ #
69
+ # puts "REQUIRE #{OMF::Base::Log4r::DateFileOutputter}"
@@ -0,0 +1,54 @@
1
+ require 'omf_base/lobject'
2
+
3
+ module Thin
4
+ # Overwrite thin's logging mix-in to work more nicely
5
+ # with log4r
6
+ #
7
+ module Logging
8
+ class << self
9
+ attr_writer :trace, :debug, :silent
10
+
11
+ def trace?; !@silent && @trace end
12
+ def debug?; !@silent && @debug end
13
+ def silent?; @silent end
14
+ end
15
+
16
+ # # Global silencer methods
17
+ # def silent
18
+ # Logging.silent?
19
+ # end
20
+ # def silent=(value)
21
+ # Logging.silent = value
22
+ # end
23
+
24
+ # Log a message to the console
25
+ def log(msg)
26
+ (@logger ||= OMF::Base::LObject.new(self.class)).info(msg)
27
+ end
28
+ module_function :log
29
+ public :log
30
+
31
+ # Log a message to the console if tracing is activated
32
+ def trace(msg=nil)
33
+ return unless msg
34
+ (@logger ||= OMF::Base::LObject.new(self.class)).debug(msg)
35
+ end
36
+ module_function :trace
37
+ public :trace
38
+
39
+ # Log a message to the console if debugging is activated
40
+ def debug(msg=nil)
41
+ return unless msg
42
+ (@logger ||= OMF::Base::LObject.new(self.class)).debug(msg)
43
+ end
44
+ module_function :debug
45
+ public :debug
46
+
47
+ # Log an error backtrace if debugging is activated
48
+ def log_error(e = $!)
49
+ (@logger ||= OMF::Base::LObject.new(self.class)).error(e)
50
+ end
51
+ module_function :log_error
52
+ public :log_error
53
+ end
54
+ end
@@ -0,0 +1,115 @@
1
+
2
+ require 'thin'
3
+ require 'omf_base/thin/logging'
4
+
5
+ #
6
+ # Add code to Thin::Connection to verify peer certificate
7
+ #
8
+ module Thin
9
+ class Connection
10
+ def ssl_verify_peer(cert_s)
11
+ true # will be verified later
12
+ end
13
+ end
14
+ end
15
+
16
+ module OMF::Base::Thin
17
+ class Runner < Thin::Runner
18
+ include OMF::Base::Loggable
19
+
20
+ @@instance = nil
21
+
22
+ def self.instance
23
+ @@instance
24
+ end
25
+
26
+ attr_reader :options
27
+
28
+ def initialize(argv, opts = {})
29
+ raise "SINGLETON" if @@instance
30
+
31
+ @argv = argv
32
+ sopts = opts.delete(:ssl) # runner has it's own idea of ssl options
33
+
34
+ # Default options values
35
+ app_name = opts[:app_name] || 'omf_web_app'
36
+ @options = {
37
+ :app_name => app_name,
38
+ :chdir => Dir.pwd,
39
+ :environment => 'development',
40
+ :address => '0.0.0.0',
41
+ :port => Thin::Server::DEFAULT_PORT,
42
+ :timeout => Thin::Server::DEFAULT_TIMEOUT,
43
+ :log => "/tmp/#{app_name}_thin.log",
44
+ :pid => "/tmp/#{app_name}.pid",
45
+ :max_conns => Thin::Server::DEFAULT_MAXIMUM_CONNECTIONS,
46
+ :max_persistent_conns => Thin::Server::DEFAULT_MAXIMUM_PERSISTENT_CONNECTIONS,
47
+ :require => [],
48
+ :wait => Thin::Controllers::Cluster::DEFAULT_WAIT_TIME,
49
+
50
+ :rackup => File.dirname(__FILE__) + '/../config.ru',
51
+ :static_dirs => ["#{File.dirname(__FILE__)}/../../../share/htdocs"],
52
+ :static_dirs_pre => ["./resources"], # directories to prepend to 'static_dirs'
53
+
54
+ :handlers => {} # procs to call at various times of the server's life cycle
55
+ }.merge(opts)
56
+ # Search path for resource files is concatination of 'pre' and 'standard' static dirs
57
+ @options[:static_dirs] = @options[:static_dirs_pre].concat(@options[:static_dirs])
58
+
59
+
60
+
61
+ print_options = false
62
+ p = parser
63
+
64
+ p.separator ""
65
+ p.separator "Testing options:"
66
+ p.on("--disable-https", "Run server without SSL") do sopts = nil end
67
+ p.on("--print-options", "Print option settings after parsing command lines args") do print_options = true end
68
+
69
+ # Allow application to add it's own parsing options
70
+ if ph = @options[:handlers][:pre_parse]
71
+ ph.call(p, @options)
72
+ end
73
+
74
+ parse!
75
+
76
+ if sopts
77
+ @options[:ssl] = true
78
+ @options[:ssl_key_file] ||= sopts[:key_file]
79
+ @options[:ssl_cert_file] ||= sopts[:cert_file]
80
+ @options[:ssl_verify] ||= sopts[:verify_peer]
81
+ end
82
+
83
+ # Change the name of the root logger so we can apply different logging
84
+ # policies depending on environment.
85
+ #
86
+ OMF::Base::Loggable.set_environment @options[:environment]
87
+
88
+ if print_options
89
+ require 'pp'
90
+ pp @options
91
+ end
92
+
93
+ @@instance = self
94
+ end
95
+
96
+ def life_cycle(step)
97
+ begin
98
+ if (p = @options[:handlers][step])
99
+ p.arity == 0 ? p.call() : p.call(@options)
100
+ end
101
+ rescue => ex
102
+ error ex
103
+ debug "#{ex.backtrace.join("\n")}"
104
+ end
105
+ end
106
+
107
+ def run!
108
+ life_cycle(:pre_run)
109
+ super
110
+ end
111
+ end
112
+ end
113
+
114
+
115
+
@@ -0,0 +1,6 @@
1
+
2
+ module OMF
3
+ module Base
4
+ VERSION = '1.0'
5
+ end
6
+ end
data/lib/omf_base.rb ADDED
File without changes
data/omf_base.gemspec ADDED
@@ -0,0 +1,24 @@
1
+ # -*- encoding: utf-8 -*-
2
+ $:.push File.expand_path("../lib", __FILE__)
3
+ require "omf_base/version"
4
+
5
+ Gem::Specification.new do |s|
6
+ s.name = "omf_base"
7
+ s.version = OMF::Base::VERSION
8
+ s.authors = ["NICTA"]
9
+ s.email = ["omf-user@lists.nicta.com.au"]
10
+ s.homepage = "https://www.mytestbed.net"
11
+ s.summary = %q{Some basic, but common functionality used in OMF libraries.}
12
+ s.description = %q{Some basic, but common functionality used in OMF libraries.}
13
+
14
+ s.rubyforge_project = "omf_base"
15
+
16
+ s.files = `git ls-files`.split("\n")
17
+ s.test_files = `git ls-files -- {test,spec,features}/*`.split("\n")
18
+ s.executables = `git ls-files -- bin/*`.split("\n").map{ |f| File.basename(f) }
19
+ s.require_paths = ["lib"]
20
+
21
+ # specify any dependencies here; for example:
22
+ # s.add_development_dependency "minitest", "~> 2.11.3"
23
+ s.add_runtime_dependency 'log4j'
24
+ end
metadata ADDED
@@ -0,0 +1,73 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: omf_base
3
+ version: !ruby/object:Gem::Version
4
+ version: '1.0'
5
+ prerelease:
6
+ platform: ruby
7
+ authors:
8
+ - NICTA
9
+ autorequire:
10
+ bindir: bin
11
+ cert_chain: []
12
+ date: 2013-08-29 00:00:00.000000000 Z
13
+ dependencies:
14
+ - !ruby/object:Gem::Dependency
15
+ name: log4j
16
+ requirement: !ruby/object:Gem::Requirement
17
+ none: false
18
+ requirements:
19
+ - - ! '>='
20
+ - !ruby/object:Gem::Version
21
+ version: '0'
22
+ type: :runtime
23
+ prerelease: false
24
+ version_requirements: !ruby/object:Gem::Requirement
25
+ none: false
26
+ requirements:
27
+ - - ! '>='
28
+ - !ruby/object:Gem::Version
29
+ version: '0'
30
+ description: Some basic, but common functionality used in OMF libraries.
31
+ email:
32
+ - omf-user@lists.nicta.com.au
33
+ executables: []
34
+ extensions: []
35
+ extra_rdoc_files: []
36
+ files:
37
+ - .gitignore
38
+ - Gemfile
39
+ - README.md
40
+ - Rakefile
41
+ - lib/omf_base.rb
42
+ - lib/omf_base/load_yaml.rb
43
+ - lib/omf_base/lobject.rb
44
+ - lib/omf_base/log4r_outputter.rb
45
+ - lib/omf_base/thin/logging.rb
46
+ - lib/omf_base/thin/runner.rb
47
+ - lib/omf_base/version.rb
48
+ - omf_base.gemspec
49
+ homepage: https://www.mytestbed.net
50
+ licenses: []
51
+ post_install_message:
52
+ rdoc_options: []
53
+ require_paths:
54
+ - lib
55
+ required_ruby_version: !ruby/object:Gem::Requirement
56
+ none: false
57
+ requirements:
58
+ - - ! '>='
59
+ - !ruby/object:Gem::Version
60
+ version: '0'
61
+ required_rubygems_version: !ruby/object:Gem::Requirement
62
+ none: false
63
+ requirements:
64
+ - - ! '>='
65
+ - !ruby/object:Gem::Version
66
+ version: '0'
67
+ requirements: []
68
+ rubyforge_project: omf_base
69
+ rubygems_version: 1.8.23
70
+ signing_key:
71
+ specification_version: 3
72
+ summary: Some basic, but common functionality used in OMF libraries.
73
+ test_files: []