summaryrefslogtreecommitdiffstats
path: root/lib/puppet/parser/resource.rb
blob: 47dc798b3353bc8b0483873ac7559739323437f7 (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
# A resource that we're managing.  This handles making sure that only subclasses
# can set parameters.
class Puppet::Parser::Resource
    require 'puppet/parser/resource/param'
    require 'puppet/parser/resource/reference'
    require 'puppet/util/tagging'
    include Puppet::Util
    include Puppet::Util::MethodHelper
    include Puppet::Util::Errors
    include Puppet::Util::Logging
    include Puppet::Util::Tagging

    attr_accessor :source, :line, :file, :scope, :rails_id
    attr_accessor :virtual, :override, :translated

    attr_reader :exported, :evaluated, :params

    # Determine whether the provided parameter name is a relationship parameter.
    def self.relationship_parameter?(name)
        unless defined?(@relationship_names)
            @relationship_names = Puppet::Type.relationship_params.collect { |p| p.name }
        end
        @relationship_names.include?(name)
    end

    # Proxy a few methods to our @ref object.
    [:builtin?, :type, :title].each do |method|
        define_method(method) do
            @ref.send(method)
        end
    end

    # Set up some boolean test methods
    [:exported, :translated, :override, :virtual, :evaluated].each do |method|
        newmeth = (method.to_s + "?").intern
        define_method(newmeth) do
            self.send(method)
        end
    end

    def [](param)
        param = symbolize(param)
        if param == :title
            return self.title
        end
        if @params.has_key?(param)
            @params[param].value
        else
            nil
        end
    end

    def builtin=(bool)
        @ref.builtin = bool
    end

    # Retrieve the associated definition and evaluate it.
    def evaluate
        if klass = @ref.definedtype
            finish()
            return klass.evaluate_code(self)
        elsif builtin?
            devfail "Cannot evaluate a builtin type"
        else
            self.fail "Cannot find definition %s" % self.type
        end
    ensure
        @evaluated = true
    end

    # Mark this resource as both exported and virtual,
    # or remove the exported mark.
    def exported=(value)
        if value
            @virtual = true
            @exported = value
        else
            @exported = value
        end
    end

    # Do any finishing work on this object, called before evaluation or
    # before storage/translation.
    def finish
        return if finished?
        @finished = true
        add_defaults()
        add_metaparams()
        add_scope_tags()
        validate()
    end

    # Has this resource already been finished?
    def finished?
        defined?(@finished) and @finished
    end

    def initialize(options)
        # Set all of the options we can.
        options.each do |option, value|
            if respond_to?(option.to_s + "=")
                send(option.to_s + "=", value)
                options.delete(option)
            end
        end

        unless self.scope
            raise ArgumentError, "Resources require a scope"
        end
        @source ||= scope.source

        options = symbolize_options(options)

        # Set up our reference.
        if type = options[:type] and title = options[:title]
            options.delete(:type)
            options.delete(:title)
        else
            raise ArgumentError, "Resources require a type and title"
        end

        @ref = Reference.new(:type => type, :title => title, :scope => self.scope)

        @params = {}

        # Define all of the parameters
        if params = options[:params]
            options.delete(:params)
            params.each do |param|
                set_parameter(param)
            end
        end

        # Throw an exception if we've got any arguments left to set.
        unless options.empty?
            raise ArgumentError, "Resources do not accept %s" % options.keys.collect { |k| k.to_s }.join(", ")
        end

        tag(@ref.type)
        tag(@ref.title) if valid_tag?(@ref.title.to_s)
    end

    # Is this resource modeling an isomorphic resource type?
    def isomorphic?
        if builtin?
            return @ref.builtintype.isomorphic?
        else
            return true
        end
    end

    # Merge an override resource in.  This will throw exceptions if
    # any overrides aren't allowed.
    def merge(resource)
        # Test the resource scope, to make sure the resource is even allowed
        # to override.
        unless self.source.object_id == resource.source.object_id || resource.source.child_of?(self.source)
            raise Puppet::ParseError.new("Only subclasses can override parameters", resource.line, resource.file)
        end
        # Some of these might fail, but they'll fail in the way we want.
        resource.params.each do |name, param|
            override_parameter(param)
        end
    end

    # Modify this resource in the Rails database.  Poor design, yo.
    def modify_rails(db_resource)
        args = rails_args
        args.each do |param, value|
            db_resource[param] = value unless db_resource[param] == value
        end

        # Handle file specially
        if (self.file and  
            (!db_resource.file or db_resource.file != self.file))
            db_resource.file = self.file
        end
        
        updated_params = @params.reject { |name, param| param.value == :undef }.inject({}) do |hash, ary|
            hash[ary[0].to_s] = ary[1]
            hash
        end
        
        db_resource.ar_hash_merge(db_resource.get_params_hash(), updated_params,
                                  :create => Proc.new { |name, parameter|
                                      parameter.to_rails(db_resource)
                                  }, :delete => Proc.new { |values|
                                      values.each { |value| Puppet::Rails::ParamValue.delete(value['id']) }
                                  }, :modify => Proc.new { |db, mem|
                                      mem.modify_rails_values(db)
                                  })
        
        updated_tags = tags.inject({}) { |hash, tag| 
            hash[tag] = tag
            hash
        }

        db_resource.ar_hash_merge(db_resource.get_tag_hash(), 
                                  updated_tags,
                                  :create => Proc.new { |name, tag|
                                      db_resource.add_resource_tag(name)
                                  }, :delete => Proc.new { |tag|
                                      Puppet::Rails::ResourceTag.delete(tag['id'])
                                  }, :modify => Proc.new { |db, mem|
                                      # nothing here
                                  })
    end

    # Return the resource name, or the title if no name
    # was specified.
    def name
        unless defined? @name
            @name = self[:name] || self.title
        end
        @name
    end

    # This *significantly* reduces the number of calls to Puppet.[].
    def paramcheck?
        unless defined? @@paramcheck
            @@paramcheck = Puppet[:paramcheck]
        end
        @@paramcheck
    end

    # A temporary occasion, until I get paths in the scopes figured out.
    def path
        to_s
    end

    # Return the short version of our name.
    def ref
        @ref.to_s
    end

    # Define a parameter in our resource.
    def set_parameter(param, value = nil)
        if value
            param = Puppet::Parser::Resource::Param.new(
                :name => param, :value => value, :source => self.source
            )
        elsif ! param.is_a?(Puppet::Parser::Resource::Param)
            raise ArgumentError, "Must pass a parameter or all necessary values"
        end

        # And store it in our parameter hash.
        @params[param.name] = param
    end

    def to_hash
        @params.inject({}) do |hash, ary|
            param = ary[1]
            # Skip "undef" values.
            if param.value != :undef
                hash[param.name] = param.value
            end
            hash
        end
    end

    # Turn our parser resource into a Rails resource.  
    def to_rails(host)
        args = rails_args

        db_resource = host.resources.build(args)

        # Handle file specially
        db_resource.file = self.file

        db_resource.save

        @params.each { |name, param|
            next if param.value == :undef
            param.to_rails(db_resource)
        }
        
        tags.each { |tag| db_resource.add_resource_tag(tag) }

        return db_resource
    end

    # Create a Puppet::Resource instance from this parser resource.
    # We plan, at some point, on not needing to do this conversion, but
    # it's sufficient for now.
    def to_resource
        result = Puppet::Resource.new(type, title)

        to_hash.each do |p, v|
            if v.is_a?(Puppet::Parser::Resource::Reference)
                v = Puppet::Resource::Reference.new(v.type, v.title)
            elsif v.is_a?(Array)
                # flatten resource references arrays
                if v.flatten.find { |av| av.is_a?(Puppet::Parser::Resource::Reference) }
                    v = v.flatten
                end
                v = v.collect do |av|
                    if av.is_a?(Puppet::Parser::Resource::Reference)
                        av = Puppet::Resource::Reference.new(av.type, av.title)
                    end
                    av
                end
            end

            # If the value is an array with only one value, then
            # convert it to a single value.  This is largely so that
            # the database interaction doesn't have to worry about
            # whether it returns an array or a string.
            result[p] = if v.is_a?(Array) and v.length == 1
                              v[0]
                          else
                              v
                          end
        end

        result.file = self.file
        result.line = self.line
        result.tag(*self.tags)

        return result
    end

    def to_s
        self.ref
    end

    # Translate our object to a transportable object.
    def to_trans
        return nil if virtual?

        return to_resource.to_trans
    end

    # Convert this resource to a RAL resource.  We hackishly go via the
    # transportable stuff.
    def to_ral
        to_resource.to_ral
    end
    
    private

    # Add default values from our definition.
    def add_defaults
        scope.lookupdefaults(self.type).each do |name, param|
            unless @params.include?(name)
                self.debug "Adding default for %s" % name

                @params[name] = param.dup
            end
        end
    end

    # Add any metaparams defined in our scope. This actually adds any metaparams
    # from any parent scope, and there's currently no way to turn that off.
    def add_metaparams
        Puppet::Type.eachmetaparam do |name|
            # Skip metaparams that we already have defined, unless they're relationship metaparams.
            # LAK:NOTE Relationship metaparams get treated specially -- we stack them, instead of
            # overriding.
            next if @params[name] and not self.class.relationship_parameter?(name)
            next if @params[name] and @params[name].value == :undef

            # Skip metaparams for which we get no value.
            next unless val = scope.lookupvar(name.to_s, false) and val != :undefined

            # The default case: just set the value
            set_parameter(name, val) and next unless @params[name]

            # For relationship params, though, join the values (a la #446).
            @params[name].value = [@params[name].value, val].flatten
        end
    end

    def add_scope_tags
        if scope_resource = scope.resource
            tag(*scope_resource.tags)
        end
    end

    # Accept a parameter from an override.
    def override_parameter(param)
        # This can happen if the override is defining a new parameter, rather
        # than replacing an existing one.
        (@params[param.name] = param and return) unless current = @params[param.name]

        # The parameter is already set.  Fail if they're not allowed to override it.
        unless param.source.child_of?(current.source)
            puts caller if Puppet[:trace]
            msg = "Parameter '%s' is already set on %s" % [param.name, self.to_s]
            if current.source.to_s != ""
                msg += " by %s" % current.source
            end
            if current.file or current.line
                fields = []
                fields << current.file if current.file
                fields << current.line.to_s if current.line
                msg += " at %s" % fields.join(":")
            end
            msg += "; cannot redefine"
            raise Puppet::ParseError.new(msg, param.line, param.file)
        end

        # If we've gotten this far, we're allowed to override.

        # Merge with previous value, if the parameter was generated with the +> syntax.
        # It's important that we use the new param instance here, not the old one,
        # so that the source is registered correctly for later overrides.
        param.value = [current.value, param.value].flatten if param.add

        @params[param.name] = param
    end

    # Verify that all passed parameters are valid.  This throws an error if
    #  there's a problem, so we don't have to worry about the return value.
    def paramcheck(param)
        param = param.to_s
        # Now make sure it's a valid argument to our class.  These checks
        # are organized in order of commonhood -- most types, it's a valid 
        # argument and paramcheck is enabled.
        if @ref.typeclass.validattr?(param)
            true
        elsif %w{name title}.include?(param) # always allow these
            true
        elsif paramcheck?
            self.fail Puppet::ParseError, "Invalid parameter '%s' for type '%s'" %
                    [param, @ref.type]
        end
    end

    def rails_args
        return [:type, :title, :line, :exported].inject({}) do |hash, param|
            # 'type' isn't a valid column name, so we have to use another name.
            to = (param == :type) ? :restype : param
            if value = self.send(param)
                hash[to] = value
            end
            hash
        end
    end

    # Make sure the resource's parameters are all valid for the type.
    def validate
        @params.each do |name, param|
            # Make sure it's a valid parameter.
            paramcheck(name)
        end
    end
end