Class: Bolt::Executor
- Inherits:
-
Object
- Object
- Bolt::Executor
- Defined in:
- lib/bolt/executor.rb
Defined Under Namespace
Classes: TimeoutError
Instance Attribute Summary collapse
-
#future ⇒ Object
readonly
Returns the value of attribute future.
-
#noop ⇒ Object
readonly
Returns the value of attribute noop.
-
#run_as ⇒ Object
Returns the value of attribute run_as.
-
#transports ⇒ Object
readonly
Returns the value of attribute transports.
Instance Method Summary collapse
-
#await_results(promises) ⇒ Object
Create a ResultSet from the results of all promises.
-
#batch_execute(targets, &block) ⇒ Object
Execute the given block on a list of nodes in parallel, one thread per “batch”.
-
#create_future(plan_id:, scope: nil, name: nil, &block) ⇒ Object
Call into FiberExecutor to avoid this class getting overloaded while also minimizing the Puppet lookups needed from plan functions.
- #download_file(targets, source, destination, options = {}, position = []) ⇒ Object
- #get_current_future(fiber:) ⇒ Object
- #get_current_plan_id(fiber:) ⇒ Object
- #get_futures_for_plan(plan_id:) ⇒ Object
- #in_parallel? ⇒ Boolean
-
#initialize(concurrency = 1, analytics = Bolt::Analytics::NoopClient.new, noop = false, modified_concurrency = false, future = {}) ⇒ Executor
constructor
A new instance of Executor.
- #log_action(description, targets) ⇒ Object
- #log_plan(plan_name) ⇒ Object
- #plan_complete? ⇒ Boolean
- #prompt(prompt, options) ⇒ Object
- #publish_event(event) ⇒ Object
-
#queue_execute(targets) ⇒ Object
Starts executing the given block on a list of nodes in parallel, one thread per “batch”.
- #report_apply(statement_count, resource_counts) ⇒ Object
- #report_bundled_content(mode, name) ⇒ Object
- #report_file_source(plan_function, source) ⇒ Object
- #report_function_call(function) ⇒ Object
- #report_noop_mode(noop) ⇒ Object
- #report_yaml_plan(plan) ⇒ Object
- #round_robin ⇒ Object
- #run_command(targets, command, options = {}, position = []) ⇒ Object
-
#run_in_thread ⇒ Object
Execute a plan function concurrently.
- #run_plan(scope, plan, params) ⇒ Object
- #run_script(targets, script, arguments, options = {}, position = []) ⇒ Object
- #run_task(targets, task, arguments, options = {}, position = [], log_level = :info) ⇒ Object
- #run_task_with(target_mapping, task, options = {}, position = []) ⇒ Object
- #shutdown ⇒ Object
- #subscribe(subscriber, types = nil) ⇒ Object
- #transport(transport) ⇒ Object
- #unsubscribe(subscriber, types = nil) ⇒ Object
- #upload_file(targets, source, destination, options = {}, position = []) ⇒ Object
- #wait(futures, **opts) ⇒ Object
- #wait_until_available(targets, description: 'wait until available', wait_time: 120, retry_interval: 1) ⇒ Object
- #with_node_logging(description, batch, log_level = :info) ⇒ Object
- #without_default_logging ⇒ Object
Constructor Details
#initialize(concurrency = 1, analytics = Bolt::Analytics::NoopClient.new, noop = false, modified_concurrency = false, future = {}) ⇒ Executor
Returns a new instance of Executor.
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 |
# File 'lib/bolt/executor.rb', line 41 def initialize(concurrency = 1, analytics = Bolt::Analytics::NoopClient.new, noop = false, modified_concurrency = false, future = {}) # lazy-load expensive gem code require 'concurrent' @analytics = analytics @logger = Bolt::Logger.logger(self) @transports = Bolt::TRANSPORTS.each_with_object({}) do |(key, val), coll| coll[key.to_s] = if key == :remote Concurrent::Delay.new do val.new(self) end else Concurrent::Delay.new do val.new end end end @reported_transports = Set.new @subscribers = {} @publisher = Concurrent::SingleThreadExecutor.new @publisher.post { Thread.current[:name] = 'event-publisher' } @noop = noop @run_as = nil @future = future @pool = if concurrency > 0 Concurrent::ThreadPoolExecutor.new(name: 'exec', max_threads: concurrency) else Concurrent.global_immediate_executor end @logger.debug { "Started with #{concurrency} max thread(s)" } @concurrency = concurrency @warn_concurrency = modified_concurrency @fiber_executor = Bolt::FiberExecutor.new end |
Instance Attribute Details
#future ⇒ Object (readonly)
Returns the value of attribute future.
38 39 40 |
# File 'lib/bolt/executor.rb', line 38 def future @future end |
#noop ⇒ Object (readonly)
Returns the value of attribute noop.
38 39 40 |
# File 'lib/bolt/executor.rb', line 38 def noop @noop end |
#run_as ⇒ Object
Returns the value of attribute run_as.
39 40 41 |
# File 'lib/bolt/executor.rb', line 39 def run_as @run_as end |
#transports ⇒ Object (readonly)
Returns the value of attribute transports.
38 39 40 |
# File 'lib/bolt/executor.rb', line 38 def transports @transports end |
Instance Method Details
#await_results(promises) ⇒ Object
Create a ResultSet from the results of all promises.
184 185 186 |
# File 'lib/bolt/executor.rb', line 184 def await_results(promises) ResultSet.new(promises.map(&:value)) end |
#batch_execute(targets, &block) ⇒ Object
Execute the given block on a list of nodes in parallel, one thread per “batch”.
This is the main driver of execution on a list of targets. It first groups targets by transport, then divides each group into batches as defined by the transport. Each batch, along with the corresponding transport, is yielded to the block in turn and the results all collected into a single ResultSet.
195 196 197 198 |
# File 'lib/bolt/executor.rb', line 195 def batch_execute(targets, &block) promises = queue_execute(targets, &block) await_results(promises) end |
#create_future(plan_id:, scope: nil, name: nil, &block) ⇒ Object
Call into FiberExecutor to avoid this class getting overloaded while also minimizing the Puppet lookups needed from plan functions
390 391 392 |
# File 'lib/bolt/executor.rb', line 390 def create_future(plan_id:, scope: nil, name: nil, &block) @fiber_executor.create_future(scope: scope, name: name, plan_id: plan_id, &block) end |
#download_file(targets, source, destination, options = {}, position = []) ⇒ Object
361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 |
# File 'lib/bolt/executor.rb', line 361 def download_file(targets, source, destination, = {}, position = []) description = .fetch(:description, "file download from #{source} to #{destination}") begin FileUtils.mkdir_p(destination) rescue Errno::EEXIST => e = "#{e.message}; unable to create destination directory #{destination}" raise Bolt::Error.new(, 'bolt/file-exist-error') end log_action(description, targets) do [:run_as] = run_as if run_as && !.key?(:run_as) batch_execute(targets) do |transport, batch| with_node_logging("Downloading file #{source} to #{destination}", batch) do transport.batch_download(batch, source, destination, , position, &method(:publish_event)) end end end end |
#get_current_future(fiber:) ⇒ Object
394 395 396 |
# File 'lib/bolt/executor.rb', line 394 def get_current_future(fiber:) @fiber_executor.get_current_future(fiber: fiber) end |
#get_current_plan_id(fiber:) ⇒ Object
398 399 400 |
# File 'lib/bolt/executor.rb', line 398 def get_current_plan_id(fiber:) @fiber_executor.get_current_plan_id(fiber: fiber) end |
#get_futures_for_plan(plan_id:) ⇒ Object
418 419 420 |
# File 'lib/bolt/executor.rb', line 418 def get_futures_for_plan(plan_id:) @fiber_executor.get_futures_for_plan(plan_id: plan_id) end |
#in_parallel? ⇒ Boolean
410 411 412 |
# File 'lib/bolt/executor.rb', line 410 def in_parallel? @fiber_executor.in_parallel? end |
#log_action(description, targets) ⇒ Object
200 201 202 203 204 205 206 207 208 209 210 |
# File 'lib/bolt/executor.rb', line 200 def log_action(description, targets) publish_event(type: :step_start, description: description, targets: targets) start_time = Time.now results = yield duration = Time.now - start_time publish_event(type: :step_finish, description: description, result: results, duration: duration) results end |
#log_plan(plan_name) ⇒ Object
212 213 214 215 216 217 218 219 220 221 222 223 224 225 |
# File 'lib/bolt/executor.rb', line 212 def log_plan(plan_name) publish_event(type: :plan_start, plan: plan_name) start_time = Time.now results = nil begin results = yield ensure duration = Time.now - start_time publish_event(type: :plan_finish, plan: plan_name, duration: duration) end results end |
#plan_complete? ⇒ Boolean
402 403 404 |
# File 'lib/bolt/executor.rb', line 402 def plan_complete? @fiber_executor.plan_complete? end |
#prompt(prompt, options) ⇒ Object
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 |
# File 'lib/bolt/executor.rb', line 488 def prompt(prompt, ) unless $stdin.tty? return [:default] if [:default] raise Bolt::Error.new('STDIN is not a tty, unable to prompt', 'bolt/no-tty-error') end @prompting = true if [:default] && ![:sensitive] $stderr.print("#{prompt} [#{options[:default]}]: ") else $stderr.print("#{prompt}: ") end value = if [:sensitive] $stdin.noecho(&:gets).to_s.chomp else $stdin.gets.to_s.chomp end @prompting = false $stderr.puts if [:sensitive] value = [:default] if value.empty? value end |
#publish_event(event) ⇒ Object
104 105 106 107 108 109 110 111 112 113 114 115 116 |
# File 'lib/bolt/executor.rb', line 104 def publish_event(event) @subscribers.each do |subscriber, types| # If types isn't set or if the subscriber is subscribed to # that type of event, publish the event next unless types.nil? || types.include?(event[:type]) @publisher.post(subscriber) do |sub| # Wait for user to input to prompt before printing anything sleep(0.1) while @prompting sub.handle_event(event) end end end |
#queue_execute(targets) ⇒ Object
Starts executing the given block on a list of nodes in parallel, one thread per “batch”.
This is the main driver of execution on a list of targets. It first groups targets by transport, then divides each group into batches as defined by the transport. Yields each batch, along with the corresponding transport, to the block in turn and returns an array of result promises.
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 |
# File 'lib/bolt/executor.rb', line 129 def queue_execute(targets) if @warn_concurrency && targets.length > @concurrency @warn_concurrency = false msg = "The ulimit is low, which might cause file limit issues. Default concurrency has been set to " \ "'#{@concurrency}' to mitigate those issues, which might cause Bolt to run slow. " \ "Disable this warning by configuring ulimit using 'ulimit -n <limit>' in your shell " \ "configuration, or by configuring Bolt's concurrency. " \ "See https://puppet.com/docs/bolt/latest/bolt_known_issues.html for details." Bolt::Logger.warn("low_ulimit", msg) end targets.group_by(&:transport).flat_map do |protocol, protocol_targets| transport = transport(protocol) report_transport(transport, protocol_targets.count) transport.batches(protocol_targets).flat_map do |batch| batch_promises = Array(batch).each_with_object({}) do |target, h| h[target] = Concurrent::Promise.new(executor: :immediate) end # Pass this argument through to avoid retaining a reference to a # local variable that will change on the next iteration of the loop. @pool.post(batch_promises) do |result_promises| Thread.current[:name] ||= Thread.current.name results = yield transport, batch Array(results).each do |result| result_promises[result.target].set(result) end # NotImplementedError can be thrown if the transport is not implemented improperly rescue StandardError, NotImplementedError => e result_promises.each do |target, promise| # If an exception happens while running, the result won't be logged # by the CLI. Log a warning, as this is probably a problem with the transport. # If batch_* commands are used from the Base transport, then exceptions # normally shouldn't reach here. @logger.warn(e) promise.set(Bolt::Result.from_exception(target, e)) end ensure # Make absolutely sure every promise gets a result to avoid a # deadlock. Use whatever exception is causing this block to # execute, or generate one if we somehow got here without an # exception and some promise is still missing a result. result_promises.each do |target, promise| next if promise.fulfilled? error = $ERROR_INFO || Bolt::Error.new("No result was returned for #{target.uri}", "puppetlabs.bolt/missing-result-error") promise.set(Bolt::Result.from_exception(target, error)) end end batch_promises.values end end end |
#report_apply(statement_count, resource_counts) ⇒ Object
252 253 254 255 256 257 258 259 260 261 262 |
# File 'lib/bolt/executor.rb', line 252 def report_apply(statement_count, resource_counts) data = { statement_count: statement_count } unless resource_counts.empty? sum = resource_counts.inject(0) { |accum, i| accum + i } # Intentionally rounded to an integer. High precision isn't useful. data[:resource_mean] = sum / resource_counts.length end @analytics&.event('Apply', 'ast', **data) end |
#report_bundled_content(mode, name) ⇒ Object
239 240 241 |
# File 'lib/bolt/executor.rb', line 239 def report_bundled_content(mode, name) @analytics.report_bundled_content(mode, name) end |
#report_file_source(plan_function, source) ⇒ Object
243 244 245 246 |
# File 'lib/bolt/executor.rb', line 243 def report_file_source(plan_function, source) label = Pathname.new(source).absolute? ? 'absolute' : 'module' @analytics&.event('Plan', plan_function, label: label) end |
#report_function_call(function) ⇒ Object
235 236 237 |
# File 'lib/bolt/executor.rb', line 235 def report_function_call(function) @analytics&.event('Plan', 'call_function', label: function) end |
#report_noop_mode(noop) ⇒ Object
248 249 250 |
# File 'lib/bolt/executor.rb', line 248 def report_noop_mode(noop) @analytics&.event('Task', 'noop', label: (!!noop).to_s) end |
#report_yaml_plan(plan) ⇒ Object
264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 |
# File 'lib/bolt/executor.rb', line 264 def report_yaml_plan(plan) steps = plan.steps.count return_type = case plan.return when Bolt::PAL::YamlPlan::EvaluableString 'expression' when nil nil else 'value' end @analytics&.event('Plan', 'yaml', plan_steps: steps, return_type: return_type) rescue StandardError => e @logger.trace { "Failed to submit analytics event: #{e.message}" } end |
#round_robin ⇒ Object
406 407 408 |
# File 'lib/bolt/executor.rb', line 406 def round_robin @fiber_executor.round_robin end |
#run_command(targets, command, options = {}, position = []) ⇒ Object
289 290 291 292 293 294 295 296 297 298 299 300 |
# File 'lib/bolt/executor.rb', line 289 def run_command(targets, command, = {}, position = []) description = .fetch(:description, "command '#{command}'") log_action(description, targets) do [:run_as] = run_as if run_as && !.key?(:run_as) batch_execute(targets) do |transport, batch| with_node_logging("Running command '#{command}'", batch) do transport.batch_command(batch, command, , position, &method(:publish_event)) end end end end |
#run_in_thread ⇒ Object
Execute a plan function concurrently. This function accepts the executor function to be run and the parameters to pass to it, and returns the result of running the executor function.
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 |
# File 'lib/bolt/executor.rb', line 426 def run_in_thread require 'concurrent' require 'fiber' future = Concurrent::Future.execute do yield end # Used to track how often we resume the same executor function still_running = 0 # While the thread is still running while future.incomplete? # If the Fiber gets resumed, increment the resume tracker. This means # the tracker starts at 1 since it needs to increment before yielding, # since it can't yield then increment. still_running += 1 # If the Fiber has been resumed before, still_running will be 2 or # more. Yield different values for when the same Fiber is resumed # multiple times and when it's resumed the first time in order to know # if progress was made in the plan. Fiber.yield(still_running < 2 ? :something_happened : :returned_immediately) end # Once the thread completes, return the result. future.value || future.reason end |
#run_plan(scope, plan, params) ⇒ Object
382 383 384 |
# File 'lib/bolt/executor.rb', line 382 def run_plan(scope, plan, params) plan.call_by_name_with_scope(scope, params, true) end |
#run_script(targets, script, arguments, options = {}, position = []) ⇒ Object
302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 |
# File 'lib/bolt/executor.rb', line 302 def run_script(targets, script, arguments, = {}, position = []) description = .fetch(:description, "script #{script}") log_action(description, targets) do [:run_as] = run_as if run_as && !.key?(:run_as) [:script_interpreter] = (future || {}).fetch('script_interpreter', false) @analytics&.event('Future', 'script_interpreter', label: [:script_interpreter].to_s) batch_execute(targets) do |transport, batch| with_node_logging("Running script #{script} with '#{arguments.to_json}'", batch) do transport.batch_script(batch, script, arguments, , position, &method(:publish_event)) end end end end |
#run_task(targets, task, arguments, options = {}, position = [], log_level = :info) ⇒ Object
318 319 320 321 322 323 324 325 326 327 328 329 330 |
# File 'lib/bolt/executor.rb', line 318 def run_task(targets, task, arguments, = {}, position = [], log_level = :info) description = .fetch(:description, "task #{task.name}") log_action(description, targets) do [:run_as] = run_as if run_as && !.key?(:run_as) arguments['_task'] = task.name batch_execute(targets) do |transport, batch| with_node_logging("Running task #{task.name} with '#{arguments.to_json}'", batch, log_level) do transport.batch_task(batch, task, arguments, , position, &method(:publish_event)) end end end end |
#run_task_with(target_mapping, task, options = {}, position = []) ⇒ Object
332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 |
# File 'lib/bolt/executor.rb', line 332 def run_task_with(target_mapping, task, = {}, position = []) targets = target_mapping.keys description = .fetch(:description, "task #{task.name}") log_action(description, targets) do [:run_as] = run_as if run_as && !.key?(:run_as) target_mapping.each_value { |arguments| arguments['_task'] = task.name } batch_execute(targets) do |transport, batch| with_node_logging("Running task #{task.name}'", batch) do transport.batch_task_with(batch, task, target_mapping, , position, &method(:publish_event)) end end end end |
#shutdown ⇒ Object
118 119 120 121 |
# File 'lib/bolt/executor.rb', line 118 def shutdown @publisher.shutdown @publisher.wait_for_termination end |
#subscribe(subscriber, types = nil) ⇒ Object
91 92 93 94 |
# File 'lib/bolt/executor.rb', line 91 def subscribe(subscriber, types = nil) @subscribers[subscriber] = types self end |
#transport(transport) ⇒ Object
82 83 84 85 86 87 88 89 |
# File 'lib/bolt/executor.rb', line 82 def transport(transport) impl = @transports[transport || 'ssh'] raise(Bolt::UnknownTransportError, transport) unless impl # If there was an error creating the transport, ensure it gets thrown impl.no_error! impl.value end |
#unsubscribe(subscriber, types = nil) ⇒ Object
96 97 98 99 100 101 102 |
# File 'lib/bolt/executor.rb', line 96 def unsubscribe(subscriber, types = nil) if types.nil? || types.sort == @subscribers[subscriber]&.sort @subscribers.delete(subscriber) elsif @subscribers[subscriber].is_a?(Array) @subscribers[subscriber] = @subscribers[subscriber] - types end end |
#upload_file(targets, source, destination, options = {}, position = []) ⇒ Object
348 349 350 351 352 353 354 355 356 357 358 359 |
# File 'lib/bolt/executor.rb', line 348 def upload_file(targets, source, destination, = {}, position = []) description = .fetch(:description, "file upload from #{source} to #{destination}") log_action(description, targets) do [:run_as] = run_as if run_as && !.key?(:run_as) batch_execute(targets) do |transport, batch| with_node_logging("Uploading file #{source} to #{destination}", batch) do transport.batch_upload(batch, source, destination, , position, &method(:publish_event)) end end end end |
#wait(futures, **opts) ⇒ Object
414 415 416 |
# File 'lib/bolt/executor.rb', line 414 def wait(futures, **opts) @fiber_executor.wait(futures, **opts) end |
#wait_until_available(targets, description: 'wait until available', wait_time: 120, retry_interval: 1) ⇒ Object
454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 |
# File 'lib/bolt/executor.rb', line 454 def wait_until_available(targets, description: 'wait until available', wait_time: 120, retry_interval: 1) log_action(description, targets) do batch_execute(targets) do |transport, batch| with_node_logging('Waiting until available', batch) do wait_until(wait_time, retry_interval) { transport.batch_connected?(batch) } batch.map { |target| Result.new(target, action: 'wait_until_available', object: description) } rescue TimeoutError => e available, unavailable = batch.partition { |target| transport.batch_connected?([target]) } ( available.map { |target| Result.new(target, action: 'wait_until_available', object: description) } + unavailable.map { |target| Result.from_exception(target, e, action: 'wait_until_available') } ) end end end end |
#with_node_logging(description, batch, log_level = :info) ⇒ Object
280 281 282 283 284 285 286 287 |
# File 'lib/bolt/executor.rb', line 280 def with_node_logging(description, batch, log_level = :info) @logger.send(log_level, "#{description} on #{batch.map(&:safe_name)}") publish_event(type: :start_spin) result = yield publish_event(type: :stop_spin) @logger.send(log_level, result.to_json) result end |
#without_default_logging ⇒ Object
517 518 519 520 521 522 |
# File 'lib/bolt/executor.rb', line 517 def without_default_logging publish_event(type: :disable_default_output) yield ensure publish_event(type: :enable_default_output) end |