class Object

Public Instance Methods

acl_line(acl) click to toggle source
# File lib/net_shell/builtin_commands/host.rb, line 82
def acl_line(acl)
  service = usherm.service_for_id(acl[:idService])
  return "Non-existent service #{acl[:idService]}" if service.nil?

  proto = service[:isUdp] ? "UDP" : "TCP"
  external_addr = [acl[:ip], acl[:port]].compact.join(":")
  "\t\t#{service[:name].style(:service)}, #{proto} #{service[:port]} (#{external_addr} external)"
end
acquire_object() click to toggle source
# File lib/net_shell/builtin_commands/jsoncache.rb, line 37
def acquire_object
  obj = JSON.parse(@input.read_all) rescue nil
  talk.locate_data(obj, params[:field], params[:type]) rescue nil
end
add_queries(*new_queries) click to toggle source
# File lib/net_shell/builtin_commands/show.rb, line 54
def add_queries(*new_queries)
  @subqueries ||= []
  @seen ||= {}
  new_queries.each do |q|
    next if q == "none" # given by methods
    @subqueries.push q unless @seen.has_key? q
    @seen[q] = true
  end
end
all_apps() click to toggle source

Tab completors

# File lib/net_shell/builtin_commands/deploy.rb, line 63
def all_apps
  all_of_key(:appId)
end
all_branches() click to toggle source
# File lib/net_shell/builtin_commands/deploy.rb, line 67
def all_branches
  all_of_key(:branches)
end
all_commits() click to toggle source
# File lib/net_shell/builtin_commands/deploy.rb, line 71
def all_commits
  all_of_key(:commitId)
end
all_jebs() click to toggle source
# File lib/net_shell/builtin_commands/deploy.rb, line 75
def all_jebs
  all_of_key(:buildId)
end
all_of_key(key) click to toggle source
# File lib/net_shell/builtin_commands/deploy.rb, line 79
def all_of_key(key)
  instances = {}

  deployment[:buildList][:builds].each do |build|
    if build[key].is_a? Array then
      build[key].each { |item| instances[item] = true }
    else
      instances[build[key]] = true
    end
  end

  instances.keys
end
author(build) click to toggle source
# File lib/net_shell/builtin_commands/deploy.rb, line 262
def author(build)
  build[:author].style(:author) rescue ""
end
branches(build) click to toggle source
# File lib/net_shell/builtin_commands/deploy.rb, line 258
def branches(build)
  build[:branches].join(",").style(:branch)
end
build(cls, path=[]) click to toggle source
# File lib/net_shell/builtin_commands/build.rb, line 241
def build(cls, path=[])
  if path.empty? then
    console_puts "Building #{talk.truncated_name cls}..."
  else
    console_puts "#{talk.truncated_name cls} #{path.last}\n\t#{cls[:description]}"
  end

  result = {}
  cls[:field].each { |field| result[field[:name]] = handle_field(field, path) }
  result
end
build_id(build) click to toggle source
# File lib/net_shell/builtin_commands/deploy.rb, line 254
def build_id(build)
  sprintf("%4d", build[:buildRecordId]).style(:identifier)
end
build_info(build) click to toggle source
# File lib/net_shell/builtin_commands/deploy.rb, line 266
def build_info(build)
  name = sprintf("%36s", build[:buildId]).style(:build_name)
  "#{name} [#{branches(build)}] -- #{author(build)}"
end
build_request(code, machine) click to toggle source
# File lib/net_shell/builtin_commands/kai_event.rb, line 83
def build_request(code, machine)
  {
    __class: "com.acres4.common.info.mercury.qatest.QATestEventRequest",
    tok:nil,
    eventList:[ qa_event_table_item(code, machine) ]
  }
end
build_set() click to toggle source
# File lib/net_shell/builtin_commands/deploy.rb, line 138
def build_set
  if params[:jeb] then
    builds_for_jeb(params[:jeb])
  elsif params[:commit] then
    builds_for_commit(params[:commit])
  elsif params[:branch] then
    builds_for_branch(params[:branch])
  elsif params[:app] then
    builds_for_app(params[:app])
  else
    deployment[:buildList][:builds]
  end
end
build_set_by_app(builds) click to toggle source
# File lib/net_shell/builtin_commands/deploy.rb, line 189
def build_set_by_app(builds)
  apps = {}
  builds.each do |build|
    apps[build[:appId]] ||= []
    apps[build[:appId]].push build
  end
  apps
end
builds() click to toggle source

Builds

# File lib/net_shell/builtin_commands/deploy.rb, line 133
def builds
  show_build_set(build_set)
  ""
end
builds_for_app(app) click to toggle source
# File lib/net_shell/builtin_commands/deploy.rb, line 152
def builds_for_app(app)
  deployment[:buildList][:builds].select { |build| talk.name_matches?(build[:appId], app) }
end
builds_for_branch(branch) click to toggle source
# File lib/net_shell/builtin_commands/deploy.rb, line 178
def builds_for_branch(branch)
  set = 
  if params[:app] then
    builds_for_app(params[:app])
  else
    deployment[:buildList][:builds]
  end
  
  set.select { |build| build[:branches].include? branch }
end
builds_for_commit(commit) click to toggle source
# File lib/net_shell/builtin_commands/deploy.rb, line 156
def builds_for_commit(commit)
  set = 
  if params[:app] then
    builds_for_app(params[:app])
  else
    deployment[:buildList][:builds]
  end

  set.select { |build| build[:commitId].start_with? commit }
end
builds_for_jeb(jeb) click to toggle source
# File lib/net_shell/builtin_commands/deploy.rb, line 167
def builds_for_jeb(jeb)
  set = 
  if params[:app] then
    builds_for_app(params[:app])
  else
    deployment[:buildList][:builds]
  end
  
  set.select { |build| build[:buildId] == jeb }
end
bypass(object, type) click to toggle source
# File lib/net_shell/builtin_commands/excerpt.rb, line 86
def bypass(object, type)
  case type
  when "com.acres4.common.info.NamedObjectWrapper"
    return bypass(object[:body], object[:className])
  when "com.acres4.common.info.JSONRPCRequest"
    return bypass(object[:params], talk.guess_class(object[:params]))
  when "com.acres4.common.info.JSONRPCResponse"
    return bypass(object[:result], talk.guess_class(object[:result]))
  else
    return [object, type]
  end
end
categories() click to toggle source
# File lib/net_shell/builtin_commands/help.rb, line 26
def categories
  (@shell.built_ins.map { |name| @shell.built_in(name).category_text }).sort.uniq
end
checkout(id) click to toggle source
# File lib/net_shell/builtin_commands/talk.rb, line 60
def checkout(id)
  id = Jebediah.new.process(id)[:result] if params[:jeb]
  `cd #{repo} && git checkout origin/#{id}`
end
client_for_key(key, url) click to toggle source
# File lib/net_shell/builtin_commands/connect.rb, line 100
def client_for_key(key, url)
  case key
  when :mercury
    AcresClient.new(url, @shell.get_env(:kai_user), @shell.get_env(:kai_pass))
  when :central
    AcresClient.new(url, @shell.get_env(:usherm_user), @shell.get_env(:usherm_pass))
  when :config
    KaiConfigClient.new(url, @shell.get_env(:usherm_user), @shell.get_env(:usherm_pass))
  when :qa
    AcresClient.new(url, @shell.get_env(:kai_user), @shell.get_env(:kai_pass))
  else
    AcresClient.new(url, @shell.get_env(:usherm_user), @shell.get_env(:usherm_pass))
  end
