Class: DakeExecutor

Inherits:
Object
  • Object
show all
Defined in:
lib/dake/executor.rb

Instance Method Summary collapse

Constructor Details

#initialize(analyzer, dake_db, dep_graph, jobs) ⇒ DakeExecutor

Returns a new instance of DakeExecutor.



5
6
7
8
9
10
11
12
13
14
15
16
# File 'lib/dake/executor.rb', line 5

def initialize(analyzer, dake_db, dep_graph, jobs)
  @analyzer = analyzer
  @dake_db = dake_db
  @dep_graph = dep_graph
  @complete_dep_steps = Hash.new(0)
  @async = (jobs ? true : false)
  @pool = Concurrent::ThreadPoolExecutor.new(
      min_threads: 1,
      max_threads: jobs,
      max_queue: 0 # unbounded work queue
  ) if @async
end

Instance Method Details

#execute(rebuild_set, dry_run = false, log = false) ⇒ Object



18
19
20
21
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
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
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
# File 'lib/dake/executor.rb', line 18

def execute(rebuild_set, dry_run=false, log=false)
  if rebuild_set.empty?
    STDERR.puts "Nothing to be done.".colorize(:green)
    return
  end
  if @async
    dep_map = Hash.new
    rebuild_set.each do |step|
      dep_set = @dep_graph.dep_step[step]
      next if dep_set.empty?
      dep_map[step] = dep_set & rebuild_set
    end

    queue = Queue.new
    error_queue = Queue.new
    error_steps = Set.new

    error_thr = Thread.new do
      while error = error_queue.deq
        if error.is_a? Exception
          STDERR.puts "#{error.class}: #{error.message}".colorize(:red)
          STDERR.puts "Continue to execute other Step(s)".colorize(:red)
          STDERR.puts "To Force Quitting: Press Ctrl + C".colorize(:red)
        end
      end
    end

    lock = Concurrent::ReadWriteLock.new
    @dep_graph.leaf_step.each { |step| queue << step if rebuild_set.include? step }

    while next_step = queue.deq
      @pool.post(next_step) do |step|
        lock.acquire_read_lock
        error_step = error_steps.include? step
        lock.release_read_lock
        if error_step
          line, column = @analyzer.step_line_and_column step
          msg = "Step(#{step.object_id}) defined in #{step.src_file} at #{line}:#{column} " +
                "skipped due to prerequisite step(s) error."
          error_queue << Exception.new(msg)
        else
          execute_step(step, dry_run, log)
        end
        lock.acquire_write_lock
        dep_map.delete step
        if dep_map.empty?
          queue.close
        else
          @dep_graph.succ_step[step].each do |succ|
            next unless dep_map[succ]
            dep_map[succ].delete step
            if dep_map[succ].empty?
              queue << succ
            elsif dep_map[succ].all? { |dep_step| error_steps.include? dep_step }
              error_steps << succ
              queue << succ
            end
          end
        end
        lock.release_write_lock
      rescue Exception => e
        error_queue << e
        lock.acquire_write_lock
        error_steps << step
        dep_map.delete step
        if dep_map.empty?
          queue.close
        else
          @dep_graph.succ_step[step].each do |succ|
            if dep_map[succ].all? { |dep_step| error_steps.include? dep_step }
              error_steps << succ
              queue << succ
            end
          end
        end
        lock.release_write_lock
      end
    end
    @pool.shutdown
    @pool.wait_for_termination
    queue.close
    error_queue.close
    error_thr.join
    raise "Failed to execute some step(s)" unless error_steps.empty?
  else
    @dep_graph.step_list.each do |step|
      execute_step(step, dry_run, log) if rebuild_set.include? step
    end
  end
end

#execute_step(step, dry_run, log) ⇒ Object



109
110
111
112
113
114
115
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
# File 'lib/dake/executor.rb', line 109

