Class: SystemInfo

Inherits:
Object
  • Object
show all
Defined in:
lib/sys.rb

Overview

SystemInfo

A container for the platform specific system information. Portions of this code were originally from Amazon’s EC2 AMI tools, specifically lib/platform.rb.

Constant Summary collapse

VERSION =
4.freeze
IMPLEMENTATIONS =
[

  # These are for JRuby, System.getproperty('os.name'). 
  # For a list of all values, see: http://lopica.sourceforge.net/os.html
  [/mac\s*os\s*x/i,     :unix,    :osx     ],  
  [/sunos/i,            :unix,    :solaris ], 
  [/windows\s*ce/i,     :win32,   :windows ],
  [/windows/i,          :win32,   :windows ],  
  [/osx/i,              :unix,    :osx     ],

  # TODO: implement other windows matches: # /djgpp|(cyg|ms|bcc)win|mingw/ (from mongrel)

  # These are for RUBY_PLATFORM and JRuby
  [/java/i,    :java,    :java             ],
  [/darwin/i,  :unix,    :osx              ],
  [/linux/i,   :unix,    :linux            ],
  [/freebsd/i, :unix,    :freebsd          ],
  [/netbsd/i,  :unix,    :netbsd           ],
  [/solaris/i, :unix,    :solaris          ],
  [/irix/i,    :unix,    :irix             ],
  [/cygwin/i,  :unix,    :cygwin           ],
  [/mswin/i,   :win32,   :windows          ],
  [/mingw/i,   :win32,   :mingw            ],
  [/bccwin/i,  :win32,   :bccwin           ],
  [/wince/i,   :win32,   :wince            ],
  [/vms/i,     :vms,     :vms              ],
  [/os2/i,     :os2,     :os2              ],
  [nil,        :unknown, :unknown          ],

].freeze
ARCHITECTURES =
[
  [/(i\d86)/i,  :i386             ],
  [/x86_64/i,   :x86_64           ],
  [/x86/i,      :i386             ],  # JRuby
  [/ia64/i,     :ia64             ],
  [/alpha/i,    :alpha            ],
  [/sparc/i,    :sparc            ],
  [/mips/i,     :mips             ],
  [/powerpc/i,  :powerpc          ],
  [/universal/i,:universal        ],
  [nil,         :unknown          ],
].freeze

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initializeSystemInfo

Returns a new instance of SystemInfo.



69
70
71
72
# File 'lib/sys.rb', line 69

def initialize
  @os, @implementation, @architecture = guess
  @hostname, @ipaddress, @uptime = get_info
end

Instance Attribute Details

#architectureObject (readonly) Also known as: arch

Returns the value of attribute architecture.



59
60
61
# File 'lib/sys.rb', line 59

def architecture
  @architecture
end

#hostnameObject (readonly)

Returns the value of attribute hostname.



60
61
62
# File 'lib/sys.rb', line 60

def hostname
  @hostname
end

#implementationObject (readonly) Also known as: impl

Returns the value of attribute implementation.



58
59
60
# File 'lib/sys.rb', line 58

def implementation
  @implementation
end

#ipaddressObject (readonly)

Returns the value of attribute ipaddress.



61
62
63
# File 'lib/sys.rb', line 61

def ipaddress
  @ipaddress
end

#osObject (readonly)

Returns the value of attribute os.



57
58
59
# File 'lib/sys.rb', line 57

def os
  @os
end

#uptimeObject (readonly)

Returns the value of attribute uptime.



62
63
64
# File 'lib/sys.rb', line 62

def uptime
  @uptime
end

Instance Method Details

#get_infoObject

get_info

Returns [hostname, ipaddr, uptime] for the local machine



131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
# File 'lib/sys.rb', line 131

def get_info
  hostname = :unknown
  ipaddr = :unknown
  uptime = :unknown

  begin
    hostname = local_hostname
    ipaddr = local_ip_address
    uptime = local_uptime       
  rescue => ex
    # Be silent!
  end

  [hostname, ipaddr, uptime]
end

#guessObject

guess

This is called at require-time in stella.rb. It guesses the current operating system, implementation, architecture. Returns [os, impl, arch]



79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
# File 'lib/sys.rb', line 79

def guess
  os = :unknown
  impl = :unknown
  arch = :unknown
  IMPLEMENTATIONS.each do |r, o, i|
    if r and RUBY_PLATFORM =~ r
      os, impl = [o, i]
      break
    end
  end
  ARCHITECTURES.each do |r, a|
    if r and RUBY_PLATFORM =~ r
      arch = a
      break
    end
  end
  
  #
  if os == :win32
    #require 'Win32API'

  # If we're running in java, we'll need to look elsewhere
  # for the implementation and architecture. 
  # We'll replace IMPL and ARCH with what we find. 
  elsif os == :java
    require 'java'
    include_class java.lang.System
    
    osname = System.getProperty("os.name")
    IMPLEMENTATIONS.each do |r, o, i|
      if r and osname =~ r
        impl = i
        break
      end
    end
    
    osarch = System.getProperty("os.arch")
    ARCHITECTURES.each do |r, a|
      if r and osarch =~ r
        arch = a
        break
      end
    end
    
  end

  [os, impl, arch]
