Skip to content

Commit

Permalink
Add tool to visualize Jobs in graphviz dot format
Browse files Browse the repository at this point in the history
  • Loading branch information
Fryguy committed Dec 10, 2019
1 parent 40d7e17 commit b112771
Show file tree
Hide file tree
Showing 2 changed files with 66 additions and 0 deletions.
45 changes: 45 additions & 0 deletions app/models/job/state_machine.rb
Original file line number Diff line number Diff line change
@@ -1,6 +1,20 @@
module Job::StateMachine
extend ActiveSupport::Concern

module ClassMethods
#
# Helper methods for display of transitions
#

def to_dot(*args)
new.to_dot(*args)
end

def to_svg(*args)
new.to_svg(*args)
end
end

def transitions
@transitions ||= load_transitions
end
Expand Down Expand Up @@ -51,4 +65,35 @@ def queue_signal(*args, priority: MiqQueue::NORMAL_PRIORITY, role: nil, deliver_
:server_guid => server_guid
)
end

#
# Helper methods for display of transitions
#

def to_dot(include_starred_states = false)
all_states = transitions.values.map(&:to_a).flatten.uniq.reject { |t| t == "*" }

"".tap do |s|
s << "digraph #{self.class.name.inspect} {\n"
transitions.each do |signal, signal_transitions|
signal_transitions.each do |from, to|
next if !include_starred_states && (from == "*" || to == "*")

from = from == "*" ? all_states : [from]
to = to == "*" ? all_states : [to]
from.product(to).each { |f, t| s << " #{f} -> #{t} [ label=\"#{signal}\" ]\n" }
end
end
s << "}\n"
end
end

def to_svg(include_starred_states = false)
require "open3"
out, err, _status = Open3.capture3("dot -Tsvg", :stdin_data => to_dot(include_starred_states))

raise "Error from graphviz:\n#{err}" if err.present?

out
end
end
21 changes: 21 additions & 0 deletions tools/job_to_svg.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
#!/usr/bin/env ruby

if ARGV.empty?
puts "USAGE: #{__FILE__} job_class [outfile]"
exit 1
end

job_class, outfile = ARGV

require File.expand_path("../config/environment", __dir__)

job_class = job_class.constantize rescue NilClass
unless job_class < Job
puts "ERROR: job_class is not a subclass of Job.\n\nValid job_class values are:"
puts Job.descendants.map(&:name).sort.join("\n").indent(2)
exit 1
end

outfile ||= "#{job_class.name.underscore.tr("/", "-")}.svg"
File.write(outfile, job_class.to_svg)
puts "\nWritten to #{outfile}"

0 comments on commit b112771

Please sign in to comment.