Class: Doable::Job

Inherits:
Object
  • Object
show all
Includes:
Helpers::FrameworkHelpers, Helpers::LoggingHelpers
Defined in:
lib/doable/job.rb

Overview

The Job class is responsible for describing the process of running some set of steps. It utilizes a very specific DSL for defining what steps need executing, along with their order. It can also describe how to recover when things break and provides hooks and triggers to make more flexible scripts for varying environments.

Constant Summary

Constants included from Helpers::LoggingHelpers

Helpers::LoggingHelpers::LOGGING_MUTEX

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Methods included from Helpers::LoggingHelpers

#colorize, #log

Methods included from Helpers::FrameworkHelpers

#skip

Constructor Details

#initialize {|_self| ... } ⇒ Job

Returns a new instance of Job.

Yields:

  • (_self)

Yield Parameters:

  • _self (Doable::Job)

    the object that the method was called on



15
16
17
18
19
20
21
# File 'lib/doable/job.rb', line 15

def initialize
  @hooks    = {}
  @steps    = []
  @handlers = {}
  @threads  = []
  yield self
end

Instance Attribute Details

#handlersObject (readonly)

Returns the value of attribute handlers.



9
10
11
# File 'lib/doable/job.rb', line 9

def handlers
  @handlers
end

#hooksObject (readonly)

Returns the value of attribute hooks.



9
10
11
# File 'lib/doable/job.rb', line 9

def hooks
  @hooks
end

#stepsObject (readonly)

Returns the value of attribute steps.



9
10
11
# File 'lib/doable/job.rb', line 9

def steps
  @steps
end

#threadsObject (readonly)

Returns the value of attribute threads.



9
10
11
# File 'lib/doable/job.rb', line 9

def threads
  @threads
end

Class Method Details

.plan(&block) ⇒ Object



11
12
13
# File 'lib/doable/job.rb', line 11

def self.plan(&block)
  self.new(&block)
end

Instance Method Details

#after(options = {}, &block) ⇒ Boolean

Registers an action to be performed after normal execution completes

Parameters:

  • options (Hash) (defaults to: {})
  • block (Proc)

Returns:

  • (Boolean)


53
54
55
# File 'lib/doable/job.rb', line 53

def after(options = {}, &block)
  on(:after, options, &block)
end

#attempt(options = {}, &block) ⇒ Boolean

Add a step to the queue, but first wrap it in a begin..rescue WARNING! Exception handlers are __not__ used with these steps, as they never actually raise exceptions

Parameters:

  • options (Hash) (defaults to: {})
  • block (Proc)

Returns:

  • (Boolean)


62
63
64
65
66
67
68
69
70
71
72
73
# File 'lib/doable/job.rb', line 62

def attempt(options = {}, &block)
  @steps << Step.new(self, options) do
    begin
      block.call
    rescue SkipStep => e
      raise e # We'll rescue this somewhere higher up the stack
    rescue => e
      log "Ignoring Exception in attempted step: #{colorize("#{e.class}: (#{e.message})", :red)}"
    end
  end
  return true
end

#background(options = {}, &block) ⇒ Step

Allow running steps in the background

Parameters:

  • options (Hash) (defaults to: {})
  • block (Proc)

Returns:



79
80
81
82
83
# File 'lib/doable/job.rb', line 79

def background(options = {}, &block)
  @steps << Step.new(self, options) do
    @threads << Thread.new { block.call }
  end
end

#before(options = {}, &block) ⇒ Step

Registers an action to be performed before normal step execution

Parameters:

  • options (Hash) (defaults to: {})
  • block (Proc)

Returns:



45
46
47
# File 'lib/doable/job.rb', line 45

def before(options = {}, &block)
  on(:before, options, &block)
end

#contextBinding

Returns the binding context of the Job

Returns:

  • (Binding)


103
104
105
# File 'lib/doable/job.rb', line 103

def context
  binding
end

#handle(exception, &block) ⇒ Object

Register a handler for named exception

Parameters:

  • exception (String, StandardError)

    Exception to register handler for

  • block (Proc)


110
111
112
# File 'lib/doable/job.rb', line 110

def handle(exception, &block)
  @handlers[exception] = Step.new(self, &block)
end

#multitasking?Boolean

Check if background steps are running

Returns:

  • (Boolean)


87
88
89
# File 'lib/doable/job.rb', line 87

def multitasking?
  return @threads.collect {|t| t if t.alive? }.compact.empty? ? false : true
end

#on(hook, options = {}, &block) ⇒ Step

Registers a hook action to be performed when the hook is triggered

Parameters:

  • hook (Symbol)

    Name of the hook to register the action with

  • options (Hash) (defaults to: {})
  • block (Proc)

Returns:



