module OML4R

This is the OML4R module, which should be required by ruby applications that want to collect measurements via OML

Copyright © 2009 - 2014 National ICT Australia Limited (NICTA). This software may be used and distributed solely under the terms of the MIT license (License). You should find a copy of the License in LICENSE.TXT or at opensource.org/licenses/MIT. By downloading or using this software you accept the terms and the liability disclaimer in the License.


Constants

DEF_PROTOCOL
DEF_SERVER_PORT
VERSION
VERSION_STRING

Public Class Methods

close() click to toggle source

Close the OML collection. This will block until all outstanding data have been sent out.

# File lib/oml4r.rb, line 518
def self.close()
  Channel.close_all
end
create_channel(name, url) click to toggle source
# File lib/oml4r.rb, line 511
def self.create_channel(name, url)
  Channel.create(name, url)
end
generate_guid() click to toggle source

Generate a random GUID

@return [BigNum] An integer GUID.

# File lib/oml4r.rb, line 525
def self.generate_guid()
  SecureRandom.random_number(2**64)
end
init(argv, opts = {}) { |op| ... } click to toggle source

The Init method of OML4R Ruby applications should call this method to initialise the OML4R module This method will parse the command line argument of the calling application to extract the OML specific parameters, it will also do the parsing for the remaining application-specific parameters. It will then connect to the OML server (if requested on the command line), and send the initial instruction to setup the database and the tables for each MPs.

param argv = the Array of command line arguments from the calling Ruby application param opts opts [String] :domain opts [String] :nodeID opts [String] :appName opts [Integer] :protocol opts [Proc] :afterParse param block = a block which defines the additional application-specific arguments