end
client_interfaces() click to toggle source
# File lib/net_shell/builtin_commands/connect.rb, line 115
def client_interfaces
  {
    mercury:"/mercury/client?wrap",
    central:"/central/central?wrap",
    config:"/config/config?wrap",
    qa:"/mercury/qatest?wrap"
  }
end
clone_repo() click to toggle source
# File lib/net_shell/builtin_commands/talk.rb, line 71
def clone_repo
  puts "Cloning respository into #{repo}"
  `cd #{File.join(repo, "..")} && git clone git@github.com:acres4/talk`
end
collapse_ranges(elements) click to toggle source
# File lib/net_shell/builtin_commands/host.rb, line 40
def collapse_ranges(elements)
  return "None" if elements.nil? or elements.empty?
  elements = (elements.map { |element| element.to_i }).sort

  ranges = []
  start = elements.first
  last = nil

  elements.each do |element|
    if not(last.nil?) and element != last + 1
      ranges.push(string_for_range(start, last))
      start = element
    end
    last = element
  end

  ranges.push(string_for_range(start, last))
  ranges.join(", ")
end
concise_host(host) click to toggle source
# File lib/net_shell/builtin_commands/host.rb, line 116
def concise_host(host)
  datacenter = usherm.datacenter(host[:idDataCenter])
  dcnote = if datacenter.nil?
    "unknown (#{host[:idDataCenter]})"
  else
    "#{datacenter[:dataCenterName].style(:datacenter)}"
  end

  "#{host[:hostName].style(:host)} -- #{dcnote} #{usherm.env_type(host[:systemHostEnvironment])}"
end
connect_kai() click to toggle source
# File lib/net_shell/builtin_commands/connect.rb, line 55
def connect_kai
  dest = args[1]
  
  if dest.match(/^([a-zA-Z]+):\/\/[a-zA-Z0-9\-\.]+(:[0-9]+)?(\/)?/) then
    connect_to_url(dest)
  elsif dest.match(/^[0-9]+$/) then
    connect_to_site_id(dest.to_i)
  else
    connect_to_usher_host(dest)
  end
end
connect_raw() click to toggle source
# File lib/net_shell/builtin_commands/connect.rb, line 39
def connect_raw
  key = args[2].to_sym rescue :user
  clients = []
  client = AcresClient.new(args[1])
  return show_error("Unable to contact server at #{args[1]}") unless client.transport_connect
  
  @shell.set_client(key, client)
  client.on(:connect) { |trigger, msg| @shell.notify_connect(client) }
  client.on(:sent) { |trigger,msg| @shell.notify_outgoing_message(client, msg) }
  client.on(:message) { |trigger,msg| @shell.notify_incoming_message(client, msg) }  
  client.on(:disconnect) { |trigger,msg| @shell.notify_disconnect(client) }

  @shell.set_active_client(key)
  ""
end
connect_to_site_id(site_id) click to toggle source
# File lib/net_shell/builtin_commands/connect.rb, line 83
def connect_to_site_id(site_id)
  site = usherm.site_with_id(site_id)
  return show_error("Site ##{site_id}: No such site ID in usher") if site.nil?
  provider = usherm.provider_for_product(site_id, "Mercury")
  return show_error("Site ##{site_id}: Does not offer Mercury") if provider.nil?
  url = usherm.url_for_provider(provider)
  return show_error("Site ##{site_id}: Site appears to be down") if url.nil?
  puts "Connecting to Kai at #{url}"
  connect_to_url(url)
end
connect_to_url(base) click to toggle source
# File lib/net_shell/builtin_commands/connect.rb, line 73
def connect_to_url(base)
  client_interfaces.each do |key, uri|
    url = URI.join(base, uri).to_s
    @shell.set_client(key, client_for_key(key, url))
  end

  request_caches
  "Connected to #{@shell.client(:config).version.style(:host)} server"
end
connect_to_usher_host(host) click to toggle source
# File lib/net_shell/builtin_commands/connect.rb, line 94
def connect_to_usher_host(host)
  site = usherm.site_with_name(host)
  return show_error("Site #{host}: Does not appear to be listed in usher") if site.nil?
  connect_to_site_id(site[:idSite])
end
descriptions() click to toggle source
# File lib/net_shell/builtin_commands/show.rb, line 96
def descriptions
  { class:"Classes", glossary:"Glossaries", enumeration:"Enumerations", protocol:"Protocols" }
end
device_type() click to toggle source
# File lib/object_builder/definitions/connection_request.rb, line 13
def device_type
  "Ruby #{RUBY_VERSION}"
end
event_by_identifier(identifier) click to toggle source
# File lib/net_shell/builtin_commands/kai_event.rb, line 133
def event_by_identifier(identifier)
  identifier ||= args[1]
  identifier = identifier.to_i if identifier.is_a? String and identifier.match(/^[0-9]+$/)
  events.events.each do |event|
    return event if(event[:key].to_s == identifier.to_s or event[:code] == identifier)
  end

  pp identifier
  pp args[1]
  nil
end
event_code(identifier=nil) click to toggle source
# File lib/net_shell/builtin_commands/kai_event.rb, line 145
def event_code(identifier=nil)
  event_by_identifier(identifier)[:code]
end
event_description(event) click to toggle source
# File lib/net_shell/builtin_commands/kai_event.rb, line 63
def event_description(event)
  name = event_name(event[:eventList][0][:event][:idEventCode]) || event[:eventList][0][:event][:idEventCode]
  location = event[:eventList][0][:location]
  "#{name} @ #{location}"
end
event_name(identifier=nil) click to toggle source
# File lib/net_shell/builtin_commands/kai_event.rb, line 149
def event_name(identifier=nil)
  event_by_identifier(identifier)[:key]
end
event_table_item(code) click to toggle source
# File lib/net_shell/builtin_commands/kai_event.rb, line 98
def event_table_item(code)
  {
    idEventCode:code,
    hostEvent:host_event(code),
    collectStats:false,
    receiptTime:Time.now.to_i,
    playerRating:player_rating
  }
end
events() click to toggle source
# File lib/a4tools.rb, line 33
def events
  $events ||= A4Tools::EventManager.new
end
expiration(mod) click to toggle source
# File lib/net_shell/builtin_commands/site.rb, line 66
def expiration(mod)
  mod[:permanent] ? "Never" : timestamp(mod[:expiration])
end
fake_repo_info() click to toggle source
# File lib/object_builder/definitions/app_info_for_script.rb, line 56
def fake_repo_info
  {
    repository: "a4tools",
    sha1:"67021ff1f82c941454a6d2bffa7a2ffde0a6320a",
    jeb:"exquisitely eased cougar",
    timestamp:1399271669,
    author:"Jonas Acres",
    notes:"Progress commit",
    branches:["master"]
  }
end
fetch() click to toggle source
# File lib/net_shell/builtin_commands/talk.rb, line 56
def fetch
  `cd #{repo} && git fetch`
end
field_value(object, field_name) click to toggle source
# File lib/net_shell/builtin_commands/inject.rb, line 33
def field_value(object, field_name)
  m = field_name.to_s.match(/^([a-zA-Z0-9_]+)\[([0-9]+)\]$/)
  if m.nil? then
    return object[field_name.to_sym] rescue nil
  else
    name = m[1]
    value = object[name.to_sym][m[2].to_i] rescue nil
    return value
  end
