summaryrefslogtreecommitdiffstats
path: root/lib/puppet/config.rb
blob: 680c9f2fb36f7b4a062722ee98fff7c0a49d2d2e (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
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
require 'puppet'
require 'sync'
require 'puppet/transportable'

module Puppet
# The class for handling configuration files.
class Config
    include Enumerable

    @@sync = Sync.new


    # Retrieve a config value
    def [](param)
        param = symbolize(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 = symbolize(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 = symbolize(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
        }
        @used = []
    end

    # This is mostly just used for testing.
    def clearused
        @used = []
    end

    def symbolize(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 = symbolize(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 = {}

        @created = []
    end

    # Make a directory with the appropriate user, group, and mode
    def mkdir(default)
        obj = nil
        unless obj = @config[default]
            raise ArgumentError, "Unknown default %s" % default
        end

        unless obj.is_a? CFile
            raise ArgumentError, "Default %s is not a file" % default
        end

        Puppet::Util.asuser(obj.owner, obj.group) do
            mode = obj.mode || 0750
            Dir.mkdir(obj.value, mode)
        end
    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

                    # Do some annoying skullduggery here.  This is so that
                    # the group can be set in the config file.  The problem
                    # is that we're using the word 'group' twice, which is
                    # confusing.
                    if var == :group and section == Puppet.name and @config.include?(:group)
                        @config[:group].value = value
                    end
                    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 = symbolize(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(hash)
        value = hash[:value] || hash[:default]
        klass = nil
        if hash[:section]
            hash[:section] = symbolize(hash[:section])
        end
        case value
        when true, false, "true", "false":
            klass = CBoolean
        when /^\$/, /^\//:
            klass = CFile
        when String, Integer, Float: # nothing
            klass = CElement
        else
            raise Puppet::Error, "Invalid value '%s' for %s" % [value.inspect, hash[:name]]
        end
        element = klass.new(hash)
        element.parent = self

        @order << element.name

        return element
    end

    # Iterate across all of the objects in a given section.
    def persection(section)
        section = symbolize(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 = nil, includefiles = true)
        done ||= Hash.new { |hash, key| hash[key] = {} }
        objects = []
        persection(section) { |obj|
            if @config[:mkusers] and @config[:mkusers].value
                [: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]
                            unless newobj.state(:ensure)
                                newobj[:ensure] = "present"
                            end
                            newobj.tag(section)
                        else
                            newobj = TransObject.new(name, type.to_s)
                            newobj.tags = ["puppet", "configuration", section]
                            newobj[:ensure] = "present"
                            done[type][name] = newobj
                            objects << newobj
                        end
                    end
                }
            end

            if obj.respond_to? :to_transportable
                next if obj.value =~ /^\/dev/
                transobjects = obj.to_transportable
                transobjects = [transobjects] unless transobjects.is_a? Array
                transobjects.each do |trans|
                    # transportable could return nil
                    next unless trans
                    unless done[:file].include? trans.name
                        @created << trans.name
                        objects << trans
                        done[:file][trans.name] = trans
                    end
                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 = symbolize(section)
        defs.each { |name, hash|
            if hash.is_a? Array
                tmp = hash
                hash = {}
                [:default, :desc].zip(tmp).each { |p,v| hash[p] = v }
            end
            name = symbolize(name)
            hash[:name] = name
            hash[:section] = section
            name = hash[:name]
            if @config.include?(name)
                raise Puppet::Error, "Parameter %s is already defined" % name
            end
            @config[name] = newelement(hash)
        }
    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 reuse
        return unless defined? @used
        @@sync.synchronize do # yay, thread-safe
            @used.each do |section|
                @used.delete(section)
                self.use(section)
            end
        end
    end

    # Create the necessary objects to use a section.  This is idempotent;
    # you can 'use' a section as many times as you want.
    def use(*sections)
        @@sync.synchronize do # yay, thread-safe
            unless defined? @used
                @used = []
            end

            runners = sections.collect { |s|
                symbolize(s)
            }.find_all { |s|
                ! @used.include? s
            }
            return if runners.empty?

            bucket = Puppet::TransBucket.new
            bucket.type = "puppetconfig"
            bucket.top = true

            # Create a hash to keep track of what we've done so far.
            @done = Hash.new { |hash, key| hash[key] = {} }
            runners.each do |section|
                bucket.push section_to_transportable(section, @done, false)
            end

            objects = bucket.to_type

            objects.finalize
            trans = objects.evaluate
            trans.evaluate

            # Remove is a recursive process, so it's sufficient to just call
            # it on the component.
            objects.remove(true)

            objects = nil

            runners.each { |s| @used << s }
        end
    end

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

    # Open a file with the appropriate user, group, and mode
    def write(default, *args)
        obj = nil
        unless obj = @config[default]
            raise ArgumentError, "Unknown default %s" % default
        end

        unless obj.is_a? CFile
            raise ArgumentError, "Default %s is not a file" % default
        end

        chown = nil
        if Process.uid == 0
            chown = [obj.owner, obj.group]
        else
            chown = [nil, nil]
        end
        Puppet::Util.asuser(*chown) do
            mode = obj.mode || 0640

            if args.empty?
                args << "w"
            end

            args << mode

            File.open(obj.value, *args) do |file|
                yield file
            end
        end
    end

    # Open a non-default file under a default dir with the appropriate user,
    # group, and mode
    def writesub(default, file, *args)
        obj = nil
        unless obj = @config[default]
            raise ArgumentError, "Unknown default %s" % default
        end

        unless obj.is_a? CFile
            raise ArgumentError, "Default %s is not a file" % default
        end

        chown = nil
        if Process.uid == 0
            chown = [obj.owner, obj.group]
        else
            chown = [nil, nil]
        end

        Puppet::Util.asuser(*chown) do
            mode = obj.mode || 0640
            if args.empty?
                args << "w"
            end

            args << mode

            # Update the umask to make non-executable files
            Puppet::Util.withumask(File.umask ^ 0111) do
                File.open(file, *args) do |file|
                    yield file
                end
            end
        end
    end

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

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

        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

        def desc=(value)
            @desc = value.gsub(/^\s*/, '')
        end

        # Create the new element.  Pretty much just sets the name.
        def initialize(args = {})
            args.each do |param, value|
                method = param.to_s + "="
                unless self.respond_to? method
                    raise ArgumentError, "%s does not accept %s" % [self.class, param]
                end

                self.send(method, value)
            end
        end

        def iscreated
            @iscreated = true
        end

        def iscreated?
            if defined? @iscreated
                return @iscreated
            else
                return false
            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 retval.is_a? String
                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.
    class CFile < CElement
        attr_writer :owner, :group
        attr_accessor :mode, :create

        def group
            if defined? @group
                return convert(@group)
            else
                return nil
            end
        end

        def owner
            if defined? @owner
                return convert(@owner)
            else
                return nil
            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.
        # FIXME There's no dependency system in place right now; if you use
        # a section that requires another section, there's nothing done to
        # correct that for you, at the moment.
        def to_transportable
            type = self.type
            return nil unless type
            path = self.value.split(File::SEPARATOR)
            path.shift # remove the leading nil

            objects = []
            obj = Puppet::TransObject.new(self.value, "file")

            # Only create directories, or files that are specifically marked to
            # create.
            if type == :directory or self.create
                obj[:ensure] = type
            end
            [:mode].each { |var|
                if value = self.send(var)
                    obj[var] = "%o" % value
                end
            }

            # Only chown or chgrp when root
            if Process.uid == 0
                [:group, :owner].each { |var|
                    if value = self.send(var)
                        obj[var] = value
                    end
                }
            end

            # And set the loglevel to debug for everything
            obj[:loglevel] = "debug"

            if self.section
                obj.tags = ["puppet", "configuration", self.section]
            end
            objects << obj
            objects
        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.
    class CBoolean < CElement
        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$