# File lib/oml4r.rb, line 333
def self.init(argv, opts = {}, &block)
  OML4R.logger.info "OML4R Client #{VERSION} [OMSPv#{opts[:protocol] || DEF_PROTOCOL}; Ruby #{RUBY_VERSION}] #{COPYRIGHT}"
  if d = (ENV['OML_EXP_ID'] || opts[:expID])
    # NOTE: It is still too early to complain about that. We need to be sure
    # of the nomenclature before making user-visible changes.
    OML4R.logger.warn "opts[:expID] and ENV['OML_EXP_ID'] are getting deprecated; please use opts[:domain] or ENV['OML_DOMAIN']  instead"
    opts[:domain] ||= d
  end
  opts[:domain] = ENV['OML_DOMAIN'] || opts[:domain]

  # TODO: Same as above; here, though, :id might actually be the way to go; or
  # perhaps instId?
  #if opts[:id]
  #  raise 'OML4R: :id is not a valid option. Do you mean :nodeID?'
  #end
  opts[:nodeID]  = ENV['OML_NAME'] || opts[:nodeID]  ||  opts[:id] || ENV['OML_ID']
  #
  # XXX: Same again; also, this is the responsibility of the developer, not the user
  #if opts[:app]
  #  raise 'OML4R: :app is not a valid option. Do you mean :appName?'
  #end
  opts[:appName] ||= opts[:app]
  @@appName = opts[:appName]
  opts[:protocol] ||= DEF_PROTOCOL

  if  ENV['OML_URL'] || opts[:omlURL] || opts[:url]
    raise MissingArgumentException.new 'neither OML_URL, :omlURL nor :url are valid. Do you mean OML_COLLECT or :omlCollect?'
  end
  if ENV['OML_SERVER'] || opts[:omlServer]
      OML4R.logger.warn "opts[:omlServer] and ENV['OML_SERVER'] are getting deprecated; please use opts[:collect] or ENV['OML_COLLECT'] instead"
  end
  opts[:omlCollectUri] = ENV['OML_COLLECT'] || ENV['OML_SERVER'] || opts[:collect] || opts[:omlServer]
  noop = opts[:noop] || false
  omlConfigFile = nil

  if argv
    OML4R.logger.debug "ARGV: #{argv.inspect}"
    # Create a new Parser for the command line
    op = OptionParser.new
    # Include the definition of application's specific arguments
    yield(op) if block
    # Include the definition of OML specific arguments
    op.on("--oml-id id", "Name to identify this app instance [#{opts[:nodeID] || 'undefined'}]") { |name| opts[:nodeID] = name }
    op.on("--oml-domain domain", "Name of experimental domain [#{opts[:domain] || 'undefined'}] *EXPERIMENTAL*") { |name| opts[:domain] = name }
    op.on("--oml-collect uri", "URI of server to send measurements to") { |u|  opts[:omlCollectUri] = u }
    op.on("--oml-protocol p", "Protocol number [#{OML4R::DEF_PROTOCOL}]") { |l| opts[:protocol] = l.to_i }
    op.on("--oml-log-level l", "Log level used (info: 0 .. debug: 1)") { |l| OML4R.logger.level = 1 - l.to_i }
    op.on("--oml-noop", "Do not collect measurements") { OML4R.logger.info "OML reporting disabled from command line"
                                                         return  }
    op.on("--oml-config file", "File holding OML configuration parameters") { |f| omlConfigFile = f }
    op.on("--oml-exp-id domain", "Obsolescent equivalent to --oml-domain domain") { |name|
      opts[:domain] = name
      OML4R.logger.warn "Option --oml-exp-id is getting deprecated; please use '--oml-domain #{domain}' instead"
    }
    op.on("--oml-file localPath", "Obsolescent equivalent to --oml-collect file:localPath") { |name|
      opts[:omlCollectUri] = "file:#{name}"
      OML4R.logger.warn "Option --oml-file is getting deprecated; please use '--oml-collect #{opts[:omlCollectUri]}' instead"
    }
    op.on("--oml-server uri", "Obsolescent equivalent to --oml-collect uri") {|u|
      opts[:omlCollectUri] = "#{u}"
      OML4R.logger.warn "Option --oml-server is getting deprecated; please use '--oml-collect #{opts[:omlCollectUri]}' instead"
    }
    op.on_tail("--oml-help", "Show this message") { $stderr.puts op }
    # XXX: This should be set by the application writer, not the command line
    #op.on("--oml-appid APPID", "Application ID for OML [#{appName || 'undefined'}] *EXPERIMENTAL*") { |name| appID = name }
    unless opts[:appName]
      raise MissingArgumentException.new 'OML4R: Missing :appName in application code!'
    end

    # Now parse the command line
    rest = op.parse(argv)
    if opts[:afterParse]
      # give the app a chance to fix missing parameters
      opts[:afterParse].call(opts)
    end
    
    # Parameters in OML config file takes precedence
    unless omlConfigFile.nil? 
      f = File.open(omlConfigFile, 'r')
      f.each_line do |l|
        d = l[/.*experiment=["']([^"']*)/,1]
        opts[:domain] = d if d
        d = l[/.*domain=["']([^"']*)/,1]
        opts[:domain] = d if d
        i = l[/.*id=["']([^"']*)/,1]
        opts[:nodeID] = i if i
        u = l[/.*url=["']([^"']*)/,1]
        opts[:omlCollectUri] = u if u
      end
      f.close
    end
  end
 
  unless opts[:nodeID]
    begin
      # Create a default nodeID by concatenating the local hostname with the process ID
      hostname = nil
      begin
        #hostname = Socket.gethostbyname(Socket.gethostname)[0]
        hostname = Socket.gethostname
      rescue Exception
        begin
          hostname = (`hostname`).chop
        rescue Exception; end
      end
      if hostname
        opts[:nodeID] = "#{hostname}-#{Process.pid}"
      end
    end
    unless opts[:nodeID]
      raise MissingArgumentException.new 'OML4R: Missing values for parameter :nodeID (--oml-id, OML_ID)'
    end
  end
  unless opts[:domain]
    raise MissingArgumentException.new 'OML4R: Missing values for parameter :domain (--oml-domain, OML_DOMAIN)!'
  end

  # Set a default collection URI if nothing has been specified
  opts[:omlCollectUri] ||= "file:#{opts[:appName]}_#{opts[:nodeID]}_#{opts[:domain]}_#{Time.now.strftime("%Y-%m-%dt%H.%M.%S%z")}"
  opts[:omlCollectUri] = qualify_uri(opts[:omlCollectUri])
  OML4R.logger.info "Collection URI is #{opts[:omlCollectUri]}"

  create_channel(:default, opts[:omlCollectUri]) if opts[:omlCollectUri]

  # Handle the defined Measurement Points
  startTime = Time.now
  Channel.init_all(opts[:domain], opts[:nodeID], opts[:appName], startTime, opts[:protocol])
  rest || []
end
logger() click to toggle source
# File lib/oml4r.rb, line 787
def self.logger
  @@logger
end
logger=(logger) click to toggle source

Overwrite the default logger

@param logger Needs to respond to ‘debug’, ‘info’, …

# File lib/oml4r.rb, line 40
def self.logger=(logger)
  @@logger = logger
end
qualify_uri(uri) click to toggle source

Parse an underspecified URI into a fully-qualified one URIs are resolved as follows; the default is [tcp:]host.

hostname           -> tcp:hostname:3003
hostname:3004      -> tcp:hostname:3004
tcp:hostname       -> tcp:hostname:3003
tcp:hostname:3004  -> tcp:hostname:3004
file:/P/A/T/H      -> file:/P/A/T/H

@param uri [String] a potentially under-qualified collection URI

@return [String] afully-qualified collection URI equivalent to uri

@raise [OML4RException] in case of a parsing error

# File lib/oml4r.rb, line 477
def self.qualify_uri(uri)
  curi = uri.split(':')

  # Defaults
  scheme = 'tcp'
  port = DEF_SERVER_PORT

  if curi.length == 1
    host = curi[0]

  elsif curi.length == 2
    if curi[0] == 'tcp'
      scheme, host = curi

    elsif  curi[0] == 'file'
      scheme, host = curi
      port = nil

    else
      host, port = curi
    end

  elsif curi.length >= 3
    if curi.length > 3
      OML4R.logger.warn "Parsing URI '#{uri}' as a triplet, ignoring later components"
    end
    scheme, host, port = curi

  else
    raise OML4RException.new "OML4R: Unable to parse URI '#{url}"
  end
  "#{scheme}:#{host}#{":#{port}" if port}"
end
version_of(name) click to toggle source

NOTE: The version number is now derived automatically from Git tags. This file needs not be modified. To create a new release, use git tag -asm “DESC” v2.m.r (make sure the feature set corresponds to that of liboml2-2.m).

# File lib/oml4r/version.rb, line 13
def self.version_of(name)
  git_tag  = `git describe --tags 2> /dev/null`.chomp
  git_root = `git rev-parse --show-toplevel 2> /dev/null`.chomp
  gem_v = Gem.loaded_specs[name].version.to_s rescue '0.0.0'

  # Not in a development environment or git not present
  if git_root != File.absolute_path("#{File.dirname(__FILE__)}/../../") || git_tag.empty?
    gem_v
  else
    git_tag.gsub(/-/, '.').gsub(/^v/, '')
  end
end