end
find_class(target, data, type=nil) click to toggle source
# File lib/net_shell/builtin_commands/excerpt.rb, line 44
def find_class(target, data, type=nil)
  return find_class_in_array(target, data, type) if data.is_a? Array

  type ||= talk.guess_class(data)
  cls = talk.class_named(type) rescue nil
  
  if cls.nil? then
    data.each do |key, value|
      searchval = find_class(target, value)
      return searchval unless searchval.nil?
    end
  else
    cls[:field].each do |field|
      value = data[field[:name].to_sym]
      fieldtype = talk.expand_name(field[:type].first)
      next if value.nil? or fieldtype.nil?
      return value if talk.name_matches?(fieldtype, target)
    end
  end

  nil
end
find_class_in_array(target, data, type) click to toggle source
# File lib/net_shell/builtin_commands/excerpt.rb, line 67
def find_class_in_array(target, data, type)
  data.each do |datum|
    result = find_class(target, datum, type)
    return result unless result.nil?
  end

  return nil
end
find_request_with_id(id) click to toggle source
# File lib/net_shell/builtin_commands/recap.rb, line 157
def find_request_with_id(id)
  target_client.history.each do |msg|
    next if msg[:message].nil? or msg[:message][:id].nil? or not(msg[:message].has_key? :params)
    return msg[:message] if msg[:message][:id].to_i == id.to_i
  end

  nil
end
get_a4tools() click to toggle source
# File lib/object_builder/definitions/app_info_for_script.rb, line 68
def get_a4tools
  repo_info(File.dirname(__FILE__), "a4tools")
end
get_action(allowed) click to toggle source
# File lib/net_shell/builtin_commands/build.rb, line 37
def get_action(allowed)
  char = STDIN.gets.chomp rescue nil
  char = nil unless char.nil? or allowed.include? char
  char
end
get_commits() click to toggle source
# File lib/object_builder/definitions/app_info_for_script.rb, line 76
def get_commits
  #list = [ get_a4tools, get_talk ].compact
  list = [ fake_repo_info ] if list.nil? or list.empty?
end
get_talk() click to toggle source
# File lib/object_builder/definitions/app_info_for_script.rb, line 72
def get_talk
  repo_info(File.join(File.dirname(__FILE__), "../../../../talk"), "talk")
end
get_value(field, path) click to toggle source
# File lib/net_shell/builtin_commands/build.rb, line 83
def get_value(field, path)
  type = field[:type].first
  console_print prompt_for_value(path, type)

  value = STDIN.gets
  if value.nil? then
    value = "null" # nil => CTRL+D. Take advantage that all get_value_* interpret null as nil-value to make CTRL+D -> null shortcut.
    console_puts # need a newline since none was actually typed
  end

  value = value.chomp
  if(value == "?") then
    show_field_help(field)
    return get_value(field, path)
  end

  return get_value_integer(value) if([ "uint8", "uint16", "uint32", "uint64", "int8", "int16", "int32", "int64" ].include?(type))
  return get_value_real(value) if([ "real" ].include?(type))
  return get_value_boolean(value) if([ "bool" ].include?(type))
  return get_value_string(value) if([ "string" ].include?(type))
end
get_value_boolean(value) click to toggle source
# File lib/net_shell/builtin_commands/build.rb, line 61
def get_value_boolean(value)
  case value
  when "0", "false"
    false
  when "1", "true"
    true
  when "", "null"
    nil
  else
    true
  end
end
get_value_integer(value) click to toggle source
# File lib/net_shell/builtin_commands/build.rb, line 52
def get_value_integer(value)
  case value
  when nil, "null", ""
    nil
  else
    value.to_i
  end
end
get_value_real(value) click to toggle source
# File lib/net_shell/builtin_commands/build.rb, line 43
def get_value_real(value)
  case value
  when nil, "null", ""
    nil
  else
    value.to_f
  end
end
get_value_string(value) click to toggle source
# File lib/net_shell/builtin_commands/build.rb, line 74
def get_value_string(value)
  case value
  when nil, "null"
    nil
  else
    value
  end
end
get_version() click to toggle source
# File lib/object_builder/definitions/app_info_for_script.rb, line 81
def get_version
  VERSION
end
handle_array_element(field, path, depth) click to toggle source
# File lib/net_shell/builtin_commands/build.rb, line 157
def handle_array_element(field, path, depth)
  actions = [ "build", "null", "done", "?" ]
  case prompt_for_action(field, path, type_at_depth(field, depth), actions)
  when "?"
    show_field_help(field, depth)
    return handle_array_element(field, path, depth)
  when nil, "null"
    return { value:nil }
  when "done"
    return nil
  when "build"
    return { value:handle_field(field, path, depth+1, true) }
  end
end
handle_array_start(field, path, depth) click to toggle source
# File lib/net_shell/builtin_commands/build.rb, line 135
def handle_array_start(field, path, depth)
  actions = [ "build", "null", "?" ]

  case prompt_for_action(field, path, type_at_depth(field, depth), actions)
  when "?"
    show_field_help(field, depth)
    return handle_array_start(field, path, depth)
  when nil, "null"
    return nil
  when "build"
    collection = []
    building = true
    index = 0
    while true do
      element = handle_array_element(field, path[0..-2] + ["#{path.last}[#{index}]"], depth+1)
      return collection if element.nil?
      collection.push element[:value]
      index += 1
    end
  end
end
handle_complex(field, path, assume_build=false) click to toggle source
# File lib/net_shell/builtin_commands/build.rb, line 197
def handle_complex(field, path, assume_build=false)
  return build(talk.class_named(field[:type].first), path) if assume_build

  actions = if has_cache?(field) then
    [ "build", "populate", "null", "?" ]
  else
    [ "build", "null", "?" ]
  end

  case prompt_for_action(field, path, field[:type].first, actions)
  when "build"
    build(talk.class_named(field[:type].first), path)
  when nil, "null"
    nil
  when "populate"
    populate(field, path)
  when "?"
    show_field_help(field, field[:type].length-1)
    return handle_complex(field, path)
  end
end
handle_field(field, path, depth=0, assume_build=false) click to toggle source
# File lib/net_shell/builtin_commands/build.rb, line 223
def handle_field(field, path, depth=0, assume_build=false)
  path += [field[:name]] if depth == 0
  if depth+1 < field[:type].length then
    if in_array?(field, depth)
      return handle_array_start(field, path, depth)
    else
      # TODO: handle dictionary
      return nil
    end
  end

  if talk.primitive? field[:type].first
    return handle_primitive(field, path)
  else
    return handle_complex(field, path, assume_build)
  end
end
handle_primitive(field, path) click to toggle source
# File lib/net_shell/builtin_commands/build.rb, line 219
def handle_primitive(field, path)
  get_value(field, path)
end
has_cache?(field) click to toggle source
# File lib/net_shell/builtin_commands/build.rb, line 190
def has_cache?(field)
  ObjectBuilder.supported_classes(false).each do |name|
    return true if talk.name_matches?(name, field[:type].first)
  end
  false
end
host_event(code) click to toggle source
# File lib/net_shell/builtin_commands/kai_event.rb, line 108
def host_event(code)
  {
    priKey:0,
    hostDeviceId:nil,
    eventCode:code.to_s,
    idPatron:params[:patron] || 0,
    idEmployee:params[:employee] || 0,
    amount:params[:amount] || 0,
    meters:nil,
    eventTime:Time.now.to_i,
    hostTime:Time.now.to_i
  }
end
host_supports_ssh?(host) click to toggle source
# File lib/net_shell/builtin_commands/ssh.rb, line 46
def host_supports_ssh?(host)
  not usherm.acl_for_service(host, "ssh").nil?
end
hostname() click to toggle source
# File lib/object_builder/definitions/connection_request.rb, line 22
def hostname
  `hostname`.chomp
