summaryrefslogtreecommitdiffstats
path: root/lib/facter/util/uptime.rb
blob: 4e6a7b6d7edd5ee6ee073e064aa03b28c539f896 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
require 'time'

# A module to gather uptime facts
#
module Facter::Util::Uptime
    def self.get_uptime_seconds_unix
        uptime_proc_uptime or uptime_sysctl or uptime_kstat or uptime_who_dash_b
    end

    def self.get_uptime_seconds_win
      require 'win32ole'
      wmi = WIN32OLE.connect("winmgmts://")
      query = wmi.ExecQuery("select * from Win32_OperatingSystem")
      last_boot = ""
      query.each { |x| last_boot = x.LastBootupTime}
      self.compute_uptime(Time.parse(last_boot.split('.').first)) 
    end

    private

    def self.uptime_proc_uptime
        if output = Facter::Util::Resolution.exec("/bin/cat #{uptime_file} 2>/dev/null")
            output.chomp.split(" ").first.to_i
        end
    end

    def self.uptime_sysctl
        if output = Facter::Util::Resolution.exec("#{uptime_sysctl_cmd} 2>/dev/null")
            compute_uptime(Time.at(output.unpack('L').first))
        end
    end

    def self.uptime_kstat
        if output = Facter::Util::Resolution.exec("#{uptime_kstat_cmd} 2>/dev/null")
            compute_uptime(Time.at(output.chomp.split(/\s/).last.to_i))
        end
    end

    def self.uptime_who_dash_b
        if output = Facter::Util::Resolution.exec("#{uptime_who_cmd} 2>/dev/null")
            compute_uptime(Time.parse(output))
        end
    end

    def self.compute_uptime(time)
        (Time.now - time).to_i
    end

    def self.uptime_file
        "/proc/uptime"
    end

    def self.uptime_sysctl_cmd
        'sysctl -b kern.boottime'
    end

    def self.uptime_kstat_cmd
        'kstat -p unix:::boot_time'
    end

    def self.uptime_who_cmd
        'who -b'
    end
end