Module: Puppet::Util

Defined Under Namespace

Modules: ADSI, Backups, CacheAccumulator, Cacher, Checksums, ClassGen, CollectionMerger, ConstantInflector, Diff, Docs, Errors, Execution, FileLocking, FileParsing, Graph, IniConfig, InlineDocs, InstanceLoader, Ldap, LogPaths, Logging, MethodHelper, NagiosMaker, POSIX, Package, ProviderFeatures, Pson, Queue, RDoc, ReferenceSerializer, SELinux, SUIDManager, SubclassLoader, Tagging, Warnings, Windows Classes: Autoload, CommandLine, ExecutionStub, Feature, FileType, LoadedFile, Log, Metric, NetworkDevice, Pidlock, Reference, ResourceTemplate, RunMode, Settings, Storage

Constant Summary collapse

@@sync_objects =
{}.extend MonitorMixin

Class Method Summary collapse

Instance Method Summary collapse

Methods included from POSIX

get_posix_field, gid, idfield, methodbyid, methodbyname, search_posix_field, uid

Class Method Details

.absolute_path?(path, platform = nil) ⇒ Boolean

Determine in a platform-specific way whether a path is absolute. This defaults to the local platform if none is specified.



212
213
214
215
216
217
218
219
220
221
222
223
224
# File 'lib/puppet/util.rb', line 212

