summaryrefslogtreecommitdiffstats
path: root/lib/puppet/config.rb
blob: aeaa218ce65f35b9d98ff2aa94b530ef49905967 (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
module Puppet
# The class for handling configuration files.
class Config
    include Enumerable

    # Retrieve a config value
    def [](param)
        param = convert(param)
        if @config.include?(param)
            if @config[param]
                val = @config[param].value
                return val
            end
        else
            raise ArgumentError, "Invalid argument %s" % param
        end
    end

    # Set a config value.  This doesn't set the defaults, it sets the value itself.
    def []=(param, value)
        param = convert(param)
        unless @config.include?(param)
            raise Puppet::Error, "Unknown configuration parameter %s" % param.inspect
        end
        unless @order.include?(param)
            @order << param
        end
        @config[param].value = value
    end

    # A simplified equality operator.
    def ==(other)
        self.each { |myname, myobj|
            unless other[myname] == myobj.value
                return false
            end
        }

        return true
    end

    # Generate the list of valid arguments, in a format that GetoptLong can
    # understand, and add them to the passed option list.
    def addargs(options)
        require 'getoptlong'
        # Add all of the config parameters as valid options.
        self.each { |param, obj|
            if self.boolean?(param)
                options << ["--#{param}", GetoptLong::NO_ARGUMENT]
                options << ["--no-#{param}", GetoptLong::NO_ARGUMENT]
            else
                options << ["--#{param}", GetoptLong::REQUIRED_ARGUMENT]
            end
        }

        return options
    end

    # Turn the config into a transaction and apply it
    def apply
        trans = self.to_transportable
        begin
            comp = trans.to_type
            trans = comp.evaluate
            trans.evaluate
            comp.remove
        rescue => detail
                puts detail.backtrace
            Puppet.err "Could not configure myself: %s" % detail
        end
    end

    # Is our parameter a boolean parameter?
    def boolean?(param)
        param = convert(param)
        if @config.include?(param) and @config[param].kind_of? CBoolean
            return true
        else
            return false
        end
    end

    # Remove all set values.
    def clear
        @config.each { |name, obj|
            obj.clear
        }
    end

    def convert(param)
        case param
        when String: return param.intern
        when Symbol: return param
        else
            raise ArgumentError, "Invalid param type %s" % param.class
        end
    end

    def each
        @order.each { |name|
            if @config.include?(name)
                yield name, @config[name]
            else
                raise Puppet::DevError, "%s is in the order but does not exist" % name
            end
        }
    end

    # Iterate over each section name.
    def eachsection
        yielded = []
        @order.each { |name|
            if @config.include?(name)
                section = @config[name].section
                unless yielded.include? section
                    yield section
                    yielded << section
                end
            else
                raise Puppet::DevError, "%s is in the order but does not exist" % name
            end
        }
    end

    # Return an object by name.
    def element(param)
        param = convert(param)
        @config[param]
    end

    # Handle a command-line argument.
    def handlearg(opt, value = nil)
        if value == "true"
            value = true
        end
        if value == "false"
            value = false
        end
        str = opt.sub(/^--/,'')
        bool = true
        newstr = str.sub(/^no-/, '')
        if newstr != str
            str = newstr
            bool = false
        end
        if self.valid?(str)
            if self.boolean?(str)
                self[str] = bool
            else
                self[str] = value
            end

            # Mark that this was set on the cli, so it's not overridden if the config
            # gets reread.
            @config[str.intern].setbycli = true
        else
            raise ArgumentError, "Invalid argument %s" % opt
        end
    end

    # Create a new config object
    def initialize
        @order = []
        @config = {}
    end

    # Return all of the parameters associated with a given section.
    def params(section)
        section = section.intern if section.is_a? String
        @config.find_all { |name, obj|
            obj.section == section
        }.collect { |name, obj|
            name
        }
    end

    # Parse a configuration file.
    def parse(file)
        text = nil
        @file = file

        begin
            text = File.read(file)
        rescue Errno::ENOENT
            raise Puppet::Error, "No such file %s" % file
        rescue Errno::EACCES
            raise Puppet::Error, "Permission denied to file %s" % file
        end

        # Store it for later, in a way that we can test and such.
        @file = Puppet::ParsedFile.new(file)

        @values = Hash.new { |names, name|
            names[name] = {}
        }

        section = "puppet"
        metas = %w{owner group mode}
        values = Hash.new { |hash, key| hash[key] = {} }
        text.split(/\n/).each { |line|
            case line
            when /^\[(\w+)\]$/: section = $1 # Section names
            when /^\s*#/: next # Skip comments
            when /^\s*$/: next # Skip blanks
            when /^\s*(\w+)\s*=\s*(.+)$/: # settings
                var = $1.intern
                value = $2

                # Mmm, "special" attributes
                if metas.include?(var.to_s)
                    unless values.include?(section)
                        values[section] = {}
                    end
                    values[section][var.to_s] = value
                    next
                end

                # Don't override set parameters, since the file is parsed
                # after cli arguments are handled.
                unless @config.include?(var) and @config[var].setbycli
                    Puppet.debug "%s: Setting %s to '%s'" % [section, var, value]
                    self[var] = value
                end
                @config[var].section = section

                metas.each { |meta|
                    if values[section][meta]
                        if @config[var].respond_to?(meta + "=")
                            @config[var].send(meta + "=", values[section][meta])
                        end
                    end
                }
            else
                raise Puppet::Error, "Could not match line %s" % line
            end
        }
    end

    # Create a new element.  The value is passed in because it's used to determine
    # what kind of element we're creating, but the value itself might be either
    # a default or a value, so we can't actually assign it.
    def newelement(param, desc, value)
        param = convert(param)
        mod = nil
        case value
        when true, false, "true", "false":
            mod = CBoolean
        when /^\$/, /^\//:
            mod = CFile
        when String, Integer, Float: # nothing
        else
            raise Puppet::Error, "Invalid value '%s' for %s" % [value, param]
        end
        element = CElement.new(param, desc)
        element.parent = self
        if mod
            element.extend(mod)
        end

        @order << param

        return element
    end

    # Iterate across all of the objects in a given section.
    def persection(section)
        self.each { |name, obj|
            if obj.section == section
                yield obj
            end
        }
    end

    # Get a list of objects per section
    def sectionlist
        sectionlist = []
        self.each { |name, obj|
            section = obj.section || "puppet"
            sections[section] ||= []
            unless sectionlist.include?(section)
                sectionlist << section
            end
            sections[section] << obj
        }

        return sectionlist, sections
    end

    # Convert a single section into transportable objects.
    def section_to_transportable(section, done)
        objects = []
        persection(section) { |obj|
            [:owner, :group].each { |attr|
                type = nil
                if attr == :owner
                    type = :user
                else
                    type = attr
                end
                if obj.respond_to? attr and name = obj.send(attr)
                    # Skip owners and groups we've already done, but tag them with
                    # our section if necessary
                    if done[type].include?(name)
                        tags = done[type][name].tags
                        unless tags.include?(section)
                            done[type][name].tags = tags << section
                        end
                    elsif newobj = Puppet::Type.type(type)[name]
                        newobj.tag(section)
                    else
                        newobj = TransObject.new(name, type.to_s)
                        newobj[:ensure] = "present"
                        done[type][name] = newobj
                        objects << newobj
                    end
                end
            }

            if obj.respond_to? :to_transportable
                unless done[:file].include? obj.name
                    trans = obj.to_transportable
                    # transportable could return nil
                    next unless trans
                    objects << trans
                    done[:file][obj.name] = obj
                end
            end
        }

        bucket = Puppet::TransBucket.new
        bucket.type = section
        bucket.push(*objects)
        bucket.keyword = "class"

        return bucket
    end

    # Set a bunch of defaults in a given section.  The sections are actually pretty
    # pointless, but they help break things up a bit, anyway.
    def setdefaults(section, *defs)
        section = section.intern unless section.is_a? Symbol
        #hash.each { |param, value|
        defs.each { |param, value, desc|
            param = convert(param)
            if @config.include?(param) and @config[param].default
                raise Puppet::Error, "Default %s is already defined" % param
            end
            unless @config.include?(param)
                @config[param] = newelement(param, desc, value)
            end
            @config[param].default = value
            @config[param].section = section
        }
    end

    # Convert our list of objects into a component that can be applied.
    def to_component
        transport = self.to_transportable
        return transport.to_type
    end

    # Convert our list of objects into a configuration file.
    def to_config
        str = %{The configuration file for #{Puppet.name}.  Note that this file
is likely to have unused configuration parameters in it; any parameter that's
valid anywhere in Puppet can be in any config file, even if it's not used.

Every section can specify three special parameters: owner, group, and mode.
These parameters affect the required permissions of any files specified after
their specification.  Puppet will sometimes use these parameters to check its
own configured state, so they can be used to make Puppet a bit more self-managing.

Note also that the section names are entirely for human-level organizational
purposes; they don't provide separate namespaces.  All parameters are in a
single namespace.

Generated on #{Time.now}.

}.gsub(/^/, "# ")

        eachsection do |section|
            str += "[#{section}]\n"
            persection(section) do |obj|
                str += obj.to_config + "\n"
            end
        end

        return str
    end

    # Convert our configuration into a list of transportable objects.
    def to_transportable
        done = Hash.new { |hash, key|
            hash[key] = {}
        }

        topbucket = Puppet::TransBucket.new
        if defined? @file and @file
            topbucket.name = @file
        else
            topbucket.name = "configtop"
        end
        topbucket.type = "puppetconfig"
        topbucket.top = true

        # Now iterate over each section
        eachsection do |section|
            topbucket.push section_to_transportable(section, done)
        end

        topbucket
    end

    # Convert to a parseable manifest
    def to_manifest
        transport = self.to_transportable

        manifest = transport.to_manifest + "\n"
        eachsection { |section|
            manifest += "include #{section}\n"
        }

        return manifest
    end

    def valid?(param)
        param = convert(param)
        @config.has_key?(param)
    end

    # The base element type.
    class CElement
        attr_accessor :name, :section, :default, :parent, :desc, :setbycli

        # Unset any set value.
        def clear
            @value = nil
        end

        # Create the new element.  Pretty much just sets the name.
        def initialize(name, desc, value = nil)
            @name = name
            @desc = desc.gsub(/^\s*/, '')
            if value
                @value = value
            end
        end

        def set?
            if defined? @value and ! @value.nil?
                return true
            else
                return false
            end
        end

        # Convert the object to a config statement.
        def to_config
            str = @desc.gsub(/^/, "# ") + "\n"

            # Add in a statement about the default.
            if defined? @default and @default
                str += "# The default value is '%s'.\n" % @default
            end

            line = "%s = %s" % [@name, self.value]

            # If the value has not been overridden, then print it out commented
            # and unconverted, so it's clear that that's the default and how it
            # works.
            if defined? @value and ! @value.nil?
                line = "%s = %s" % [@name, self.value]
            else
                line = "# %s = %s" % [@name, @default]
            end

            str += line + "\n"

            str.gsub(/^/, "    ")
        end

        # Retrieves the value, or if it's not set, retrieves the default.
        def value
            retval = nil
            if defined? @value and ! @value.nil?
                retval = @value
            elsif defined? @default
                retval = @default
            else
                return nil
            end

            if respond_to?(:convert)
                return convert(retval)
            else
                return retval
            end
        end

        # Set the value.
        def value=(value)
            if respond_to?(:validate)
                validate(value)
            end
            if respond_to?(:munge)
                @value = munge(value)
            else
                @value = value
            end
        end
    end

    # A file.
    module CFile
        attr_accessor :owner, :group, :mode

        def convert(value)
            return value unless value
            return value unless value.is_a? String
            if value =~ /\$(\w+)/
                parent = $1
                if pval = @parent[parent]
                    newval = value.sub(/\$#{parent}/, pval)
                    return File.join(newval.split("/"))
                else
                    raise Puppet::DevError, "Could not find value for %s" % parent
                end
            else
                return value
            end
        end

        # Set the type appropriately.  Yep, a hack.  This supports either naming
        # the variable 'dir', or adding a slash at the end.
        def munge(value)
            if value.to_s =~ /\/$/
                @type = :directory
                return value.sub(/\/$/, '')
            end
            return value
        end

        # Return the appropriate type.
        def type
            value = self.value
            if @name.to_s =~ /dir/
                return :directory
            elsif value.to_s =~ /\/$/
                return :directory
            elsif value.is_a? String
                return :file
            else
                return nil
            end
        end

        # Convert the object to a TransObject instance.
        def to_transportable
            type = self.type
            return nil unless type
            obj = Puppet::TransObject.new(self.value, "file")
            obj[:ensure] = type
            [:owner, :group, :mode].each { |var|
                if value = self.send(var)
                    obj[var] = value
                end
            }
            if self.section
                obj.tags = ["puppet", "configuration", self.section]
            end
            obj
        end

        # Make sure any provided variables look up to something.
        def validate(value)
            return true unless value.is_a? String
            value.scan(/\$(\w+)/) { |name|
                name = name[0]
                unless @parent[name]
                    raise Puppet::Error, "'%s' is unset" % name
                end
            }
        end
    end

    # A simple boolean.
    module CBoolean
        def munge(value)
            case value
            when true, "true": return true
            when false, "false": return false
            else
                raise Puppet::Error, "Invalid value '%s' for %s" %
                    [value.inspect, @name]
            end
        end
    end
end
end

# $Id$