Class: Bolt::Executor
- Inherits:
-
Object
- Object
- Bolt::Executor
- Defined in:
- lib/bolt/executor.rb
Defined Under Namespace
Classes: TimeoutError
Instance Attribute Summary collapse
-
#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”.
- #finish_plan(plan_result) ⇒ Object
-
#initialize(concurrency = 1, analytics = Bolt::Analytics::NoopClient.new, noop = false) ⇒ Executor
constructor
FIXME: There must be a better way makandracards.com/makandra/36011-ruby-do-not-mix-optional-and-keyword-arguments.
- #log_action(description, targets) ⇒ Object
- #log_plan(plan_name) ⇒ 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_function_call(function) ⇒ Object
- #report_transport(transport, count) ⇒ Object
- #report_yaml_plan(plan) ⇒ Object
- #run_command(targets, command, options = {}, &callback) ⇒ Object
- #run_script(targets, script, arguments, options = {}, &callback) ⇒ Object
- #run_task(targets, task, arguments, options = {}, &callback) ⇒ Object
-
#start_plan(plan_context) ⇒ Object
Plan context doesn’t make sense for most transports but it is tightly coupled with the orchestrator transport since the transport behaves differently when a plan is running.
- #transport(transport) ⇒ Object
- #upload_file(targets, source, destination, options = {}, &callback) ⇒ Object
- #wait_until(timeout, retry_interval) ⇒ Object
- #wait_until_available(targets, description: 'wait until available', wait_time: 120, retry_interval: 1) ⇒ Object
- #with_node_logging(description, batch) ⇒ Object
- #without_default_logging ⇒ Object
Constructor Details
#initialize(concurrency = 1, analytics = Bolt::Analytics::NoopClient.new, noop = false) ⇒ Executor
FIXME: There must be a better way makandracards.com/makandra/36011-ruby-do-not-mix-optional-and-keyword-arguments
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 |
# File 'lib/bolt/executor.rb', line 22 def initialize(concurrency = 1, analytics = Bolt::Analytics::NoopClient.new, noop = false) # lazy-load expensive gem code require 'concurrent' @analytics = analytics @logger = Logging.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 @noop = noop @run_as = nil @pool = if concurrency > 0 Concurrent::ThreadPoolExecutor.new(max_threads: concurrency) else Concurrent.global_immediate_executor end @logger.debug { "Started with #{concurrency} max thread(s)" } @notifier = Bolt::Notifier.new end |
Instance Attribute Details
#noop ⇒ Object (readonly)
Returns the value of attribute noop.
17 18 19 |
# File 'lib/bolt/executor.rb', line 17 def noop @noop end |
#run_as ⇒ Object
Returns the value of attribute run_as.
18 19 20 |
# File 'lib/bolt/executor.rb', line 18 def run_as @run_as end |
#transports ⇒ Object (readonly)
Returns the value of attribute transports.
17 18 19 |
# File 'lib/bolt/executor.rb', line 17 def transports @transports end |
Instance Method Details
#await_results(promises) ⇒ Object
Create a ResultSet from the results of all promises.
115 116 117 |
# File 'lib/bolt/executor.rb', line 115 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.
126 127 128 129 |
# File 'lib/bolt/executor.rb', line 126 def batch_execute(targets, &block) promises = queue_execute(targets, &block) await_results(promises) end |
#finish_plan(plan_result) ⇒ Object
340 341 342 |
# File 'lib/bolt/executor.rb', line 340 def finish_plan(plan_result) transport('pcp').finish_plan(plan_result) end |
#log_action(description, targets) ⇒ Object
131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 |
# File 'lib/bolt/executor.rb', line 131 def log_action(description, targets) # When running a plan, info messages like starting a task are promoted to notice. log_method = @plan_logging ? :notice : :info target_str = if targets.length > 5 "#{targets.count} targets" else targets.map(&:uri).join(', ') end @logger.send(log_method, "Starting: #{description} on #{target_str}") start_time = Time.now results = yield duration = Time.now - start_time failures = results.error_set.length plural = failures == 1 ? '' : 's' @logger.send(log_method, "Finished: #{description} with #{failures} failure#{plural} in #{duration.round(2)} sec") results end |
#log_plan(plan_name) ⇒ Object
154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 |
# File 'lib/bolt/executor.rb', line 154 def log_plan(plan_name) log_method = @plan_logging ? :notice : :info @logger.send(log_method, "Starting: plan #{plan_name}") start_time = Time.now results = nil begin results = yield ensure duration = Time.now - start_time @logger.send(log_method, "Finished: plan #{plan_name} in #{duration.round(2)} sec") end results 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.
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 |
# File 'lib/bolt/executor.rb', line 70 def queue_execute(targets) 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| begin 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 end batch_promises.values end end end |
#report_apply(statement_count, resource_counts) ⇒ Object
188 189 190 191 192 193 194 195 196 197 198 |
# File 'lib/bolt/executor.rb', line 188 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
182 183 184 185 186 |
# File 'lib/bolt/executor.rb', line 182 def report_bundled_content(mode, name) if @analytics.bundled_content&.include?(name) @analytics&.event('Bundled Content', mode, label: name) end end |
#report_function_call(function) ⇒ Object
178 179 180 |
# File 'lib/bolt/executor.rb', line 178 def report_function_call(function) @analytics&.event('Plan', 'call_function', label: function) end |
#report_transport(transport, count) ⇒ Object
170 171 172 173 174 175 176 |
# File 'lib/bolt/executor.rb', line 170 def report_transport(transport, count) name = transport.class.name.split('::').last.downcase unless @reported_transports.include?(name) @analytics&.event('Transport', 'initialize', label: name, value: count) end @reported_transports.add(name) end |
#report_yaml_plan(plan) ⇒ Object
200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 |
# File 'lib/bolt/executor.rb', line 200 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.debug { "Failed to submit analytics event: #{e.message}" } end |
#run_command(targets, command, options = {}, &callback) ⇒ Object
223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 |
# File 'lib/bolt/executor.rb', line 223 def run_command(targets, command, = {}, &callback) description = .fetch('_description', "command '#{command}'") log_action(description, targets) do notify = proc { |event| @notifier.notify(callback, event) if callback } = { '_run_as' => run_as }.merge() if run_as results = batch_execute(targets) do |transport, batch| with_node_logging("Running command '#{command}'", batch) do transport.batch_command(batch, command, , ¬ify) end end @notifier.shutdown results end end |
#run_script(targets, script, arguments, options = {}, &callback) ⇒ Object
240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 |
# File 'lib/bolt/executor.rb', line 240 def run_script(targets, script, arguments, = {}, &callback) description = .fetch('_description', "script #{script}") log_action(description, targets) do notify = proc { |event| @notifier.notify(callback, event) if callback } = { '_run_as' => run_as }.merge() if run_as results = batch_execute(targets) do |transport, batch| with_node_logging("Running script #{script} with '#{arguments}'", batch) do transport.batch_script(batch, script, arguments, , ¬ify) end end @notifier.shutdown results end end |
#run_task(targets, task, arguments, options = {}, &callback) ⇒ Object
257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 |
# File 'lib/bolt/executor.rb', line 257 def run_task(targets, task, arguments, = {}, &callback) description = .fetch('_description', "task #{task.name}") log_action(description, targets) do notify = proc { |event| @notifier.notify(callback, event) if callback } = { '_run_as' => run_as }.merge() if run_as arguments['_task'] = task.name results = batch_execute(targets) do |transport, batch| with_node_logging("Running task #{task.name} with '#{arguments}'", batch) do transport.batch_task(batch, task, arguments, , ¬ify) end end @notifier.shutdown results end end |
#start_plan(plan_context) ⇒ Object
Plan context doesn’t make sense for most transports but it is tightly coupled with the orchestrator transport since the transport behaves differently when a plan is running. In order to limit how much this pollutes the transport API we only handle the orchestrator transport here. Since we callt this function without resolving targets this will result in the orchestrator transport always being initialized during plan runs. For now that’s ok.
In the future if other transports need this or if we want a plan stack we’ll need to refactor.
335 336 337 338 |
# File 'lib/bolt/executor.rb', line 335 def start_plan(plan_context) transport('pcp').plan_context = plan_context @plan_logging = true end |
#transport(transport) ⇒ Object
56 57 58 59 60 61 62 |
# File 'lib/bolt/executor.rb', line 56 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 |
#upload_file(targets, source, destination, options = {}, &callback) ⇒ Object
275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 |
# File 'lib/bolt/executor.rb', line 275 def upload_file(targets, source, destination, = {}, &callback) description = .fetch('_description', "file upload from #{source} to #{destination}") log_action(description, targets) do notify = proc { |event| @notifier.notify(callback, event) if callback } = { '_run_as' => run_as }.merge() if run_as results = batch_execute(targets) do |transport, batch| with_node_logging("Uploading file #{source} to #{destination}", batch) do transport.batch_upload(batch, source, destination, , ¬ify) end end @notifier.shutdown results end end |
#wait_until(timeout, retry_interval) ⇒ Object
317 318 319 320 321 322 323 |
# File 'lib/bolt/executor.rb', line 317 def wait_until(timeout, retry_interval) start = wait_now until yield raise(TimeoutError, 'Timed out waiting for target') if (wait_now - start).to_i >= timeout sleep(retry_interval) end end |
#wait_until_available(targets, description: 'wait until available', wait_time: 120, retry_interval: 1) ⇒ Object
294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 |
# File 'lib/bolt/executor.rb', line 294 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 begin wait_until(wait_time, retry_interval) { transport.batch_connected?(batch) } batch.map { |target| Result.new(target) } rescue TimeoutError => e batch.map { |target| Result.from_exception(target, e) } end end end end end |
#with_node_logging(description, batch) ⇒ Object
216 217 218 219 220 221 |
# File 'lib/bolt/executor.rb', line 216 def with_node_logging(description, batch) @logger.info("#{description} on #{batch.map(&:uri)}") result = yield @logger.info(result.to_json) result end |
#without_default_logging ⇒ Object
344 345 346 347 348 349 350 |
# File 'lib/bolt/executor.rb', line 344 def without_default_logging old_log = @plan_logging @plan_logging = false yield ensure @plan_logging = old_log end |