28
29
30
31
# File 'lib/doable/job.rb', line 28

def on(hook, options = {}, &block)
  @hooks[hook] ||= []
  @hooks[hook] << Step.new(self, options, &block)
end

#rollback!Object

Trigger a rollback of the entire Job, based on calls to #rollback!() on each eligible Step

Raises:



92
93
94
95
96
97
98
99
# File 'lib/doable/job.rb', line 92

def rollback!
  log "Rolling Back...", :warn
  @hooks[:after].reverse.each {|s| s.rollback! if s.rollbackable? }
  @steps.reverse.each {|s| s.rollback! if s.rollbackable? }
  @hooks[:before].reverse.each {|s| s.rollback! if s.rollbackable? }
  log "Rollback complete!", :warn
  raise RolledBack
end

#runObject

Here we actually trigger the execution of a Job



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
# File 'lib/doable/job.rb', line 157

def run
  #merge_config FILE_CONFIG
  #merge_config CLI_CONFIG
  ## Run our defaults Proc to merge in any default configs
  #@defaults.call(@@config)

  # before hooks
  trigger(:before)
  
  # Actual installer steps
  @steps.each_with_index do |step, index|
    begin
      step.call
    rescue SkipStep => e
      step.skip
      log e.message, :warn
    rescue => e
      if @handlers[e.message]
        log "Handling #{e.class}: (#{e.message})", :warn
        @handlers[e.message].call(e, step)
        step.handled
      elsif @handlers[e.class]
        log "Handling #{e.class}: (#{e.message})", :warn
        @handlers[e.class].call(e, step)
        step.handled
      else
        # Check the ancestry of the exception to see if any lower level Exception classes are caught
        e.class.ancestors[1..-4].each do |ancestor|
          if @handlers[ancestor]
            log "Handling #{e.class}: (#{e.message}) via handler for #{ancestor}", :warn
            @handlers[ancestor].call(e, step)
            step.handled
          end # if @handlers[ancestor]
        end
        
        unless step.successful?
          message = "\n\nUnhandled Exception in #{colorize("steps[#{index}]", :yellow)}: #{colorize("#{e.class}: (#{e.message})", :red)}\n\n"
          #if @config.auto_rollback
          #  log message
          #  rollback!
          #else
            raise message
          #end
        end # unless
      end # if @handlers...
    end # rescue
  end # @steps.each_with_index
  
  # after hooks
  trigger(:after)
  
  # bring together all background threads
  unless @threads.empty?
    log "Cleaning up background tasks..."
    @threads.each do |t|
      begin
        t.join
      rescue => e
        # We don't really need to do anything here,
        # we've already handled or died from aborted Threads
      end
    end
  end

  log "All Job steps completed successfully!", :success   # This should only happen if everything goes well
end

#step(options = {}, &block) ⇒ Step

Adds a step to the queue

Parameters:

  • options (Hash) (defaults to: {})
  • block (Proc)

Returns:



37
38
39
# File 'lib/doable/job.rb', line 37

def step(options = {}, &block)
  @steps << Step.new(self, options, &block)
end

#trigger(hook) ⇒ Object

This triggers a block associated with a hook

Parameters:

  • hook (Symbol)

    Hook to trigger



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
# File 'lib/doable/job.rb', line 116

def trigger(hook)
  @hooks[hook].each_with_index do |step, index|
    begin
      step.call
    rescue SkipStep => e
      step.skip
      log e.message, :warn
    rescue => e
      if @handlers[e.message]
        log "Handling #{e.class}: (#{e.message})", :warn
        @handlers[e.message].call(e, step)
        step.handled unless step.status == :skipped       # Don't mark the step as "handled" if it was skipped
      elsif @handlers[e.class]
        log "Handling #{e.class}: (#{e.message})", :warn
        @handlers[e.class].call(e, step)
        step.handled unless step.status == :skipped       # Don't mark the step as "handled" if it was skipped
      else
        # Check the ancestry of the exception to see if any lower level Exception classes are caught
        e.class.ancestors[1..-4].each do |ancestor|
          if @handlers[ancestor]
            log "Handling #{e.class}: (#{e.message}) via handler for #{ancestor}", :warn
            @handlers[ancestor].call(e, step)
            step.handled unless step.status == :skipped   # Don't mark the step as "handled" if it was skipped
          end # if @@handlers[ancestor]
        end
        
        unless step.successful?
          message = "\n\nUnhandled Exception in #{colorize("hooks##{hook}[#{index}]", :yellow)}: #{colorize("#{e.class}: (#{e.message})", :red)}\n\n"
          if @config.auto_rollback
            log message
            rollback!
          else
            raise message
          end
        end # unless
      end
    end # begin()
  end if @hooks[hook] # each_with_index()
end