end
human_readable_size(size) click to toggle source
# File lib/net_shell/builtin_commands/recap.rb, line 141
def human_readable_size(size)
  titles = [ "B", "KiB", "MiB", "GiB", "TiB" ]
  titles.each_index do |idx|
    title = titles[idx]
    unit = 1024**idx
    boundary = 1024*unit
    return "#{size/unit} #{title}" if size < boundary or title == titles.last
  end
end
in_array?(field, depth) click to toggle source
# File lib/net_shell/builtin_commands/build.rb, line 105
def in_array?(field, depth)
  field[:type][-1 - depth] == "[]"
end
in_container?(field, depth) click to toggle source
# File lib/net_shell/builtin_commands/build.rb, line 113
def in_container?(field, depth)
  in_array?(field, depth) or in_hash?(field, depth)
end
in_hash?(field, depth) click to toggle source
# File lib/net_shell/builtin_commands/build.rb, line 109
def in_hash?(field, depth)
  field[:type][-1 - depth] == "{}"
end
json_output() click to toggle source
# File lib/net_shell/builtin_commands/recap.rb, line 100
def json_output
  set = params[:reverse] ? messages : messages.reverse
  set = (set.reverse[range_for_args(args)].map do |msg|
    if params[:raw] then
      msg[:message]
    else
      msg.reject { |k,v| k == :raw }
    end
  end)

  set = set[0] if set.length == 1 and not params[:array]
  set.to_json
end
list() click to toggle source

List

# File lib/net_shell/builtin_commands/deploy.rb, line 96
def list
  sites = if args.length >= 3 then
    args[2..-1].map { |arg| arg.to_i }
  else
    (usherm[:usherSystemId][:usherSites].map { |site| site[:idSite] }).sort
  end

  sites.each do |site_id|
    list_site(site_id, deployment.query(:buildPublicationList, site_id))
  end
  ""
end
list_all_commands() click to toggle source
# File lib/net_shell/builtin_commands/help.rb, line 16
def list_all_commands
  (categories.map { |cat| list_category(cat) }).join("\n\n")