def absolute_path?(path, platform=nil)
  # Escape once for the string literal, and once for the regex.
  slash = '[\\\\/]'
  name = '[^\\\\/]+'
  regexes = {
    :windows => %r!^(([A-Z]:#{slash})|(#{slash}#{slash}#{name}#{slash}#{name})|(#{slash}#{slash}\?#{slash}#{name}))!i,
    :posix   => %r!^/!,
  }
  require 'puppet'
  platform ||= Puppet.features.microsoft_windows? ? :windows : :posix

  !! (path =~ regexes[platform])
end

.activerecord_versionObject



27
28
29
30
31
32
33
# File 'lib/puppet/util.rb', line 27

def self.activerecord_version
  if (defined?(::ActiveRecord) and defined?(::ActiveRecord::VERSION) and defined?(::ActiveRecord::VERSION::MAJOR) and defined?(::ActiveRecord::VERSION::MINOR))
    ([::ActiveRecord::VERSION::MAJOR, ::ActiveRecord::VERSION::MINOR].join('.').to_f)
  else
    0
  end
end

.benchmark(*args) ⇒ Object

Raises:



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
# File 'lib/puppet/util.rb', line 155

def benchmark(*args)
  msg = args.pop
  level = args.pop
  object = nil

  if args.empty?
    if respond_to?(level)
      object = self
    else
      object = Puppet
    end
  else
    object = args.pop
  end

  raise Puppet::DevError, "Failed to provide level to :benchmark" unless level

  unless level == :none or object.respond_to? level
    raise Puppet::DevError, "Benchmarked object does not respond to #{level}"
  end

  # Only benchmark if our log level is high enough
  if level != :none and Puppet::Util::Log.sendlevel?(level)
    result = nil
    seconds = Benchmark.realtime {
      yield
    }
    object.send(level, msg + (" in %0.2f seconds" % seconds))
    return seconds
  else
    yield
  end
end

.binread(file) ⇒ Object

Because IO#binread is only available in 1.9



507
508
509
# File 'lib/puppet/util.rb', line 507

def binread(file)
  File.open(file, 'rb') { |f| f.read }
end

.chuserObject

Change the process to a different user



50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
# File 'lib/puppet/util.rb', line 50

def self.chuser
  if group = Puppet[:group]
    begin
      Puppet::Util::SUIDManager.change_group(group, true)
    rescue => detail
      Puppet.warning "could not change to group #{group.inspect}: #{detail}"
      $stderr.puts "could not change to group #{group.inspect}"

      # Don't exit on failed group changes, since it's
      # not fatal
      #exit(74)
    end
  end

  if user = Puppet[:user]
    begin
      Puppet::Util::SUIDManager.change_user(user, true)
    rescue => detail
      $stderr.puts "Could not change to user #{user}: #{detail}"
      exit(74)
    end
  end
end

.classproxy(klass, objmethod, *methods) ⇒ Object

Proxy a bunch of methods to another object.



100
101
102
103
104
105
106
107
108
109
# File 'lib/puppet/util.rb', line 100

def self.classproxy(klass, objmethod, *methods)
  classobj = class << klass; self; end
  methods.each do |method|
    classobj.send(:define_method, method) do |*args|
      obj = self.send(objmethod)

      obj.send(method, *args)
    end
  end
end

.execute(command, arguments = {:failonfail => true, :combine => true}) ⇒ Object

Execute the desired command, and return the status and output. def execute(command, failonfail = true, uid = nil, gid = nil) :combine sets whether or not to combine stdout/stderr in the output :stdinfile sets a file that can be used for stdin. Passing a string for stdin is not currently supported.



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
# File 'lib/puppet/util.rb', line 346

def execute(command, arguments = {:failonfail => true, :combine => true})
  if command.is_a?(Array)
    command = command.flatten.map(&:to_s)
    str = command.join(" ")
  elsif command.is_a?(String)
    str = command
  end

  if respond_to? :debug
    debug "Executing '#{str}'"
  else
    Puppet.debug "Executing '#{str}'"
  end

  null_file = Puppet.features.microsoft_windows? ? 'NUL' : '/dev/null'

  stdin = File.open(arguments[:stdinfile] || null_file, 'r')
  stdout = arguments[:squelch] ? File.open(null_file, 'w') : Tempfile.new('puppet')
  stderr = arguments[:combine] ? stdout : File.open(null_file, 'w')

  exec_args = [command, arguments, stdin, stdout, stderr]

  if execution_stub = Puppet::Util::ExecutionStub.current_value
    return execution_stub.call(*exec_args)
  elsif Puppet.features.posix?
    child_pid = execute_posix(*exec_args)
    exit_status = Process.waitpid2(child_pid).last.exitstatus
  elsif Puppet.features.microsoft_windows?
    child_pid = execute_windows(*exec_args)
    exit_status = Process.waitpid2(child_pid).last
    # $CHILD_STATUS is not set when calling win32/process Process.create
    # and since it's read-only, we can't set it. But we can execute a
    # a shell that simply returns the desired exit status, which has the
    # desired effect.
    %x{#{ENV['COMSPEC']} /c exit #{exit_status}}
  end

  [stdin, stdout, stderr].each {|io| io.close rescue nil}

  # read output in if required
  unless arguments[:squelch]
    output = wait_for_output(stdout)
    Puppet.warning "Could not get output" unless output
  end

  if arguments[:failonfail] and exit_status != 0
    raise ExecutionFailure, "Execution of '#{str}' returned #{exit_status}: #{output}"
  end

  output
end

.execute_posix(command, arguments, stdin, stdout, stderr) ⇒ Object



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
# File 'lib/puppet/util.rb', line 301

def execute_posix(command, arguments, stdin, stdout, stderr)
  child_pid = Kernel.fork do
    # We can't just call Array(command), and rely on it returning
    # things like ['foo'], when passed ['foo'], because
    # Array(command) will call command.to_a internally, which when
    # given a string can end up doing Very Bad Things(TM), such as
    # turning "/tmp/foo;\r\n /bin/echo" into ["/tmp/foo;\r\n", " /bin/echo"]
    command = [command].flatten
    Process.setsid
    begin
      $stdin.reopen(stdin)
      $stdout.reopen(stdout)
      $stderr.reopen(stderr)

      3.upto(256){|fd| IO::new(fd).close rescue nil}

      Puppet::Util::SUIDManager.change_group(arguments[:gid], true) if arguments[:gid]
      Puppet::Util::SUIDManager.change_user(arguments[:uid], true)  if arguments[:uid]

      ENV['LANG'] = ENV['LC_ALL'] = ENV['LC_MESSAGES'] = ENV['LANGUAGE'] = 'C'
      Kernel.exec(*command)
    rescue => detail
      puts detail.to_s
      exit!(1)
    end
  end
  child_pid
end

.execute_windows(command, arguments, stdin, stdout, stderr) ⇒ Object



331
332
333
334
335
336
337
338
# File 'lib/puppet/util.rb', line 331

def execute_windows(command, arguments, stdin, stdout, stderr)
  command = command.map do |part|
    part.include?(' ') ? %Q["#{part.gsub(/"/, '\"')}"] : part
  end.join(" ") if command.is_a?(Array)

  process_info = Process.create( :command_line => command, :startup_info => {:stdin => stdin, :stdout => stdout, :stderr => stderr} )
  process_info.process_id
end

.logmethods(klass, useself = true) ⇒ Object

Create instance methods for each of the log levels. This allows the messages to be a little richer. Most classes will be calling this method.



77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
# File 'lib/puppet/util.rb', line 77

def self.logmethods(klass, useself = true)
  Puppet::Util::Log.eachlevel { |level|
    klass.send(:define_method, level, proc { |args|
      args = args.join(" ") if args.is_a?(Array)
      if useself

        Puppet::Util::Log.create(
          :level => level,
          :source => self,
          :message => args
        )
      else

        Puppet::Util::Log.create(
          :level => level,
          :message => args
        )
      end
    })
  }
end

.memoryObject



431
432
433
434
435
436
437
438
439
440
# File 'lib/puppet/util.rb', line 431

def memory
  unless defined?(@pmap)
    @pmap = which('pmap')
  end
  if @pmap
    %x{#{@pmap} #{Process.pid}| grep total}.chomp.sub(/^\s*total\s+/, '').sub(/K$/, '').to_i
  else
    0
  end
end

.path_to_uri(path) ⇒ Object

Convert a path to a file URI



228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
# File 'lib/puppet/util.rb', line 228

def path_to_uri(path)
  return unless path

  params = { :scheme => 'file' }

  if Puppet.features.microsoft_windows?
    path = path.gsub(/\\/, '/')

    if unc = /^\/\/([^\/]+)(\/[^\/]+)/.match(path)
      params[:host] = unc[1]
      path = unc[2]
    elsif path =~ /^[a-z]:\//i
      path = '/' + path
    end
  end

  params[:path] = URI.escape(path)

  begin
    URI::Generic.build(params)
  rescue => detail
    raise Puppet::Error, "Failed to convert '#{path}' to URI: #{detail}"
  end
end

.proxy(klass, objmethod, *methods) ⇒ Object

Proxy a bunch of methods to another object.



112
113
114
115
116
117
118
119
120
# File 'lib/puppet/util.rb', line 112

def self.proxy(klass, objmethod, *methods)
  methods.each do |method|
    klass.send(:define_method, method) do |*args|
      obj = self.send(objmethod)

      obj.send(method, *args)
    end
  end
end

.recmkdir(dir, mode = 0755) ⇒ Object

XXX this should all be done using puppet objects, not using normal mkdir



124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
# File 'lib/puppet/util.rb', line 124

def self.recmkdir(dir,mode = 0755)
  if FileTest.exist?(dir)
    return false
  else
    tmp = dir.sub(/^\//,'')
    path = [File::SEPARATOR]
    tmp.split(File::SEPARATOR).each { |dir|
      path.push dir
      if ! FileTest.exist?(File.join(path))
        Dir.mkdir(File.join(path), mode)
      elsif FileTest.directory?(File.join(path))
        next
      else FileTest.exist?(File.join(path))
        raise "Cannot create #{dir}: basedir #{File.join(path)} is a file"
      end
    }
    return true
  end
end

.secure_open(file, must_be_w, &block) ⇒ Object

Raises:



484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
# File 'lib/puppet/util.rb', line 484

def secure_open(file,must_be_w,&block)
  raise Puppet::DevError,"secure_open only works with mode 'w'" unless must_be_w == 'w'
  raise Puppet::DevError,"secure_open only requires a block"    unless block_given?
  Puppet.warning "#{file} was a symlink to #{File.readlink(file)}" if File.symlink?(file)
  if File.exists?(file) or File.symlink?(file)
    wait = File.symlink?(file) ? 5.0 : 0.1
    File.delete(file)
    sleep wait # give it a chance to reappear, just in case someone is actively trying something.
  end
  begin
    File.open(file,File::CREAT|File::EXCL|File::TRUNC|File::WRONLY,&block)
  rescue Errno::EEXIST
    desc = File.symlink?(file) ? "symlink to #{File.readlink(file)}" : File.stat(file).ftype
    puts "Warning: #{file} was apparently created by another process (as"
    puts "a #{desc}) as soon as it was deleted by this process.  Someone may be trying"
    puts "to do something objectionable (such as tricking you into overwriting system"
    puts "files if you are running as root)."
    raise
  end
end

.symbolize(value) ⇒ Object



442
443
444
445
446
447
448
# File 'lib/puppet/util.rb', line 442

def symbolize(value)
  if value.respond_to? :intern
    value.intern
  else
    value
  end
end

.symbolizehash(hash) ⇒ Object



450
451
452
453
454
455
456
457
458
459
# File 'lib/puppet/util.rb', line 450

def symbolizehash(hash)
  newhash = {}
  hash.each do |name, val|
    if name.is_a? String
      newhash[name.intern] = val
    else
      newhash[name] = val
    end
  end
end

.symbolizehash!(hash) ⇒ Object



461
462
463
464
465
466
467
468
469
470
# File 'lib/puppet/util.rb', line 461

def symbolizehash!(hash)
  hash.each do |name, val|
    if name.is_a? String
      hash[name.intern] = val
      hash.delete(name)
    end
  end

  hash
end

.synchronize_on(x, type) ⇒ Object



35
36
37
38
39
40
41
42
43
44
45
46
47
# File 'lib/puppet/util.rb', line 35

def self.synchronize_on(x,type)
  sync_object,users = 0,1
  begin
    @@sync_objects.synchronize {
      (@@sync_objects[x] ||= [Sync.new,0])[users] += 1
    }
    @@sync_objects[x][sync_object].synchronize(type) { yield }
  ensure
    @@sync_objects.synchronize {
      @@sync_objects.delete(x) unless (@@sync_objects[x][users] -= 1) > 0
    }
  end
end

.thinmarkObject

Just benchmark, with no logging.



474
475
476
477
478
479
480
# File 'lib/puppet/util.rb', line 474

def thinmark
  seconds = Benchmark.realtime {
    yield
  }

  seconds
end

.uri_to_path(uri) ⇒ Object

Get the path component of a URI



255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
# File 'lib/puppet/util.rb', line 255

def uri_to_path(uri)
  return unless uri.is_a?(URI)

  path = URI.unescape(uri.path)

  if Puppet.features.microsoft_windows? and uri.scheme == 'file'
    if uri.host
      path = "//#{uri.host}" + path # UNC
    else
      path.sub!(/^\//, '')
    end
  end

  path
end

.wait_for_output(stdout) ⇒ Object



400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
# File 'lib/puppet/util.rb', line 400

def wait_for_output(stdout)
  # Make sure the file's actually been written.  This is basically a race
  # condition, and is probably a horrible way to handle it, but, well, oh
  # well.
  2.times do |try|
    if File.exists?(stdout.path)
      output = stdout.open.read

      stdout.close(true)

      return output
    else
      time_to_sleep = try / 2.0
      Puppet.warning "Waiting for output; will sleep #{time_to_sleep} seconds"
      sleep(time_to_sleep)
    end
  end
  nil
end

.which(bin) ⇒ Object



189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
# File 'lib/puppet/util.rb', line 189

def which(bin)
  if absolute_path?(bin)
    return bin if FileTest.file? bin and FileTest.executable? bin
  else
    ENV['PATH'].split(File::PATH_SEPARATOR).each do |dir|
      dest = File.expand_path(File.join(dir, bin))
      if Puppet.features.microsoft_windows? && File.extname(dest).empty?
        exts = ENV['PATHEXT']
        exts = exts ? exts.split(File::PATH_SEPARATOR) : %w[.COM .EXE .BAT .CMD]
        exts.each do |ext|
          destext = File.expand_path(dest + ext)
          return destext if FileTest.file? destext and FileTest.executable? destext
        end
      end
      return dest if FileTest.file? dest and FileTest.executable? dest
    end
  end
  nil
end

.withumask(mask) ⇒ Object

Execute a given chunk of code with a new umask.



145
146
147
148
149
150
151
152
153
# File 'lib/puppet/util.rb', line 145

def self.withumask(mask)
  cur = File.umask(mask)

  begin
    yield
  ensure
    File.umask(cur)
  end
end

Instance Method Details

#execfail(command, exception) ⇒ Object



294
295
296
297
298
299
# File 'lib/puppet/util.rb', line 294

def execfail(command, exception)
    output = execute(command)
    return output
rescue ExecutionFailure
    raise exception, output
end

#execpipe(command, failonfail = true) ⇒ Object

Execute the provided command in a pipe, yielding the pipe object.



273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
# File 'lib/puppet/util.rb', line 273

def execpipe(command, failonfail = true)
  if respond_to? :debug
    debug "Executing '#{command}'"
  else
    Puppet.debug "Executing '#{command}'"
  end

  command_str = command.respond_to?(:join) ? command.join('') : command
  output = open("| #{command_str} 2>&1") do |pipe|
    yield pipe
  end

  if failonfail
    unless $CHILD_STATUS == 0
      raise ExecutionFailure, output
    end
  end

  output
end

#threadlock(resource, type = Sync::EX) ⇒ Object

Create an exclusive lock.



422
423
424
# File 'lib/puppet/util.rb', line 422

def threadlock(resource, type = Sync::EX)
  Puppet::Util.synchronize_on(resource,type) { yield }
end