summaryrefslogtreecommitdiffstats
path: root/lib/facter.rb
blob: 9e03892bde6b111486e0ffdf6e5e305d3e51e3db (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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
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
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
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
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
# $Id$
#--
# Copyright 2004 Luke Kanies <luke@madstop.com>
#
# This program is free software. It may be redistributed and/or modified under
# the terms of the GPL version 2 (or later), the Perl Artistic licence, or the
# Ruby licence.
# 
#--

#--------------------------------------------------------------------
class Facter
    include Comparable
    include Enumerable

    FACTERVERSION="1.0.0"
	# = Facter 1.0
    # Functions as a hash of 'facts' you might care about about your
    # system, such as mac address, IP address, Video card, etc.
    # returns them dynamically

	# == Synopsis
	#
    # Generally, treat <tt>Facter</tt> as a hash:
    # == Example
    # require 'facter'
    # puts Facter['operatingsystem']
    #


    @@facts = {}
    GREEN = ""
    RESET = ""
    @@debug = 0
    @@os = nil
    @@osrel = nil

    attr_accessor :name, :os, :osrel, :hardware, :searching

	#----------------------------------------------------------------
	# module methods
	#----------------------------------------------------------------

    def Facter.version
        return FACTERVERSION
    end

    def Facter.debug(string)
        if string.nil?
            return
        end
        if @@debug != 0
            puts GREEN + string + RESET
        end
    end

	#----------------------------------------------------------------
	def Facter.[](name)
        if @@facts.include?(name.downcase)
            return @@facts[name.downcase]
        else
            return Facter.add(name)
        end
    end
	#----------------------------------------------------------------

	#----------------------------------------------------------------
    def Facter.add(name)
        fact = nil
        dcname = name.downcase

        if @@facts.include?(dcname)
            fact = @@facts[dcname]
        else
            Facter.new(dcname)
            fact = @@facts[dcname]
        end

        if block_given?
            fact.add
        end

        return fact
    end
	#----------------------------------------------------------------

	#----------------------------------------------------------------
    class << self
        include Enumerable
        def each
            @@facts.each { |name,fact|
                if fact.suitable?
                    value = fact.value
                    unless value.nil?
                        yield name, fact.value
                    end
                end
            }
        end
    end
	#----------------------------------------------------------------

	#----------------------------------------------------------------
    def Facter.reset
        @@facts.each { |name,fact|
            @@facts.delete(name)
        }
    end
	#----------------------------------------------------------------

	#----------------------------------------------------------------
	# 
	def Facter.debugging(bit)
		if bit
            case bit
            when TrueClass: @@debug = 1
            when FalseClass: @@debug = 0
            when Fixnum: 
                if bit > 0
                    @@debug = 1
                else
                    @@debug = 0
                end
            when String:
                if bit.downcase == 'off'
                    @@debug = 0
                else
                    @@debug = 1
                end
            else
                @@debug = 0
            end
		else
			@@debug = 0
		end
	end
	#----------------------------------------------------------------

	#----------------------------------------------------------------
    #def Facter.init
    #    @@os = @@facts["operatingsystem"].value
    #    @@release = @@facts["operatingsystemrelease"].value
    #end
	#----------------------------------------------------------------

	#----------------------------------------------------------------
    def Facter.list
        return @@facts.keys
    end
	#----------------------------------------------------------------

	#----------------------------------------------------------------
    def Facter.os
        return @@os
    end
	#----------------------------------------------------------------

	#----------------------------------------------------------------
    def Facter.release
        return @@release
    end
	#----------------------------------------------------------------

	#----------------------------------------------------------------
    def <=>(other)
        return self.value <=> other
    end
	#----------------------------------------------------------------

	#----------------------------------------------------------------
    def initialize(name)
        @name = name.downcase
        if @@facts.include?(@name)
            raise "A fact named %s already exists" % name
        else
            @@facts[@name] = self
        end

        @resolves = []
        @searching = false
    end
	#----------------------------------------------------------------

	#----------------------------------------------------------------
    # as long as this doesn't work over the 'net, it should probably
    # be optimized to throw away any resolutions not valid for the machine
    # it's running on
    # but that's not currently done...
    def add
        resolve = Resolution.new(@name)
        yield(resolve)

        # skip resolves that will never be suitable for us
        return unless resolve.suitable?

        # insert resolves in order of number of tags
        inserted = false
        @resolves.each_with_index { |r,index|
            if resolve.length > r.length
                @resolves.insert(index,resolve)
                inserted = true
                break
            end
        }

        unless inserted
            @resolves.push resolve
        end
    end
	#----------------------------------------------------------------

	#----------------------------------------------------------------
    # iterate across all of the currently configured resolves
    # sort the resolves in order of most tags first, so we're getting
    # the most specific answers first, hopefully
    def each
#        @resolves.sort { |a,b|
#            puts "for tag %s, alength is %s and blength is %s" %
#                [@name, a.length, b.length]
#            b.length <=> a.length
#        }.each { |resolve|
#            yield resolve
#        }
        @resolves.each { |r| yield r }
    end
	#----------------------------------------------------------------

	#----------------------------------------------------------------
    # return a count of resolution mechanisms available
    def count
        return @resolves.length
    end
	#----------------------------------------------------------------

	#----------------------------------------------------------------
    # is this fact suitable for finding answers on this host?
    # again, this should really be optimizing by throwing away everything
    # not suitable, but...
    def suitable?
        return false if @resolves.length == 0

        unless defined? @suitable
            @suitable = false
            self.each { |resolve|
                if resolve.suitable?
                    @suitable = true
                    break
                end
            }
        end

        return @suitable
    end
	#----------------------------------------------------------------

	#----------------------------------------------------------------
    def value
        # make sure we don't get stuck in recursive dependency loops
        if @searching
            Facter.debug "Caught recursion on %s" % @name
            
            # return a cached value if we've got it
            if @value
                return @value
            else
                return nil
            end
        end
        @value = nil
        foundsuits = false

        if @resolves.length == 0
            Facter.debug "No resolves for %s" % @name
            return nil
        end

        @searching = true
        @resolves.each { |resolve|
            #Facter.debug "Searching resolves for %s" % @name
            if resolve.suitable?
                @value = resolve.value
                foundsuits = true
            else
                Facter.debug "Unsuitable resolve %s for %s" % [resolve,@name]
            end
            unless @value.nil? or @value == ""
                break
            end
        }
        @searching = false

        unless foundsuits
            Facter.debug "Found no suitable resolves of %s for %s" %
                [@resolves.length,@name]
        end

        if @value.nil?
            # nothing
            Facter.debug("value for %s is still nil" % @name)
            return nil
        else
            return @value
        end
    end
	#----------------------------------------------------------------

	#----------------------------------------------------------------
    class Resolution
        attr_accessor :interpreter, :code, :name

        def Resolution.exec(code, interpreter = "/bin/sh")
            if interpreter == "/bin/sh"
                binary = code.split(/\s+/).shift

                path = nil
                if binary !~ /^\//
                    path = %x{which #{binary} 2>/dev/null}.chomp
                    if path == ""
                        # we don't have the binary necessary
                        return nil
                    end
                else
                    path = binary
                end

                unless FileTest.exists?(path)
                    # our binary does not exist
                    return nil
                end
                out = nil
                begin
                    out = %x{#{code}}.chomp
                rescue => detail
                    $stderr.puts detail
                end
                if out == ""
                    return nil
                else
                    return out
                end
            else
                raise "non-sh interpreters are not currently supported"
            end
        end

        def initialize(name)
            @name = name
            @tags = []
        end

        def length
            @tags.length
        end

        def suitable?
            unless defined? @suitable
                @suitable = true
                if @tags.length == 0
                    #Facter.debug "'%s' has no tags" % @name
                    return true
                end
                @tags.each { |tag|
                    unless tag.true?
                        #Facter.debug "'%s' is false" % tag
                        @suitable = false
                    end
                }
            end

            return @suitable
        end

        def tag(fact,op,value)
            @tags.push Tag.new(fact,op,value)
        end

        def to_s
            return self.value()
        end

        # how we get a value for our resolution mechanism
        def value
            #puts "called %s value" % @name
            value = nil
            if @code.is_a?(Proc)
                value = @code.call()
            else
                unless defined? @interpreter
                    @interpreter = "/bin/sh"
                end
                if @code.nil?
                    $stderr.puts "Code for %s is nil" % @name
                else
                    value = Resolution.exec(@code,@interpreter)
                end
            end

            if value == ""
                value = nil
            end

            return value
        end
    end
	#----------------------------------------------------------------

	#----------------------------------------------------------------
    class Tag
        attr_accessor :fact, :op, :value

        def initialize(fact,op,value)
            @fact = fact
            if op == "="
                op = "=="
            end
            @op = op
            @value = value
        end

        def to_s
            return "'%s' %s '%s'" % [@fact,@op,@value]
        end

        def true?
            value = Facter[@fact].value

            if value.nil?
                return false
            end

            str = "'%s' %s '%s'" % [value,@op,@value]
            begin
                if eval(str)
                    return true
                else
                    return false
                end
            rescue => detail
                $stderr.puts "Failed to test '%s': %s" % [str,detail]
                return false
            end
        end
    end
	#----------------------------------------------------------------

    # Load all of the default facts
    def Facter.load
        Facter["OperatingSystem"].add { |obj|
            obj.code = 'uname -s'
        }

        Facter["OperatingSystemRelease"].add { |obj|
            obj.code = 'uname -r'
        }

        Facter["HardwareModel"].add { |obj|
            obj.code = 'uname -m'
            #obj.os = "SunOS"
            #obj.tag("operatingsystem","=","SunOS")
        }

        Facter["CfKey"].add { |obj|
            obj.code = proc {
                value = nil
                ["/usr/local/etc/cfkey.pub",
                    "/etc/cfkey.pub",
                    "/var/cfng/keys/localhost.pub",
                    "/var/cfengine/ppkeys/localhost.pub"
                ].each { |file|
                    if FileTest.file?(file)
                        File.open(file) { |openfile|
                            value = openfile.readlines.reject { |line|
                                line =~ /PUBLIC KEY/
                            }.collect { |line|
                                line.chomp
                            }.join("")
                        }
                    end
                    if value
                        break
                    end
                }

                value
            }
        }

        Facter["Domain"].add { |obj|
            obj.code = proc {
                if defined? $domain and ! $domain.nil?
                    $domain
                end
            }
        }
        Facter["Domain"].add { |obj|
            obj.code = proc {
                domain = Resolution.exec('domainname')
                # make sure it's a real domain
                if domain =~ /.+\..+/
                    domain
                else
                    nil
                end
            }
        }
        Facter["Domain"].add { |obj|
            obj.code = proc {
                value = nil
                unless FileTest.exists?("/etc/resolv.conf")
                    return nil
                end
                File.open("/etc/resolv.conf") { |file|
                    # is the domain set?
                    file.each { |line|
                        if line =~ /domain\s+(\S+)/
                            value = $1
                            break
                        end
                    }
                }
                ! value and File.open("/etc/resolv.conf") { |file|
                    # is the search path set?
                    file.each { |line|
                        if line =~ /search\s+(\S+)/
                            value = $1
                            break
                        end
                    }
                }
                value
            }
        }
        Facter["Hostname"].add { |obj|
            obj.code = proc {
                hostname = nil
                name = Resolution.exec('hostname')
                if name =~ /^([\w-]+)\.(.+)$/
                    hostname = $1
                    # the Domain class uses this
                    $domain = $2
                else
                    hostname = name
                end
                hostname
            }
        }

        Facter["IPHostNumber"].add { |obj|
            obj.code = proc {
                require 'resolv'

                begin
                    hostname = Facter["hostname"].value
                    ip = Resolv.getaddress(hostname)
                    unless ip == "127.0.0.1"
                        ip
                    end
                rescue Resolv::ResolvError
                    nil
                rescue NoMethodError # i think this is a bug in resolv.rb?
                    nil
                end
            }
        }
        Facter["IPHostNumber"].add { |obj|
            obj.code = proc {
                hostname = Facter["hostname"].value
                # crap, we need Hostname to exist for this to
                # work
                list = Resolution.exec("host #{hostname}").chomp.split(/\s/)
                if defined? list[-1] and list[-1] =~ /[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+/
                    list[-1]
                end
            }
        }

        ["/etc/ssh","/usr/local/etc/ssh","/etc","/usr/local/etc"].each { |dir|
            {"SSHDSAKey" => "ssh_host_dsa_key.pub",
                    "SSHRSAKey" => "ssh_host_rsa_key.pub"}.each { |name,file|
                Facter[name].add { |obj|
                    obj.code = proc {
                        value = nil
                        filepath = File.join(dir,file)
                        if FileTest.file?(filepath)
                            begin
                                value = File.open(filepath).read.chomp
                            rescue
                                return nil
                            end
                        end
                        return value
                    } # end of proc
                } # end of add
            } # end of hash each
        } # end of dir each

        Facter["UniqueId"].add { |obj|
            obj.code = 'hostid'
            obj.interpreter = '/bin/sh'
            obj.tag("operatingsystem","=","SunOS")
            #obj.os = "SunOS"
        }
        Facter["HardwareISA"].add { |obj|
            obj.code = 'uname -p'
            obj.interpreter = '/bin/sh'
            #obj.os = "SunOS"
            obj.tag("operatingsystem","=","SunOS")
        }
        Facter["MacAddress"].add { |obj|
            #obj.os = "SunOS"
            obj.tag("operatingsystem","=","SunOS")
            obj.code = proc {
                ether = nil
                output = %x{/sbin/ifconfig -a}

                output =~ /ether (\w{1,2}:\w{1,2}:\w{1,2}:\w{1,2}:\w{1,2}:\w{1,2})/
                ether = $1

                ether
            }
        }
        Facter["MacAddress"].add { |obj|
            #obj.os = "Darwin"
            obj.tag("operatingsystem","=","Darwin")
            obj.code = proc {
                ether = nil
                output = %x{/sbin/ifconfig}

                output.split(/^\S/).each { |str|
                    if str =~ /10baseT/ # we're wired
                        str =~ /ether (\w\w:\w\w:\w\w:\w\w:\w\w:\w\w)/
                        ether = $1
                    end
                }

                ether
            }
        }
        Facter["IPHostnumber"].add { |obj|
            #obj.os = "Darwin"
            obj.tag("operatingsystem","=","Darwin")
            obj.code = proc {
                ip = nil
                output = %x{/sbin/ifconfig}

                output.split(/^\S/).each { |str|
                    if str =~ /inet ([0-9]+\.[0-9]+\.[0-9]+\.[0-9]+)/
                        tmp = $1
                        unless tmp =~ /127\./
                            ip = tmp
                            break
                        end
                    end
                }

                ip
            }
        }
        Facter["Hostname"].add { |obj|
            #obj.os = "Darwin"
            #obj.release = "R7"
            obj.tag("operatingsystem","=","Darwin")
            obj.tag("operatingsystemrelease","=","R7")
            obj.code = proc {
                hostname = nil
                File.open(
                    "/Library/Preferences/SystemConfiguration/preferences.plist"
                ) { |file|
                    found = 0
                    file.each { |line|
                        if line =~ /ComputerName/i
                            found = 1
                            next
                        end
                        if found == 1
                            if line =~ /<string>([\w|-]+)<\/string>/
                                hostname = $1
                                break
                            end
                        end
                    }
                }

                if hostname != nil
                    hostname
                end
            }
        }
        Facter["IPHostnumber"].add { |obj|
            #obj.os = "Darwin"
            #obj.release = "R6"
            obj.tag("operatingsystem","=","Darwin")
            obj.tag("operatingsystemrelease","=","R6")
            obj.code = proc {
                hostname = nil
                File.open(
                    "/var/db/SystemConfiguration/preferences.xml"
                ) { |file|
                    found = 0
                    file.each { |line|
                        if line =~ /ComputerName/i
                            found = 1
                            next
                        end
                        if found == 1
                            if line =~ /<string>([\w|-]+)<\/string>/
                                hostname = $1
                                break
                            end
                        end
                    }
                }

                if hostname != nil
                    hostname
                end
            }
        }
        Facter["IPHostnumber"].add { |obj|
            #obj.os = "Darwin"
            #obj.release = "R6"
            obj.tag("operatingsystem","=","Darwin")
            obj.tag("operatingsystemrelease","=","R6")
            obj.code = proc {
                ether = nil
                output = %x{/sbin/ifconfig}

                output =~ /HWaddr (\w\w:\w\w:\w\w:\w\w:\w\w:\w\w)/
                ether = $1

                ether
            }
        }
        Facter["Distro"].add { |obj|
            #obj.os = "Linux"
            obj.tag("operatingsystem","=","Linux")
            obj.code = proc {
                if FileTest.exists?("/etc/debian_version")
                    return "Debian"
                elsif FileTest.exists?("/etc/gentoo-release")
                    return "Gentoo"
                elsif FileTest.exists?("/etc/fedora-release")
                    return "Fedora"
                elsif FileTest.exists?("/etc/redhat-release")
                    return "RedHat"
                end
            }
        }
        Facter["ps"].add { |obj|
            obj.code = "echo 'ps -ef'"
        }
        Facter["ps"].add { |obj|
            obj.tag("operatingsystem","=","Darwin")
            obj.code = "echo 'ps -auxwww'"
        }

        Facter["id"].add { |obj|
            obj.tag("operatingsystem","=","Linux")
            obj.code = "whoami"
        }
    end

    Facter.load
end

# try to load a local fact library, if there happens to be one
begin
    require 'facter/local'
rescue LoadError
    # no worries
end