def execute_step(step, dry_run, log)
  prepare_step(step)
  protocol = step.option_dict['protocol']
  protocol ||= 'shell'

  line, column = @analyzer.step_line_and_column step
  proto = DakeProtocol::ProtocolDict[protocol].new(step, @analyzer, @dake_db, dry_run)
  STDERR.puts ("[#{Time.now.strftime('%Y-%m-%d %H:%M:%S')}] Running #{protocol} step(#{step.object_id}) defined in " +
               "#{step.src_file} at #{line}:#{column}").colorize(:green)
  STDERR.puts "[#{Time.now.strftime('%Y-%m-%d %H:%M:%S')}] step(#{step.object_id}) Script in #{proto.script_file}".colorize(:green) unless dry_run
  step.targets.each do |target|
    next if target.scheme.is_a? DakeScheme::Regex
    if target.scheme.is_a? DakeScheme::Tag
      STDERR.puts "[#{Time.now.strftime('%Y-%m-%d %H:%M:%S')}] step(#{step.object_id}) Producing ".colorize(:green) +
                   "@#{target.scheme.path}".colorize(:light_blue)
    else
      STDERR.puts "[#{Time.now.strftime('%Y-%m-%d %H:%M:%S')}] step(#{step.object_id}) Producing ".colorize(:green) +
                  "#{target.scheme.path}".colorize(:light_white)
    end
  end
  STDERR.puts "[#{Time.now.strftime('%Y-%m-%d %H:%M:%S')}] step(#{step.object_id}) STDOUT in #{proto.script_stdout}".colorize(:green) if log and not dry_run
  STDERR.puts "[#{Time.now.strftime('%Y-%m-%d %H:%M:%S')}] step(#{step.object_id}) STDERR in #{proto.script_stderr}".colorize(:green) if log and not dry_run

  if dry_run
    puts step.cmd_text
  else
    proto.execute_step(log)
  end

  STDERR.puts ("[#{Time.now.strftime('%Y-%m-%d %H:%M:%S')}] Complete #{protocol} step(#{step.object_id}) defined in " +
      "#{step.src_file} at #{line}:#{column}").colorize(:green)
end

#prepare_command(step, context = {}) ⇒ Object

command preparation is intentionally deferred to execution phase to accelerate the analysis phase of big workflow file



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
# File 'lib/dake/executor.rb', line 168

def prepare_command(step, context={})
  mixin_method = (step.option_dict['method'] ? step.option_dict['method'] : nil)
  method_mode = (step.option_dict['method_mode'] ? step.option_dict['method_mode'] : 'prepend')
  if mixin_method
    meth = @analyzer.method_dict[mixin_method]
    unless meth
      line, column = @analyzer.option_line_and_column(step.options, 'method')
      raise "Method `#{mixin_method}' used in #{step.src_file} at #{line}:#{column} is not defined."
    end
    @analyzer.analyze_option(meth)
    unless step.option_dict['protocol'] == meth.option_dict['protocol']
      line, column = @analyzer.option_line_and_column(step.options, 'protocol')
      line, column = @analyzer.step_line_and_column(step) unless line
      meth_line, meth_column = meth.name.line_and_column
      raise "Method `#{mixin_method}' defined in #{meth.src_file} at #{meth_line}:#{meth_column} " +
            "uses protocol `#{meth.option_dict['protocol']}', which is incompatible with protocol " +
            "`#{step.option_dict['protocol']}' used in #{step.src_file} at #{line}:#{column}."
    end
    if method_mode == 'replace'
      return prepare_command(meth, step.context)
    else
      method_text = prepare_command(meth, step.context)
    end
  end
  cmd_text = ''
  cmd_text << method_text if mixin_method and method_mode == 'prepend'
  first_indent = step.commands[0].items[0].to_s unless step.commands.empty?
  step.commands.each do |command|
    indent = command.items[0]
    if not indent.to_s.start_with? first_indent
      line, column = indent.line_and_column
      raise "Incompatible indentation in #{step.src_file} at #{line}:#{column}."
    else
      indentation = indent.to_s[first_indent.length..-1]
      cmd_text << indentation + @analyzer.text_eval(command, step.src_file, step.context.merge(context), 1) + "\n"
    end
  end
  cmd_text << method_text if mixin_method and method_mode == 'append'
  if cmd_text == ''
    line, column = @analyzer.step_line_and_column step
    step_meth = step.is_a?(StepMethod) ? 'Method' : 'Step'
    raise "#{step_meth} defined in #{step.src_file} at #{line}:#{column} has no commands."
  end
  cmd_text
end

#prepare_step(step) ⇒ Object



142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
# File 'lib/dake/executor.rb', line 142

def prepare_step(step)
  context = step.context.merge!({'OUTPUTN' => 0, 'OUTPUTS' => [], 'INPUTN' => 0, 'INPUTS' => []})
  step.targets.reject { |f| [DakeScheme::Tag, DakeScheme::Regex].include? f.scheme.class }.each_with_index do |output, n|
    name = output.scheme.path
    context["OUTPUT"] = name if n == 0
    context["OUTPUT#{n}"] = name
    context["OUTPUTS"] << name
    context["OUTPUTN"] += 1
  end
  context['OUTPUTN'] = context['OUTPUTN'].to_s
  context['OUTPUTS'] = context['OUTPUTS'].join(" ")
  step.prerequisites.reject { |s| s.tag }.each_with_index do |input, n|
    name = input.scheme.path
    context["INPUT"] = name if n == 0
    context["INPUT#{n}"] = name
    context["INPUTS"] << name
    context["INPUTN"] += 1
  end
  context['INPUTN'] = context['INPUTN'].to_s
  context['INPUTS'] = context['INPUTS'].join(" ")
  @analyzer.analyze_option(step)
  step.cmd_text = prepare_command(step)
end