end
list_branches() click to toggle source
# File lib/net_shell/builtin_commands/talk.rb, line 85
def list_branches
  return [] unless repo_exists?
  branches = `cd #{repo} && git branch -a --no-color`.split("\n").map { |x| x.gsub(/^\*? */,"").gsub(/^.*-> /,"").gsub(/^(remotes\/)?origin\//,"") }
  branches &= branches # remove dupes
  branches.sort
end
list_category(category) click to toggle source
# File lib/net_shell/builtin_commands/help.rb, line 30
def list_category(category)
  commands = @shell.built_ins.select { |name| @shell.built_in(name).category_text == category }
  cat = category.style(:category)
  cmds = (commands.sort.map do |name|
    cmd = @shell.built_in(name).new(@shell)
    usermark = cmd.user_defined? ? "@".style(:userdefined) : " "
    "#{sprintf("%25s", name.to_s).style(:command)}#{usermark} -- #{cmd.description}"
  end).join("\n")

  [cat, cmds].join("\n")
end
list_command(name) click to toggle source
# File lib/net_shell/builtin_commands/help.rb, line 20
def list_command(name)
  return show_error("#{name}: command not found") unless @shell.has_built_in?(name)
  cmd = @shell.built_in(name).new(@shell)
  cmd.educate
end
list_commits() click to toggle source
# File lib/net_shell/builtin_commands/talk.rb, line 76
def list_commits
  return [] unless repo_exists?
  jeb = Jebediah.new
  `cd #{repo} && git log --pretty=format:"%an:%h:%s"`.split("\n").map do |commit|
    components = commit.split(":")
    { author:components[0], hash:components[1], jeb:jeb.process(components[1])[:result].join(" "), notes:components[2] }
  end
end
list_fields(name) click to toggle source
# File lib/net_shell/builtin_commands/references.rb, line 46
def list_fields(name)
  fields = []
  talk.definition[:class].each do |cls|
    cls[:field].each do |field|
      fields.push({class:cls, field:field}) if talk.name_matches?(name, field[:type].first)
    end
  end

  fields
end
list_methods(name) click to toggle source
# File lib/net_shell/builtin_commands/references.rb, line 35
def list_methods(name)
  methods = []
  talk.definition[:protocol].each do |proto|
    proto[:method].each do |method|
      methods.push({protocol:proto, method:method}) if(talk.name_matches?(name, method[:request]) or talk.name_matches?(name, method[:response]))
    end
  end

  methods
end
list_site(site_id, publications) click to toggle source
# File lib/net_shell/builtin_commands/deploy.rb, line 109
def list_site(site_id, publications)
  site = usherm.site_with_id(site_id) || {name:"Unknown site", siteDescription:"Not in usher"}
  lines = []
  
  lines.push "Site #{site_id} -- #{site[:name]} (#{site[:siteDescription]})"
  publications[:orders].keys.sort.each do |app|
    next if params[:app] and not talk.name_matches?(app, params[:app])
    lines.push list_site_app(app.to_s, publications[:orders][app])
  end

  puts lines.join("\n")+"\n" unless lines.length == 1
end
list_site_app(app, orders) click to toggle source
# File lib/net_shell/builtin_commands/deploy.rb, line 122
def list_site_app(app, orders)
  pub = orders.first
  return if params[:jeb] and pub[:buildInfo][:buildId] != params[:jeb]
  return if params[:commit] and pub[:buildInfo][:commitId] != params[:commit]
  return if params[:branch] and not(pub[:buildInfo][:branches].include? params[:branch])
  "\t#{timestamp(pub[:publicationTime])} #{app.style(:class)} -- #{build_info(pub[:buildInfo])}"
end
machine_list() click to toggle source
# File lib/net_shell/builtin_commands/kai_event.rb, line 69
def machine_list
  @shell.client(:config).machines rescue []
end
make_talk() click to toggle source
# File lib/net_shell/builtin_commands/talk.rb, line 65
def make_talk
  version = params[:talkversion] ? " _#{params[:talkversion]}_" : ""
  `cd #{repo} && maketalk#{version} --upgrade --json info > #{talk_json_path}`
  refresh_talk
end
messages() click to toggle source
# File lib/net_shell/builtin_commands/recap.rb, line 52
def messages
  messages = target_client.history
end
method(message) click to toggle source
# File lib/net_shell/builtin_commands/recap.rb, line 151
def method(message)
  return message[:method] if message.has_key? :method
  request = find_request_with_id(message[:id])
  request[:method] rescue "unknown"
end
origin_line(method) click to toggle source
# File lib/net_shell/builtin_commands/show.rb, line 132
def origin_line(method)
  return "Asynchronous from server\n\t\t".style(:origin) if method[:origin] == "server"
  return ""
end
os_name() click to toggle source
# File lib/object_builder/definitions/connection_request.rb, line 26
def os_name
  `uname`.chomp
end
os_version() click to toggle source
# File lib/object_builder/definitions/device_info_for_system.rb, line 35
def os_version
  RUBY_VERSION
end
parse_params(args) click to toggle source
# File lib/net_shell/builtin_commands/ssh.rb, line 50
def parse_params(args)
  if args.length == 3
    return { host:args[1], user:args[2] }
  else
    if args[1].include? "@" then
      comps = args[1].split("@")
      return { host:comps[1], user:comps[0] }
    else
      return { host:args[1], user:"acres4" }
    end
  end
end
persist() click to toggle source
# File lib/net_shell/builtin_commands/jsoncache.rb, line 53
def persist
  builder = ObjectBuilder[args[1]]
  return show_error("#{args[1]}: no such identifier") if  builder.nil?
  File.write(File.join(@shell.shelldir(:json), args[1]), builder.value.to_json)
  ""
end
pick_toplevel(message) click to toggle source
# File lib/net_shell/builtin_commands/recap.rb, line 166
def pick_toplevel(message)
  message = symbolify(JSON.parse(message)) if message.is_a? String
  if message[:jsonrpc] == "2.0" then
    return bypass(message, "com.acres4.common.info.JSONRPCRequest") if message.has_key? :params
    return [message, "Error"] unless message[:error].nil?
    return bypass(message, "com.acres4.common.info.JSONRPCResponse") if message.has_key? :result
  end

  [message, talk.guess_class(message)]
end
player_rating() click to toggle source
# File lib/net_shell/builtin_commands/kai_event.rb, line 122
def player_rating
  return nil unless params[:patron] or params[:firstName] or params[:lastName] or params[:loyaltyTierStr]

  {
    idPatron:params[:patron] || 0,
    firstName:params[:first_name] || "Little",
    lastName:params[:last_name] || "Timmy",
    loyaltyTierStr:params[:tier] || "Wood"
  }
end
populate(field, path) click to toggle source
# File lib/net_shell/builtin_commands/build.rb, line 172
def populate(field, path)
  while true do
    idx = 0
    builders = ObjectBuilder.builders_for_name(field[:type].first)
    builders.each do |builder|
      console_puts("#{idx.to_s.style(:constant_value)} #{builder.identifier.to_s.style(:method_name)}: #{builder.description}")
      idx += 1
    end

    console_print prompt_for_path(path)
    action = STDIN.gets.chomp rescue nil

    return handle_complex(field, path) if action.nil? # CTRL+D cancels populate
    index = action.match(/^[0-9]+$/) ? action.to_i : nil
    return builders[index].value if not index.nil? and index < builders.length
  end
end
prompt(basis={}) click to toggle source
# File lib/net_shell/builtin_commands/usher_site.rb, line 244
def prompt(basis={})
end
prompt_add() click to toggle source
# File lib/net_shell/builtin_commands/usher_site.rb, line 233
def prompt_add
end
prompt_delete() click to toggle source
# File lib/net_shell/builtin_commands/usher_site.rb, line 239
def prompt_delete
end
prompt_edit() click to toggle source
# File lib/net_shell/builtin_commands/usher_site.rb, line 236
def prompt_edit
end
prompt_for_action(field, path, type, actions) click to toggle source
# File lib/net_shell/builtin_commands/build.rb, line 117
def prompt_for_action(field, path, type, actions)
  while true do
    console_puts "#{path.join('.').style(:class)}: #{type.style(:field_datatype)}. #{actions.map { |a| "[#{a[0].bold}]#{a[1..-1]}" }.join(', ')}"
    console_print prompt_for_path(path)
    action = get_action(actions.map { |a| a[0] })
    return (actions.select { |a| a[0] == action }).first unless action.nil?
  end
end
prompt_for_apps(set) click to toggle source

Publish

# File lib/net_shell/builtin_commands/deploy.rb, line 201
def prompt_for_apps(set)
  apps = build_set_by_app(set)
  return apps.keys.sort.map { |app| apps[app].last } if params[:yes]

  selected = []
  apps.keys.sort.each do |app|
    build = apps[app].last
    cls = sprintf("%s", app).style(:class)
    name = sprintf("%s", build[:buildId]).style(:build_name)
    branch = build[:branches].join(",").style(:branch)
    line = sprintf("%99s", "#{cls}: #{name} [#{branch}]")

    while true do
      print "#{line} [y/N]> "
      input = STDIN.gets.chomp.upcase rescue nil
      input = "N" if not input.nil? and input.empty?

      selected.push build if input == "Y"
      puts if input.nil?
      break if ["Y", "N"].include? input
    end
  end

  selected
end
prompt_for_path(path) click to toggle source
# File lib/net_shell/builtin_commands/build.rb, line 29
def prompt_for_path(path)
  path.join(".").style(:class) + ") "
end
prompt_for_value(path, type) click to toggle source
# File lib/net_shell/builtin_commands/build.rb, line 33
def prompt_for_value(path, type)
  "#{path.join(".").style(:class)} #{type.style(:field_datatype)}) "
end
provider_line(id_provider) click to toggle source
# File lib/net_shell/builtin_commands/host.rb, line 60
def provider_line(id_provider)
  provider = usherm.provider(id_provider)
  return "Non-existent provider #{id_provider}" if provider.nil?
  return nil if provider[:isSpecial]

  sites = collapse_ranges(provider[:idSites])

  ipLines = ["Internal", "External"].map do |zone|
    hosts = provider["usherHosts#{zone}".to_sym] || []
    zone + ": " + if hosts.empty? then
      "None"
    else
      urls = hosts.map { |host| host[:url] }
      urls.join(", ")
    end
  end

  out = "\t\t#{provider[:product].style(:product)}: Site #{sites}\n"
  out += (ipLines.map { |line| "\t\t\t#{line}"}).join("\n") + "\n"
  out
end
publish() click to toggle source
# File lib/net_shell/builtin_commands/deploy.rb, line 227
def publish
  sites = args[2..-1].map { |arg| arg.to_i }
  selected = prompt_for_apps(build_set)
  selected.each do |build|
    puts "Publishing #{build[:appId].style(:class)} \"#{build[:buildId].style(:build_name)}\" to site #{sites.join(",")}..."
    deployment.publish_build(build, sites)
  end
  "Done."
end
qa_event_table_item(code, machine) click to toggle source
# File lib/net_shell/builtin_commands/kai_event.rb, line 91
def qa_event_table_item(code, machine)
  {
    event:event_table_item(code),
    location:machine
  }
end
query_for_params() click to toggle source
# File lib/net_shell/builtin_commands/show.rb, line 74
def query_for_params
  query = []
  options = [ :class, :enumeration, :glossary, :protocol ]
  options.each { |opt| query.push(opt) if params[opt] }

  query = options if query.empty?
  query
end
random_machine() click to toggle source
# File lib/net_shell/builtin_commands/kai_event.rb, line 73
def random_machine
  machine_list.sample
end
range_for_args(args) click to toggle source
# File lib/net_shell/builtin_commands/recap.rb, line 56
def range_for_args(args)
  case args.length
  when 0,1
    range = (0 .. -1)
  when 2
    range = args[1].to_i .. args[1].to_i
  when 3
    low = [args[1], args[2]].min
    high = [args[1], args[2]].max
    range = low.to_i .. high.to_i
  end
end
read() click to toggle source
# File lib/net_shell/builtin_commands/jsoncache.rb, line 60
def read
  if args.length == 1 then
    builders = ObjectBuilder.builders
    return show_error("no builders defined") if builders.empty?
    return show_builder_list(builders)
  end

  builder = ObjectBuilder[args[1]]
  return builder.value.to_json unless builder.nil?

  builders = ObjectBuilder.builders_for_name(args[1])
  return "#{args[0]}: #{args[1]}: no such identifier or class in cache" if builders.empty?
  show_builder_list(builders)
end
refresh_talk() click to toggle source
# File lib/a4tools.rb, line 24
def refresh_talk
  $talk = A4Tools::TalkConsumer.new(talk_file)
end
render_client(key) click to toggle source
# File lib/net_shell/builtin_commands/select.rb, line 18
def render_client(key)
  target = @shell.client(key)
  fmt_key = sprintf("%20s", key.to_s)
  host = usherm.host_for_url(target.uri) || "unknown host"
  info = source_id(target)

  "#{fmt_key.style(:target)}: #{info} #{target.uri.to_s.style(:url)} (#{host.style(:host)})"
end
render_result(response) click to toggle source
# File lib/net_shell/builtin_commands/usher.rb, line 28
def render_result(response)
  return ("Unable to contact usher") if response.nil?
  return "Usher returned status #{response.code}" if response.code.to_i < 200 or response.code.to_i >= 300
  begin
    payload = JSON.parse(response.body)
    return ("Usher returned non-JSON RPC response") unless payload["jsonrpc"] == "2.0"
    return ("Usher returned error: \"#{payload["error"]}\"") unless payload["error"].nil?
    return ("Usher did not include result") if payload["result"].nil?
    return ("Usher server returned non-usher response") unless payload["result"]["className"] == "com.acres4.common.info.usher.UsherResponse"
    return ("Usher response did not include body") if payload["result"]["body"].nil?
    return render_success(payload["result"]["body"])
  rescue JSON::ParserError
    return ("Usher returned non-JSON response")
  end
end
render_success(result) click to toggle source
# File lib/net_shell/builtin_commands/usher.rb, line 44
def render_success(result)
  s  = "       Site ID: #{result["siteID"]}\n"
  s += "     Site name: #{result["siteName"]}\n"
  s += "Remote address: #{result["remoteAddr"]}\n\n"

  result["hosts"].each do |host|
    s += "Product: #{host["product"]} (#{host["host"]}:#{host["port"]})\n\t#{host["url"]}, #{host["ctx"]}, System #{host["systemId"]}\n\n"
  end

  s
end
render_summary(message) click to toggle source
# File lib/net_shell/builtin_commands/recap.rb, line 126
def render_summary(message)
  toplevel, cls = pick_toplevel(message)
  puts toplevel if cls.nil?
  cls ||= talk.guess_class(toplevel)
  class_name = cls.style(:class) || "Unknown"
  id_str = message[:id] ? sprintf("%3d", message[:id]) : "   "

  sprintf("%s %20s %s %s",
    id_str.style(:id),
    method(message).style(:method_name),
    class_name.style(:class),
    human_readable_size(message.to_json.length)
    )
end
render_text(message) click to toggle source
# File lib/net_shell/builtin_commands/recap.rb, line 118
def render_text(message)
  if params[:summary] then
    render_summary(message)
  else
    message.is_a?(Hash) ? JSON.generate(message) : message
  end
end
repo() click to toggle source
# File lib/net_shell/builtin_commands/talk.rb, line 44
def repo
  params[:repo] || @shell.shelldir("talk")
end
repo_exists?() click to toggle source
# File lib/net_shell/builtin_commands/talk.rb, line 52
def repo_exists?
  File.exist?(File.join(repo, ".git"))
end
repo_info(directory, repository=nil) click to toggle source
# File lib/object_builder/definitions/app_info_for_script.rb, line 37
def repo_info(directory, repository=nil)
  begin
    info = {}
    info[:repository] = repository || File.basename(directory)
    info[:sha1] = `cd "#{directory}"; git log --format="%H" -n1`.chomp
    info[:jeb] = Jebediah.new.process(info[:sha1])[:result].join(" ")
    info[:timestamp] = `cd "#{directory}"; git log --format="%at" -n1`.chomp.to_i
    info[:author] = `cd "#{directory}"; git log --format="%an" -n1`.chomp
    info[:notes] = `cd "#{directory}"; git log --format="%s" -n1`.chomp

    info[:branches] = (`cd "#{directory}"; git branch --contains #{info[:sha1]}`.split("\n").map do |line|
      line.length > 0 ? line.gsub(/^[\s*]*/, "").gsub(/\s*$/, "") : nil
    end).compact
    return info
  rescue
    return nil
  end
end
request_caches() click to toggle source
# File lib/net_shell/builtin_commands/connect.rb, line 67
def request_caches
  version = @shell.client(:config).site_version
  client_interfaces.keys.each { |key| @shell.client(key).version = version }
  @shell.client(:config).machines
end
send(message) click to toggle source
# File lib/net_shell/builtin_commands/send.rb, line 68
def send(message)
  if params[:dry] then
    puts message
  else
    client.send_message(message)
  end
end
send_event(message) click to toggle source
# File lib/net_shell/builtin_commands/kai_event.rb, line 77
def send_event(message)  
  qa.inject_token(message)
  jsonrpc = qa.jsonrpc_message(:qaTestEvent, "qatest", nil, message)
  qa.send_message(jsonrpc).body
end
send_raw(message) click to toggle source
# File lib/net_shell/builtin_commands/send.rb, line 50
def send_raw(message)
  send(message)
end
send_wrapped(message) click to toggle source
# File lib/net_shell/builtin_commands/send.rb, line 54
def send_wrapped(message)
  message = symbolify(JSON.parse(message)) if message.is_a? String
  method, protocol = talk.method_named(args[2])
  return show_error("#{args[1]}: unknown method") if method.nil?
  cls = talk.class_named(method[:request])
  return show_error("#{args[1]}: unable to locate request class") if cls.nil?

  client.inject_token(message) unless params[:no_inject]
  jsonrpc = client.jsonrpc_message(method[:name], args[1], talk.guess_class(message), message)

  message = JSON.generate(jsonrpc)
  send(message)
end
sender(msg) click to toggle source
# File lib/net_shell/builtin_commands/recap.rb, line 69
def sender(msg)
  case msg[:sender]
  when :client
    "client".light_blue
  when :server
    "server".magenta
  end
end
serial_number() click to toggle source
# File lib/object_builder/definitions/connection_request.rb, line 17
def serial_number
  return $config[:serial] unless $config.nil? or $config[:serial].nil?
  "1234"
end
show(query) click to toggle source
# File lib/net_shell/builtin_commands/show.rb, line 180
def show(query)
  show_field(query) || show_method(query) || show_class(query) || show_protocol(query) || show_constant(query) || show_glossary(query) || show_enumeration(query)
end
show_all_sites() click to toggle source
# File lib/net_shell/builtin_commands/site.rb, line 42
def show_all_sites
  sites = (usherm[:usherSystemId][:usherSites].map { |site| site[:idSite] }).sort
  sites.each do |site_id|
    site = usherm.site_with_id(site_id)
    site_id_str = sprintf("%6d", site_id).style(:id)
    puts "##{site_id_str}: #{site[:name]} (#{site[:siteDescription]})"
  end
end
show_app(app, limit=50) click to toggle source

Other stuff

# File lib/net_shell/builtin_commands/deploy.rb, line 239
def show_app(app, limit=50)
  list = deployment.index_list_by_app[app]
  return show_error("#{app}: No such app in deployment server") if list.nil?

  list.each do |build|
    puts show_build(build)
  end

  ""
end
show_build_set(set) click to toggle source
# File lib/net_shell/builtin_commands/deploy.rb, line 277
def show_build_set(set)
  apps = build_set_by_app(set)
  apps.keys.sort.each { |app| show_app(app, apps[app]) }
end
show_builder_list(builders) click to toggle source
# File lib/net_shell/builtin_commands/jsoncache.rb, line 75
def show_builder_list(builders)
  (builders.map do |builder|
    "#{builder.name.to_s.style(:class)} #{builder.identifier.to_s.green}: #{builder.description}"
  end).join("\n")
end
show_class(query) click to toggle source
# File lib/net_shell/builtin_commands/show.rb, line 120
def show_class(query)
  cls = (query[0].is_a? Hash) ? query[0] : talk.class_named(query[0])
  return nil if cls.nil?

  fields = cls[:field].map do |f|
    add_queries(f[:type].first)
    "\t#{f[:name].style(:field_name)}, #{(f[:type].map { |t| talk.truncated_name t }).join('').style(:field_datatype)}\n\t\t#{f[:description]}\n"
  end

  "Class #{cls[:name].style(:class)}\n\t#{cls[:description]}\n\n" + fields.join("\n")
end
show_constant(query) click to toggle source
# File lib/net_shell/builtin_commands/show.rb, line 157
def show_constant(query)
  constant, container = (query.length > 1) ? talk.constant_named(query[1], query[0]) : talk.constant_named(query[0], nil)
  return nil if constant.nil?

  origin = (container.has_key? :term) ? "Glossary #{container[:name]}" : "Enumeration #{container[:name]}"

  "Constant #{constant[:name].style(:constant_name)}: #{constant[:value].to_s.style(:constant_value)}\n\t#{origin}\n\t#{constant[:description]}\n\n"
end
show_enumeration(query) click to toggle source
# File lib/net_shell/builtin_commands/show.rb, line 173
def show_enumeration(query)
  enumeration = (query[0].is_a? Hash) ? query[0] : talk.enumeration_named(query[0])
  return nil if enumeration.nil?

  "Enumeration #{enumeration[:name].style(:collection_name)}\n\t#{enumeration[:description]}\n\n" + (enumeration[:constant].map { |c| "\t#{c[:value].to_i.to_s.style(:constant_value)} #{c[:name].style(:constant_name)}\n\t\t#{c[:description]}\n"}).join("\n")
end
show_field(cls, field) click to toggle source
# File lib/net_shell/builtin_commands/references.rb, line 61
def show_field(cls, field)
  puts "\t#{cls[:name].style(:class)}: #{field[:name].style(:field_name)}#{field[:type][1..-1].join("")}"
end
show_field_help(field, depth=-1) click to toggle source
# File lib/net_shell/builtin_commands/build.rb, line 130
def show_field_help(field, depth=-1)
  depth = field[:type].length - 1 if depth < 0
  console_puts "#{talk.truncated_name(type_at_depth(field, depth)).style(:field_datatype)} #{field[:name].style(:field_name)}\n\t#{field[:description]}"
end
show_glossary(query) click to toggle source
# File lib/net_shell/builtin_commands/show.rb, line 166
def show_glossary(query)
  glossary = (query[0].is_a? Hash) ? query[0] : talk.glossary_named(query[0])
  return nil if glossary.nil?

  "Glossary #{glossary[:name].style(:collection_name)}\n\t#{glossary[:description]}\n\n" + (glossary[:term].map { |t| "\t#{t[:name].style(:constant_name)} (\"#{t[:value].style(:constant_value)}\")\n\t\t#{t[:description]}\n"}).join("\n")
end
show_host_info(site_id) click to toggle source
# File lib/net_shell/builtin_commands/site.rb, line 93
def show_host_info(site_id)
  puts "\tHosts".style(:heading)
  usherm.providers_for_site(site_id).each do |provider|
    host = usherm.host_with_id(provider[:idSystemHost])
    product = sprintf("%20s", provider[:product]).style(:product)
    puts "\t\t#{product}: #{host[:hostName].style(:host)}"
  end
end
show_list() click to toggle source
# File lib/net_shell/builtin_commands/show.rb, line 64
def show_list
  s = ""
  query_for_params.each do |section|
    next if talk.definition[section].nil?
    s += descriptions[section] + " (#{talk.definition[section].length})\n"
    s += (talk.definition[section].map { |item| "\t#{item[:name].style(style_for_section(section))}\n\t#{item[:description]}\n" }).join("\n") + "\n\n"
  end
  s
end
show_method(protocol, method) click to toggle source
# File lib/net_shell/builtin_commands/references.rb, line 57
def show_method(protocol, method)
  puts "\t#{protocol[:name].style(:protcol_name)}: #{method[:name].style(:method_name)} #{method[:request].style(:class)} -> #{method[:response].style(:class)}"
end
show_protocol(query) click to toggle source
# File lib/net_shell/builtin_commands/show.rb, line 137
def show_protocol(query)
  proto = (query[0].is_a? Hash) ? query[0] : talk.protocol_named(query[0])
  return nil if proto.nil?

  methods = proto[:method].map do |m|
    add_queries(m[:request], m[:response])
    "\t#{m[:name].style(:method_name)}: #{m[:request].style(:class)} -> #{m[:response].style(:class)}\n\t\t#{origin_line(m)}#{m[:description]}\n"
  end

  "Protocol #{proto[:name].style(:protocol_name)}\n\t#{proto[:description]}\n" + methods.join("\n")
end
show_publications(publications) click to toggle source
# File lib/net_shell/builtin_commands/site.rb, line 102
def show_publications(publications)
  puts "\tDeployments".style(:heading)
  publications[:orders].keys.sort.each do |app|
    next if params[:app] and not talk.name_matches?(app, params[:app])
    list_site_app(app.to_s, publications[:orders][app])
  end
end
show_site(site_id) click to toggle source
# File lib/net_shell/builtin_commands/site.rb, line 51
def show_site(site_id)
  site = usherm.site_with_id(site_id)
  show_usher_site(site_id, site)
  show_host_info(site_id)
  show_publications(deployment.query(:buildPublicationList,site_id)) unless params[:no_deploy]
end
show_usher_site(site_id, site) click to toggle source
# File lib/net_shell/builtin_commands/site.rb, line 70
def show_usher_site(site_id, site)
  if site.nil?
    puts "Site #{site_id.to_s.style(:id)}: Unknown (not in usher)"
    return
  end

  puts "Site".style(:heading) +" #{site[:idSite].to_s.style(:id)}: #{site[:name]} (#{site[:siteDescription]})"
  puts "\t         Timezone: #{site[:zoneinfoId].style(:timezone)}"
  mod = site[:moduleProvision]
  if mod then
    mask = sprintf("%16x", mod[:modules]).style(:mask)
    puts "\t          Modules: #{mask}"
    puts "\t     Max machines: #{mod[:maxAllowedMachines]}"
    puts "\t           Active: #{yes_no(mod[:active])}"
    puts "\tPermanent license: #{yes_no(mod[:permanent])}"
    puts "\t       Expiration: #{expiration(mod)}"
    puts "\t Renewal attempts: #{mod[:renewalAttemtps]}"
  end
  site[:siteRange].each do |range|
    puts "\t             CIDR: #{range[:cidrBlock].style(:cidr)} #{range[:siteRangeDescription]}"
  end
end
site_id_for_arg(arg) click to toggle source
# File lib/net_shell/builtin_commands/site.rb, line 36
def site_id_for_arg(arg)
  return arg.to_i if arg.is_a? Fixnum or arg.match(/^[0-9]+$/)
  usherm[:usherSystemId][:usherSites].each { |site| return site[:idSite] if site[:name] == arg  }
  nil
end
source_id(target) click to toggle source
# File lib/net_shell/builtin_commands/select.rb, line 27
def source_id(target)
  app_info = target.server_info || {}
  version = target.version || app_info[:currentTalkVersion]
  protocol = sprintf("%-6s", (version || "")).style(:protocol_name)
  name = sprintf("%20s", ((app_info[:appName] rescue nil) || "")).style(:name)
  commit = sprintf("%7s", ((app_info[:sourceRevision][0..6] rescue nil) || "")).style(:commit)
  branch = sprintf("%-30s", ((app_info[:supportingRevisions].first[:branches].first rescue nil) || "")).style(:branch)

  "#{protocol} #{commit} #{branch}"
end
store() click to toggle source
# File lib/net_shell/builtin_commands/jsoncache.rb, line 42
def store
  description = args[1] rescue "Defined from console"
  obj, type = acquire_object
  return show_error("Unable to acquire field from JSON") if obj.nil?

  obj[:__class] = type unless type.nil?

  ObjectBuilder.load_object(obj, params[:store], description)
  ""
end
string_for_range(start, last, params={}) click to toggle source
# File lib/net_shell/builtin_commands/host.rb, line 32
def string_for_range(start, last, params={})
  if start == last then
    last
  else
    "#{start}-#{last}"
  end
end
style_for_section(section) click to toggle source
# File lib/net_shell/builtin_commands/show.rb, line 83
def style_for_section(section)
  case section
  when :class
    :class
  when :protocol
    :protocol_name
  when :enumeration, :glossary
    :collection_name
  else
    :none
  end
end
symbolify(item) click to toggle source
# File lib/a4tools.rb, line 8
def symbolify(item)
  if item.is_a? Array
    return item.map! { |value| symbolify value }
  elsif not item.is_a? Hash
    return item
  end

  new_hash = {}
  item.each { |key, value| new_hash[key.to_sym] = symbolify value }
  new_hash
end
talk() click to toggle source
# File lib/a4tools.rb, line 20
def talk
  $talk ||= A4Tools::TalkConsumer.new(talk_file)
end
talk_file() click to toggle source
# File lib/a4tools.rb, line 28
def talk_file
  return $localtalk if not $localtalk.nil? and File.exists?($localtalk)
  A4Tools::TalkConsumer.new(File.join(File.dirname(__FILE__), "talk.json"))
end
talk_json_path() click to toggle source
# File lib/net_shell/builtin_commands/talk.rb, line 48
def talk_json_path
  $localtalk
end
target_client() click to toggle source
# File lib/net_shell/builtin_commands/recap.rb, line 48
def target_client
  params[:client] ? @shell.client(params[:client]) : client
end
text_output() click to toggle source
# File lib/net_shell/builtin_commands/recap.rb, line 90
def text_output
  index = -1
  set = params[:reverse] ? messages : messages.reverse
  (set.reverse[range_for_args(args)].map do |msg|
    index += 1
    index_str = sprintf("%3d", index)
    "#{index_str} #{timecode(msg)} #{sender(msg)} #{render_text(msg[:message])}"
  end).join("\n")
end
timecode(msg) click to toggle source
# File lib/net_shell/builtin_commands/recap.rb, line 78
def timecode(msg)
  delta = msg[:time] - target_client.start_time
  all_seconds = delta.to_i

  milliseconds = 1000.0*(delta - all_seconds)
  hours = (all_seconds / 3660).to_i
  minutes = ((all_seconds - 3660*hours) / 60).to_i
  seconds = (all_seconds - 3600*hours - 60*minutes).to_i

  return sprintf("%3d:%02d:%02d.%03d", hours, minutes, seconds, milliseconds).light_black
end
timestamp(ts) click to toggle source
# File lib/net_shell/builtin_commands/deploy.rb, line 250
def timestamp(ts)
  DateTime.strptime(ts.to_s,'%s').strftime("%Y-%m-%d %H:%M:%S").style(:timestamp)
end
toplevel_value() click to toggle source
# File lib/net_shell/builtin_commands/excerpt.rb, line 76
def toplevel_value
  json = @input.read_all
  object = symbolify(JSON.parse(json)) rescue nil
  type = (talk.expand_name(params[:type]) rescue nil) || talk.guess_class(object) rescue nil
  
  return nil if type.nil? or object.nil?
  return [object, type] if params[:no_bypass]
  return bypass(object, type)
end
translate(value) click to toggle source
# File lib/net_shell/builtin_commands/translate.rb, line 27
def translate(value)
  is_numeric = (not(value.is_a?(String)) or value.match(/^[-+]?[0-9]+(.[0-9]+)?$/) != nil)

  candidates = case is_numeric
  when true
    talk.definition[:enumeration].inject([]) do |c, enum|
      c + (enum[:constant].select { |constant| constant[:value] == value.to_f }).map { |x| { collection:enum, constant:x } }
    end
  when false
    talk.definition[:glossary].inject([]) do |c, glossary|
      c + (glossary[:term].select { |term| term[:value] == value }).map { |x| { collection:glossary, constant:x } }
    end
  end

  return "No matches for #{value}" if candidates.empty?

  (candidates.map { |item| "#{item[:constant][:name].style(:constant_name)} (#{talk.truncated_name item[:collection][:name].style(:collection_name)}): #{item[:constant][:description]}" }).join("\n")
end
try_acl(params, acl) click to toggle source
# File lib/net_shell/builtin_commands/ssh.rb, line 29
def try_acl(params, acl)
  host = usherm.host_named(params[:host])
  service = usherm.service_for_id(acl[:idService])
  options = [
    { host:host[:ipAddrInt], port:service[:port] },
    { host:host[:ipAddrExt], port:acl[:port] }
  ]

  result = try_connection_options(options)
  unless result.nil? then
    process = fork { exec "ssh -l #{params[:user]} -p #{result[:port]} #{result[:ip]}" }
    Process.waitpid(process)
  end

  not result.nil?
end
try_connection(hostname, port) click to toggle source
# File lib/a4tools.rb, line 37
def try_connection(hostname, port)
  s = TCPSocket.new(hostname, port) rescue false
  s != false
end
try_connection_options(options, timeout=2) click to toggle source

array of { :host, :port }

# File lib/a4tools.rb, line 43
def try_connection_options(options, timeout=2)
  mutex = Mutex.new
  condition = ConditionVariable.new
  result = nil

  mutex.synchronize do
    options.each do |opt|
      Thread.new do
        if try_connection(opt[:host], opt[:port]) then
          result = opt
          mutex.synchronize { condition.signal }
        end
      end
    end

    condition.wait(mutex, timeout)
  end
  result
end
type_at_depth(field, depth) click to toggle source
# File lib/net_shell/builtin_commands/build.rb, line 126
def type_at_depth(field, depth)
  field[:type][0 .. -1 - depth].join("")
end
use_json?() click to toggle source
# File lib/net_shell/builtin_commands/recap.rb, line 114
def use_json?
  params[:json] or params[:raw] or params[:array]
end
verbose_host(host) click to toggle source
# File lib/net_shell/builtin_commands/host.rb, line 91
def verbose_host(host)
  datacenter = usherm.datacenter(host[:idDataCenter])
  out = "Host #{host[:hostName].style(:host)} (#{host[:idSystemHost]})\n"
  out += "\tInternal #{host[:ipAddrInt].style(:ip)}\n"
  out += "\tExternal #{host[:ipAddrExt].style(:ip)}\n"
  if datacenter.nil?
    out += "\tDatacenter: not found in usher (#{host[:idDataCenter]})\n"
  else
    out += "\tDatacenter: #{datacenter[:dataCenterName].style(:datacenter)} (#{host[:idDataCenter]})\n"
  end
  out += "\tHost environment: #{usherm.env_type(host[:systemHostEnvironment])}\n"
  out += "\tUsher system type: #{usherm.system_type(host[:usherResponseType])}\n"
  out += (host[:providers].map { |id_provider| provider_line(id_provider) }).compact.join("\n")

  out += "\tACLs:\n"
  acls = usherm.acls_for_host_id(host[:idSystemHost])
  if acls.empty?
    out += "\t\tNo ACLs for this host."
  else
    out += (acls.map { |acl| acl_line(acl) }).compact.join("\n")
  end

  out
end
yes_no(b) click to toggle source
# File lib/net_shell/builtin_commands/site.rb, line 58
def yes_no(b)
  b ? "yes" : "no"
end