end

#homeObject



258
259
260
261
262
263
264
265
266
# File 'lib/sys.rb', line 258

def home
  if @os == :unix
    File.expand_path(ENV['HOME'])
  elsif @os == :win32
    File.expand_path(ENV['USERPROFILE'])
  else
    raise "paths not implemented for: #{@os}"
  end
end

#local_hostnameObject

local_hostname

Return the hostname for the local machine



150
151
152
# File 'lib/sys.rb', line 150

def local_hostname
  Socket.gethostname
end

#local_ip_addressObject

Return the local IP address which receives external traffic from: coderrr.wordpress.com/2008/05/28/get-your-local-ip-address/ NOTE: This does not open a connection to the IP address.



208
209
210
211
212
213
214
# File 'lib/sys.rb', line 208

def local_ip_address
  # turn off reverse DNS resolution temporarily 
  orig, Socket.do_not_reverse_lookup = Socket.do_not_reverse_lookup, true   
  UDPSocket.open {|s| s.connect('75.101.137.7', 1); s.addr.last } # Solutious IP
ensure  
  Socket.do_not_reverse_lookup = orig
end

#local_ip_address_altObject

Returns the local IP address based on the hostname. According to coderrr (see comments on blog link above), this implementation doesn’t guarantee that it will return the address for the interface external traffic goes through. It’s also possible the hostname isn’t resolvable to the local IP.



222
223
224
225
226
227
228
229
230
# File 'lib/sys.rb', line 222

def local_ip_address_alt
  ipaddr = :unknown
  begin
    saddr = Socket.getaddrinfo(  Socket.gethostname, nil, Socket::AF_UNSPEC, Socket::SOCK_STREAM, nil, Socket::AI_CANONNAME)
    ipaddr = saddr.select{|type| type[0] == 'AF_INET' }[0][3]
  rescue => ex
  end
  ipaddr
end

#local_uptimeObject

local_uptime

Returns the local uptime in hours. Use Win32API in Windows, ‘sysctl -b kern.boottime’ os osx, and ‘who -b’ on unix. Based on Ruby Quiz solutions by: Matthias Reitinger On Windows, see also: net statistics server



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
188
189
190
191
192
193
194
195
196
197
198
199
200
201
# File 'lib/sys.rb', line 160

def local_uptime

  # Each method must return uptime in seconds
  methods = {

    :win32_windows => lambda {
      # Win32API is required in self.guess
      getTickCount = Win32API.new("kernel32", "GetTickCount", nil, 'L')
      ((getTickCount.call()).to_f / 1000).to_f
    },

    # Ya, this is kinda wack. Ruby -> Java -> Kernel32. See:
    # http://www.oreillynet.com/ruby/blog/2008/01/jruby_meets_the_windows_api_1.html
    # http://msdn.microsoft.com/en-us/library/ms724408(VS.85).aspx
    # Ruby 1.9.1: Win32API is now deprecated in favor of using the DL library.
    :java_windows => lambda {
      kernel32 = com.sun.jna.NativeLibrary.getInstance('kernel32')
      buf = java.nio.ByteBuffer.allocate(256)
      (kernel32.getFunction('GetTickCount').invokeInt([256, buf].to_java).to_f / 1000).to_f 
    },
    
    :unix_osx => lambda {
      # This is faster than who and could work on BSD also. 
      (Time.now.to_f - Time.at(`sysctl -b kern.boottime 2>/dev/null`.unpack('L').first).to_f).to_f
    },
    # This should work for most unix flavours. 
    :unix => lambda {
      # who is sloooooow. Use File.read('/proc/uptime')
      (Time.now.to_f - Time.parse(`who -b 2>/dev/null`).to_f)
    }
  }

  hours = 0
  
  begin
    key = platform
    method = (methods.has_key? key) ? methods[key] : methods[:unix]
    hours = (method.call) / 3600 # seconds to hours
  rescue => ex
  end
  hours
end

#pathsObject

Returns the environment PATH as an Array



244
245
246
247
248
249
250
251
252
# File 'lib/sys.rb', line 244

def paths
  if @os == :unix
    (ENV['PATH'] || '').split(':')
  elsif
    (ENV['PATH'] || '').split(';') # Note tested!
  else
    raise "paths not implemented for: #{@os}"
  end
end

#platformObject

returns a symbol in the form: os_implementation. This is used throughout Stella for platform specific support.



234
235
236
# File 'lib/sys.rb', line 234

def platform
  "#{@os}_#{@implementation}".to_sym
end

#rubyObject

Returns Ruby version as an array



239
240
241
# File 'lib/sys.rb', line 239

def ruby
  RUBY_VERSION.split('.').map { |v| v.to_i }
end

#to_sObject

Print friendly system information.



269
270
271
272
# File 'lib/sys.rb', line 269

def to_s
  sprintf("Hostname: %s#{$/}IP Address: %s#{$/}System: %s#{$/}Uptime: %.2f (hours)#{$/}Ruby: #{ruby.join('.')}", 
    @hostname, @ipaddress, "#{@os}-#{@implementation}-#{@architecture}", @uptime)
end

#userObject



254
255
256
# File 'lib/sys.rb', line 254

def user
  ENV['USER']
end