Module: Puppet::Util
- Extended by:
- POSIX
- Included in:
- Puppet, Application, Application, Configurer, Configurer, Indirector::Queue, Network::AuthStore::Declaration, Network::Client, Network::Handler, Network::Handler::Master, Network::XMLRPCClient, Network::XMLRPCServer, Node::Exec, Parameter, Parameter, Parser::Compiler, Parser::Functions, Parser::Resource, Parser::Resource::Param, Parser::TemplateWrapper, Provider, Provider, Provider::Confine, Rails::Host, Resource::Catalog::Compiler, Transaction, Type, Type, Autoload, ClassGen, Diff, FileParsing, FileParsing::FileRecord, InstanceLoader, Log, Log, ProviderFeatures::ProviderFeature, Reference, Storage
- Defined in:
- lib/puppet/util.rb,
lib/puppet/util/run_mode.rb,
lib/puppet/util/command_line.rb,
lib/puppet/util/execution_stub.rb
Defined Under Namespace
Modules: 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 Classes: Autoload, CommandLine, ExecutionStub, Feature, FileType, LoadedFile, Log, Metric, Pidlock, Reference, ResourceTemplate, RunMode, Settings, Storage
Constant Summary collapse
- @@sync_objects =
{}.extend MonitorMixin
Class Method Summary collapse
- .activerecord_version ⇒ Object
- .benchmark(*args) ⇒ Object
-
.chuser ⇒ Object
Change the process to a different user.
-
.classproxy(klass, objmethod, *methods) ⇒ Object
Proxy a bunch of methods to another object.
-
.execute(command, arguments = {:failonfail => true, :combine => true}) ⇒ Object
Execute the desired command, and return the status and output.
-
.logmethods(klass, useself = true) ⇒ Object
Create instance methods for each of the log levels.
- .memory ⇒ Object
-
.proxy(klass, objmethod, *methods) ⇒ Object
Proxy a bunch of methods to another object.
-
.recmkdir(dir, mode = 0755) ⇒ Object
XXX this should all be done using puppet objects, not using normal mkdir.
- .secure_open(file, must_be_w, &block) ⇒ Object
- .symbolize(value) ⇒ Object
- .symbolizehash(hash) ⇒ Object
- .symbolizehash!(hash) ⇒ Object
- .synchronize_on(x, type) ⇒ Object
-
.thinmark ⇒ Object
Just benchmark, with no logging.
- .which(bin) ⇒ Object
-
.withumask(mask) ⇒ Object
Execute a given chunk of code with a new umask.
Instance Method Summary collapse
- #execfail(command, exception) ⇒ Object
-
#execpipe(command, failonfail = true) ⇒ Object
Execute the provided command in a pipe, yielding the pipe object.
-
#threadlock(resource, type = Sync::EX) ⇒ Object
Create an exclusive lock.
Methods included from POSIX
get_posix_field, gid, idfield, methodbyid, methodbyname, search_posix_field, uid
Class Method Details
.activerecord_version ⇒ Object
24 25 26 27 28 29 30 |
# File 'lib/puppet/util.rb', line 24 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
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 |
# File 'lib/puppet/util.rb', line 168 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 |
.chuser ⇒ Object
Change the process to a different user
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 |
# File 'lib/puppet/util.rb', line 48 def self.chuser if group = Puppet[:group] group = self.gid(group) raise Puppet::Error, "No such group #{Puppet[:group]}" unless group unless Puppet::Util::SUIDManager.gid == group begin Puppet::Util::SUIDManager.egid = group Puppet::Util::SUIDManager.gid = group 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 end if user = Puppet[:user] user = self.uid(user) raise Puppet::Error, "No such user #{Puppet[:user]}" unless user unless Puppet::Util::SUIDManager.uid == user begin Puppet::Util::SUIDManager.initgroups(user) Puppet::Util::SUIDManager.uid = user Puppet::Util::SUIDManager.euid = user rescue => detail $stderr.puts "Could not change to user #{user}: #{detail}" exit(74) end end end end |
.classproxy(klass, objmethod, *methods) ⇒ Object
Proxy a bunch of methods to another object.
113 114 115 116 117 118 119 120 121 122 |
# File 'lib/puppet/util.rb', line 113 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.
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 |
# File 'lib/puppet/util.rb', line 248 def execute(command, arguments = {:failonfail => true, :combine => true}) if command.is_a?(Array) command = command.flatten.collect { |i| i.to_s } str = command.join(" ") else # We require an array here so we know where we're incorrectly # using a string instead of an array. Once everything is # switched to an array, we might relax this requirement. raise ArgumentError, "Must pass an array to execute()" end if respond_to? :debug debug "Executing '#{str}'" else Puppet.debug "Executing '#{str}'" end arguments[:uid] = Puppet::Util::SUIDManager.convert_xid(:uid, arguments[:uid]) if arguments[:uid] arguments[:gid] = Puppet::Util::SUIDManager.convert_xid(:gid, arguments[:gid]) if arguments[:gid] if execution_stub = Puppet::Util::ExecutionStub.current_value return execution_stub.call(command, arguments) end @@os ||= Facter.value(:operatingsystem) output = nil child_pid, child_status = nil # There are problems with read blocking with badly behaved children # read.partialread doesn't seem to capture either stdout or stderr # We hack around this using a temporary file # The idea here is to avoid IO#read whenever possible. output_file="/dev/null" error_file="/dev/null" if ! arguments[:squelch] require "tempfile" output_file = Tempfile.new("puppet") error_file=output_file if arguments[:combine] end if Puppet.features.posix? oldverb = $VERBOSE $VERBOSE = nil child_pid = Kernel.fork $VERBOSE = oldverb if child_pid # Parent process executes this child_status = (Process.waitpid2(child_pid)[1]).to_i >> 8 else # Child process executes this Process.setsid begin if arguments[:stdinfile] $stdin.reopen(arguments[:stdinfile]) else $stdin.reopen("/dev/null") end $stdout.reopen(output_file) $stderr.reopen(error_file) 3.upto(256){|fd| IO::new(fd).close rescue nil} if arguments[:gid] Process.egid = arguments[:gid] Process.gid = arguments[:gid] unless @@os == "Darwin" end if arguments[:uid] Process.euid = arguments[:uid] Process.uid = arguments[:uid] unless @@os == "Darwin" end ENV['LANG'] = ENV['LC_ALL'] = ENV['LC_MESSAGES'] = ENV['LANGUAGE'] = 'C' if command.is_a?(Array) Kernel.exec(*command) else Kernel.exec(command) end rescue => detail puts detail.to_s exit!(1) end end elsif Puppet.features.microsoft_windows? command = command.collect {|part| '"' + part.gsub(/"/, '\\"') + '"'}.join(" ") if command.is_a?(Array) Puppet.debug "Creating process '#{command}'" processinfo = Process.create( :command_line => command ) child_status = (Process.waitpid2(child_pid)[1]).to_i >> 8 end # read output in if required if ! arguments[:squelch] # Make sure the file's actually there. This is # basically a race condition, and is probably a horrible # way to handle it, but, well, oh well. unless FileTest.exists?(output_file.path) Puppet.warning "sleeping" sleep 0.5 unless FileTest.exists?(output_file.path) Puppet.warning "sleeping 2" sleep 1 unless FileTest.exists?(output_file.path) Puppet.warning "Could not get output" output = "" end end end unless output # We have to explicitly open here, so that it reopens # after the child writes. output = output_file.open.read # The 'true' causes the file to get unlinked right away. output_file.close(true) end end if arguments[:failonfail] unless child_status == 0 raise ExecutionFailure, "Execution of '#{str}' returned #{child_status}: #{output}" end end output 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.
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 |
# File 'lib/puppet/util.rb', line 86 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 |
.memory ⇒ Object
384 385 386 387 388 389 390 391 392 393 |
# File 'lib/puppet/util.rb', line 384 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 |
.proxy(klass, objmethod, *methods) ⇒ Object
Proxy a bunch of methods to another object.
125 126 127 128 129 130 131 132 133 |
# File 'lib/puppet/util.rb', line 125 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
137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 |
# File 'lib/puppet/util.rb', line 137 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
437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 |
# File 'lib/puppet/util.rb', line 437 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
395 396 397 398 399 400 401 |
# File 'lib/puppet/util.rb', line 395 def symbolize(value) if value.respond_to? :intern value.intern else value end end |
.symbolizehash(hash) ⇒ Object
403 404 405 406 407 408 409 410 411 412 |
# File 'lib/puppet/util.rb', line 403 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
414 415 416 417 418 419 420 421 422 423 |
# File 'lib/puppet/util.rb', line 414 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
33 34 35 36 37 38 39 40 41 42 43 44 45 |
# File 'lib/puppet/util.rb', line 33 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 |
.thinmark ⇒ Object
Just benchmark, with no logging.
427 428 429 430 431 432 433 |
# File 'lib/puppet/util.rb', line 427 def thinmark seconds = Benchmark.realtime { yield } seconds end |
.which(bin) ⇒ Object
202 203 204 205 206 207 208 209 210 211 212 |
# File 'lib/puppet/util.rb', line 202 def which(bin) if bin =~ /^\// return bin if FileTest.file? bin and FileTest.executable? bin else ENV['PATH'].split(File::PATH_SEPARATOR).each do |dir| dest=File.join(dir, bin) return dest if FileTest.file? dest and FileTest.executable? dest end end nil end |
Instance Method Details
#execfail(command, exception) ⇒ Object
236 237 238 239 240 241 |
# File 'lib/puppet/util.rb', line 236 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.
216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 |
# File 'lib/puppet/util.rb', line 216 def execpipe(command, failonfail = true) if respond_to? :debug debug "Executing '#{command}'" else Puppet.debug "Executing '#{command}'" end output = open("| #{command} 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.
375 376 377 |
# File 'lib/puppet/util.rb', line 375 def threadlock(resource, type = Sync::EX) Puppet::Util.synchronize_on(resource,type) { yield } end |