summaryrefslogtreecommitdiffstats
path: root/lib/puppet/rails/host.rb
blob: 3efdfa9df27e8c10537485e1621deb70a157e089 (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
require 'puppet/rails/resource'
require 'puppet/util/rails/collection_merger'

class Puppet::Rails::Host < ActiveRecord::Base
    include Puppet::Util::CollectionMerger

    has_many :fact_values, :through => :fact_names 
    has_many :fact_names, :dependent => :destroy
    belongs_to :puppet_classes
    has_many :source_files
    has_many :resources,
        :include => [ :param_names, :param_values ],
        :dependent => :destroy

    acts_as_taggable

    # If the host already exists, get rid of its objects
    def self.clean(host)
        if obj = self.find_by_name(host)
            obj.rails_objects.clear
            return obj
        else
            return nil
        end
    end

    # Store our host in the database.
    def self.store(hash)
        unless name = hash[:name]
            raise ArgumentError, "You must specify the hostname for storage"
        end

        args = {}

        unless host = find_by_name(name)
            host = new(:name => name)
        end
        if ip = hash[:facts]["ipaddress"]
            host.ip = ip
        end

        # Store the facts into the database.
        host.setfacts(hash[:facts])

        unless hash[:resources]
            raise ArgumentError, "You must pass resources"
        end

        host.setresources(hash[:resources])

        host.last_compile = Time.now

        host.save

        return host
    end

    def tags=(tags)
        tags.each do |tag|   
            self.tag_with tag
        end
    end

    # Return the value of a fact.
    def fact(name)
        if fv = self.fact_values.find(:first, :conditions => "fact_names.name = '#{name}'") 
            return fv.value
        else
            return nil
        end
    end

    def setfacts(facts)
        collection_merge(:fact_names, facts) do |name, value|
            fn = fact_names.find_by_name(name) || fact_names.build(:name => name)
            # We're only ever going to have one fact value, at this point.
            unless fv = fn.fact_values.find_by_value(value)
                fv = fn.fact_values.build(:value => value)
            end
            fn.fact_values = [fv]

            fn
        end
    end

    # Set our resources.
    def setresources(list)
        collection_merge(:resources, list) do |resource|
            resource.to_rails(self)
        end
    end

    def update_connect_time
        self.last_connect = Time.now
        save
    end
end

# $Id$