summaryrefslogtreecommitdiffstats
path: root/lib/puppet/util/filetype.rb
blob: bbc837e7588e8bea4a2960bf07139695b4c3cb5a (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
# Basic classes for reading, writing, and emptying files.  Not much
# to see here.
class Puppet::Util::FileType
    attr_accessor :loaded, :path, :synced

    class << self
        attr_accessor :name
        include Puppet::Util::ClassGen
    end

    # Create a new filetype.
    def self.newfiletype(name, &block)
        @filetypes ||= {}

        klass = genclass(name,
            :block => block,
            :prefix => "FileType",
            :hash => @filetypes
        )

        # Rename the read and write methods, so that we're sure they
        # maintain the stats.
        klass.class_eval do
            # Rename the read method
            define_method(:real_read, instance_method(:read))
            define_method(:read) do
                begin
                    val = real_read()
                    @loaded = Time.now
                    if val
                        return val.gsub(/# HEADER.*\n/,'')
                    else
                        return ""
                    end
                rescue Puppet::Error => detail
                    raise
                rescue => detail
                    if Puppet[:trace]
                        puts detail.backtrace
                    end
                    raise Puppet::Error, "%s could not read %s: %s" %
                        [self.class, @path, detail]
                end
            end

            # And then the write method
            define_method(:real_write, instance_method(:write))
            define_method(:write) do |text|
                begin
                    val = real_write(text)
                    @synced = Time.now
                    return val
                rescue Puppet::Error => detail
                    raise
                rescue => detail
                    if Puppet[:debug]
                        puts detail.backtrace
                    end
                    raise Puppet::Error, "%s could not write %s: %s" %
                        [self.class, @path, detail]
                end
            end
        end
    end

    def self.filetype(type)
        @filetypes[type]
    end

    # Back the file up before replacing it.
    def backup
        bucket.backup(@path) if FileTest.exists?(@path)
    end

    # Pick or create a filebucket to use.
    def bucket
        filebucket = Puppet::Type.type(:filebucket)
        (filebucket["puppet"] || filebucket.mkdefaultbucket).bucket
    end

    def initialize(path)
        raise ArgumentError.new("Path is nil") if path.nil?
        @path = path
    end

    # Operate on plain files.
    newfiletype(:flat) do
        # Read the file.
        def read
            if File.exists?(@path)
                File.read(@path)
            else
                return nil
            end
        end

        # Remove the file.
        def remove
            if File.exists?(@path)
                File.unlink(@path)
            end
        end

        # Overwrite the file.
        def write(text)
            backup()
            File.open(@path, "w") { |f| f.print text; f.flush }
        end
    end

    # Operate on plain files.
    newfiletype(:ram) do
        @@tabs = {}

        def self.clear
            @@tabs.clear
        end

        def initialize(path)
            super
            @@tabs[@path] ||= ""
        end

        # Read the file.
        def read
            Puppet.info "Reading %s from RAM" % @path
            @@tabs[@path]
        end

        # Remove the file.
        def remove
            Puppet.info "Removing %s from RAM" % @path
            @@tabs[@path] = ""
        end

        # Overwrite the file.
        def write(text)
            Puppet.info "Writing %s to RAM" % @path
            @@tabs[@path] = text
        end
    end

    # Handle Linux-style cron tabs.
    newfiletype(:crontab) do
        def initialize(user)
            self.path = user
        end

        def path=(user)
            begin
                @uid = Puppet::Util.uid(user)
            rescue Puppet::Error => detail
                raise Puppet::Error, "Could not retrieve user %s" % user
            end

            # XXX We have to have the user name, not the uid, because some
            # systems *cough*linux*cough* require it that way
            @path = user
        end

        # Read a specific @path's cron tab.
        def read
            %x{#{cmdbase()} -l 2>/dev/null}
        end

        # Remove a specific @path's cron tab.
        def remove
            if %w{Darwin FreeBSD}.include?(Facter.value("operatingsystem"))
                %x{/bin/echo yes | #{cmdbase()} -r 2>/dev/null}
            else
                %x{#{cmdbase()} -r 2>/dev/null}
            end
        end

        # Overwrite a specific @path's cron tab; must be passed the @path name
        # and the text with which to create the cron tab.
        def write(text)
            IO.popen("#{cmdbase()} -", "w") { |p|
                p.print text
            }
        end

        private

        # Only add the -u flag when the @path is different.  Fedora apparently
        # does not think I should be allowed to set the @path to my own user name
        def cmdbase
            cmd = nil
            if @uid == Puppet::Util::SUIDManager.uid
                return "crontab"
            else
                return "crontab -u #{@path}"
            end
        end
    end

    # SunOS has completely different cron commands; this class implements
    # its versions.
    newfiletype(:suntab) do
        # Read a specific @path's cron tab.
        def read
            begin
                output = Puppet::Util.execute(%w{crontab -l}, :uid => @path)
                return "" if output.include?("can't open your crontab")
                return output
            rescue
                # If there's a failure, treat it like an empty file.
                return ""
            end
        end

        # Remove a specific @path's cron tab.
        def remove
            begin
                Puppet::Util.execute(%w{crontab -r}, :uid => @path)
            rescue => detail
                raise Puppet::Error, "Could not remove crontab for %s: %s" % [@path, detail]
            end
        end

        # Overwrite a specific @path's cron tab; must be passed the @path name
        # and the text with which to create the cron tab.
        def write(text)
            puts text
            require "tempfile"
            output_file = Tempfile.new("puppet")
            fh = output_file.open
            fh.print text
            fh.close

            # We have to chown the stupid file to the user.
            File.chown(Puppet::Util.uid(@path), nil, output_file.path)

            begin
                Puppet::Util.execute(["crontab", output_file.path], :uid => @path)
            rescue => detail
                raise Puppet::Error, "Could not write crontab for %s: %s" % [@path, detail]
            end
            output_file.delete
        end
    end

    # Treat netinfo tables as a single file, just for simplicity of certain
    # types
    newfiletype(:netinfo) do
        class << self
            attr_accessor :format
        end
        def read
            %x{nidump -r /#{@path} /}
        end

        # This really only makes sense for cron tabs.
        def remove
            %x{nireport / /#{@path} name}.split("\n").each do |name|
                newname = name.gsub(/\//, '\/').sub(/\s+$/, '')
                output = %x{niutil -destroy / '/#{@path}/#{newname}'}

                unless $? == 0
                    raise Puppet::Error, "Could not remove %s from %s" %
                        [name, @path]
                end
            end
        end

        # Convert our table to an array of hashes.  This only works for
        # handling one table at a time.
        def to_array(text = nil)
            unless text
                text = read
            end

            hash = nil

            # Initialize it with the first record
            records = []
            text.split("\n").each do |line|
                next if line =~ /^[{}]$/ # Skip the wrapping lines
                next if line =~ /"name" = \( "#{@path}" \)/ # Skip the table name
                next if line =~ /CHILDREN = \(/ # Skip this header
                next if line =~ /^  \)/ # and its closer

                # Now we should have nothing but records, wrapped in braces

                case line
                when /^\s+\{/: hash = {}
                when /^\s+\}/: records << hash
                when /\s+"(\w+)" = \( (.+) \)/
                    field = $1
                    values = $2

                    # Always use an array
                    hash[field] = []

                    values.split(/, /).each do |value|
                        if value =~ /^"(.*)"$/
                            hash[field] << $1
                        else
                            raise ArgumentError, "Could not match value %s" % value
                        end
                    end
                else    
                    raise ArgumentError, "Could not match line %s" % line
                end
            end

            records
        end

        def write(text)
            text.gsub!(/^#.*\n/,'')
            text.gsub!(/^$/,'')
            if text == "" or text == "\n"
                self.remove
                return
            end
            unless format = self.class.format
                raise Puppe::DevError, "You must define the NetInfo format to inport"
            end
            IO.popen("niload -d #{format} . 1>/dev/null 2>/dev/null", "w") { |p|
                p.print text
            }

            unless $? == 0
                raise ArgumentError, "Failed to write %s" % @path
            end
        end
    end
end