44acc18a019759342f94c15c3e1bafd9207be758
[arvados.git] / apps / workbench / app / helpers / provenance_helper.rb
1 module ProvenanceHelper
2
3   class GenerateGraph
4     def initialize(pdata, opts)
5       @pdata = pdata
6       @opts = opts
7       @visited = {}
8       @jobs = {}
9       @node_extra = {}
10     end
11
12     def self.collection_uuid(uuid)
13       Keep::Locator.parse(uuid).andand.strip_hints.andand.to_s
14     end
15
16     def url_for u
17       p = { :host => @opts[:request].host,
18         :port => @opts[:request].port,
19         :protocol => @opts[:request].protocol }
20       p.merge! u
21       Rails.application.routes.url_helpers.url_for (p)
22     end
23
24     def determine_fillcolor(n)
25       fillcolor = %w(666666 669966 666699 666666 996666)[n || 0] || '666666'
26       "style=\"filled\",color=\"#ffffff\",fillcolor=\"##{fillcolor}\",fontcolor=\"#ffffff\""
27     end
28
29     def describe_node(uuid, describe_opts={})
30       bgcolor = determine_fillcolor (describe_opts[:pip] || @opts[:pips].andand[uuid])
31
32       rsc = ArvadosBase::resource_class_for_uuid uuid
33
34       if GenerateGraph::collection_uuid(uuid) || rsc == Collection
35         if Collection.is_empty_blob_locator? uuid.to_s
36           # special case
37           return "\"#{uuid}\" [label=\"(empty collection)\"];\n"
38         end
39
40         href = url_for ({:controller => Collection.to_s.tableize,
41                           :action => :show,
42                           :id => uuid.to_s })
43
44         return "\"#{uuid}\" [label=\"#{encode_quotes(describe_opts[:label] || (@pdata[uuid] and @pdata[uuid][:name]) || uuid)}\",shape=box,href=\"#{href}\",#{bgcolor}];\n"
45       else
46         href = ""
47         if describe_opts[:href]
48           href = ",href=\"#{url_for ({:controller => describe_opts[:href][:controller],
49                             :action => :show,
50                             :id => describe_opts[:href][:id] })}\""
51         end
52         return "\"#{uuid}\" [label=\"#{encode_quotes(describe_opts[:label] || uuid)}\",#{bgcolor},shape=#{describe_opts[:shape] || 'box'}#{href}];\n"
53       end
54     end
55
56     def job_uuid(job)
57       d = Digest::MD5.hexdigest(job[:script_parameters].to_json)
58       if @opts[:combine_jobs] == :script_only
59         uuid = "#{job[:script]}_#{d}"
60       elsif @opts[:combine_jobs] == :script_and_version
61         uuid = "#{job[:script]}_#{job[:script_version]}_#{d}"
62       else
63         uuid = "#{job[:uuid]}"
64       end
65
66       @jobs[uuid] = [] unless @jobs[uuid]
67       @jobs[uuid] << job unless @jobs[uuid].include? job
68
69       uuid
70     end
71
72     def edge(tail, head, extra)
73       if @opts[:direction] == :bottom_up
74         gr = "\"#{encode_quotes head}\" -> \"#{encode_quotes tail}\""
75       else
76         gr = "\"#{encode_quotes tail}\" -> \"#{encode_quotes head}\""
77       end
78
79       if extra.length > 0
80         gr += " ["
81         extra.each do |k, v|
82           gr += "#{k}=\"#{encode_quotes v}\","
83         end
84         gr += "]"
85       end
86       gr += ";\n"
87       gr
88     end
89
90     def script_param_edges(uuid, sp)
91       gr = ""
92
93       sp.each do |k, v|
94         if @opts[:all_script_parameters]
95           if v.is_a? Array or v.is_a? Hash
96             encv = JSON.pretty_generate(v).gsub("\n", "\\l") + "\\l"
97           else
98             encv = v.to_json
99           end
100           gr += "\"#{encode_quotes encv}\" [shape=box];\n"
101           gr += edge(encv, uuid, {:label => k})
102         end
103       end
104       gr
105     end
106
107     def cr_edges cr
108       uuid = cr[:uuid]
109       gr = ""
110
111       # Search for input mounts
112       input_obj = cr[:mounts].andand[:"/var/lib/cwl/cwl.input.json"].andand[:content] || cr[:mounts] || {}
113       if input_obj
114         ProvenanceHelper::find_collections input_obj, 'input' do |col_hash, col_uuid, key|
115           if col_uuid
116             gr += describe_node(col_uuid)
117             gr += edge(col_uuid, uuid, {:label => key})
118           else
119             gr += describe_node(col_hash)
120             gr += edge(col_hash, uuid, {:label => key})
121           end
122         end
123       end
124
125       [
126         [:output_uuid, 'output'],
127         [:log_uuid, 'log']
128       ].each do |attr, label|
129         if cr[attr]
130           gr += describe_node(cr[attr])
131           gr += edge(uuid, cr[attr], {label: label})
132         end
133       end
134
135       gr
136     end
137
138     def job_edges job, edge_opts={}
139       uuid = job_uuid(job)
140       gr = ""
141
142       ProvenanceHelper::find_collections job[:script_parameters] do |collection_hash, collection_uuid, key|
143         if collection_uuid
144           gr += describe_node(collection_uuid)
145           gr += edge(collection_uuid, uuid, {:label => key})
146         else
147           gr += describe_node(collection_hash)
148           gr += edge(collection_hash, uuid, {:label => key})
149         end
150       end
151
152       if job[:docker_image_locator] and !@opts[:no_docker]
153         gr += describe_node(job[:docker_image_locator], {label: (job[:runtime_constraints].andand[:docker_image] || job[:docker_image_locator])})
154         gr += edge(job[:docker_image_locator], uuid, {label: "docker_image"})
155       end
156
157       if @opts[:script_version_nodes]
158         gr += describe_node(job[:script_version], {:label => "git:#{job[:script_version]}"})
159         gr += edge(job[:script_version], uuid, {:label => "script_version"})
160       end
161
162       if job[:output] and !edge_opts[:no_output]
163         gr += describe_node(job[:output])
164         gr += edge(uuid, job[:output], {label: "output" })
165       end
166
167       if job[:log] and !edge_opts[:no_log]
168         gr += describe_node(job[:log])
169         gr += edge(uuid, job[:log], {label: "log"})
170       end
171
172       gr
173     end
174
175     def generate_provenance_edges(uuid)
176       gr = ""
177       m = GenerateGraph::collection_uuid(uuid)
178       uuid = m if m
179
180       if uuid.nil? or uuid.empty? or @visited[uuid]
181         return ""
182       end
183
184       if @pdata[uuid].nil?
185         return ""
186       else
187         @visited[uuid] = true
188       end
189
190       if uuid.start_with? "component_"
191         # Pipeline component inputs
192         job = @pdata[@pdata[uuid][:job].andand[:uuid]]
193
194         if job
195           gr += describe_node(job_uuid(job), {label: uuid[38..-1], pip: @opts[:pips].andand[job[:uuid]], shape: "oval",
196                                 href: {controller: 'jobs', id: job[:uuid]}})
197           gr += job_edges job, {no_output: true, no_log: true}
198         end
199
200         # Pipeline component output
201         outuuid = @pdata[uuid][:output_uuid]
202         if outuuid
203           outcollection = @pdata[outuuid]
204           if outcollection
205             gr += edge(job_uuid(job), outcollection[:portable_data_hash], {label: "output"})
206             gr += describe_node(outcollection[:portable_data_hash], {label: outcollection[:name]})
207           end
208         elsif job and job[:output]
209           gr += describe_node(job[:output])
210           gr += edge(job_uuid(job), job[:output], {label: "output" })
211         end
212       else
213         rsc = ArvadosBase::resource_class_for_uuid uuid
214
215         if rsc == Job
216           job = @pdata[uuid]
217           gr += job_edges job if job
218         elsif rsc == ContainerRequest
219           cr = @pdata[uuid]
220           if cr
221             gr += cr_edges cr
222             gr += describe_node(uuid, {href: {controller: 'container_requests',
223                                               id: uuid},
224                                        label: @pdata[uuid][:name],
225                                        shape: 'oval'})
226             # Search for child CRs
227             if cr[:container_uuid]
228               child_crs = ContainerRequest.where(requesting_container_uuid: cr[:container_uuid])
229               child_crs.each do |child|
230                 gr += generate_provenance_edges(child[:uuid])
231                 gr += edge(uuid, child[:uuid], {label: 'child'})
232               end
233             end
234           end
235         end
236       end
237
238       @pdata.each do |k, link|
239         if link[:head_uuid] == uuid.to_s and link[:link_class] == "provenance"
240           href = url_for ({:controller => Link.to_s.tableize,
241                             :action => :show,
242                             :id => link[:uuid] })
243
244           gr += describe_node(link[:tail_uuid])
245           gr += edge(link[:head_uuid], link[:tail_uuid], {:label => link[:name], :href => href})
246           gr += generate_provenance_edges(link[:tail_uuid])
247         end
248       end
249
250       gr
251     end
252
253     def describe_jobs
254       gr = ""
255       @jobs.each do |k, v|
256         href = url_for ({:controller => Job.to_s.tableize,
257                           :action => :index })
258
259         gr += "\"#{k}\" [href=\"#{href}?"
260
261         n = 0
262         v.each do |u|
263           gr += ";" unless gr.end_with? "?"
264           gr += "uuid%5b%5d=#{u[:uuid]}"
265           n |= @opts[:pips][u[:uuid]] if @opts[:pips] and @opts[:pips][u[:uuid]]
266         end
267
268         gr += "\",label=\""
269
270         label = "#{v[0][:script]}"
271
272         if label == "run-command" and v[0][:script_parameters][:command].is_a? Array
273           label = v[0][:script_parameters][:command].join(' ')
274         end
275
276         if not @opts[:combine_jobs]
277           label += "\\n#{v[0][:finished_at]}"
278         end
279
280         gr += encode_quotes label
281
282         gr += "\",#{determine_fillcolor n}];\n"
283       end
284       gr
285     end
286
287     def encode_quotes value
288       value.to_s.gsub("\"", "\\\"").gsub("\n", "\\n")
289     end
290   end
291
292   def self.create_provenance_graph(pdata, svgId, opts={})
293     if pdata.is_a? Array or pdata.is_a? ArvadosResourceList
294       p2 = {}
295       pdata.each do |k|
296         p2[k[:uuid]] = k if k[:uuid]
297       end
298       pdata = p2
299     end
300
301     unless pdata.is_a? Hash
302       raise "create_provenance_graph accepts Array or Hash for pdata only, pdata is #{pdata.class}"
303     end
304
305     gr = """strict digraph {
306 node [fontsize=10,fontname=\"Helvetica,Arial,sans-serif\"];
307 edge [fontsize=10,fontname=\"Helvetica,Arial,sans-serif\"];
308 """
309
310     if opts[:direction] == :bottom_up
311       gr += "edge [dir=back];"
312     end
313
314     begin
315       pdata = pdata.stringify_keys
316
317       g = GenerateGraph.new(pdata, opts)
318
319       pdata.each do |k, v|
320         if !opts[:only_components] or k.start_with? "component_"
321           gr += g.generate_provenance_edges(k)
322         else
323           #gr += describe_node(k)
324         end
325       end
326
327       if !opts[:only_components]
328         gr += g.describe_jobs
329       end
330
331     rescue => e
332       Rails.logger.warn "#{e.inspect}"
333       Rails.logger.warn "#{e.backtrace.join("\n\t")}"
334       raise
335     end
336
337     gr += "}"
338     svg = ""
339
340     require 'open3'
341
342     Open3.popen2("dot", "-Tsvg") do |stdin, stdout, wait_thr|
343       stdin.print(gr)
344       stdin.close
345       svg = stdout.read()
346       wait_thr.value
347       stdout.close()
348     end
349
350     svg = svg.sub(/<\?xml.*?\?>/m, "")
351     svg = svg.sub(/<!DOCTYPE.*?>/m, "")
352     svg = svg.sub(/<svg /, "<svg id=\"#{svgId}\" ")
353   end
354
355   # yields hash, uuid
356   # Position indicates whether it is a content hash or arvados uuid.
357   # One will hold a value, the other will always be nil.
358   def self.find_collections(sp, key=nil, &b)
359     case sp
360     when ArvadosBase
361       sp.class.columns.each do |c|
362         find_collections(sp[c.name.to_sym], nil, &b)
363       end
364     when Hash
365       sp.each do |k, v|
366         find_collections(v, key || k, &b)
367       end
368     when Array
369       sp.each do |v|
370         find_collections(v, key, &b)
371       end
372     when String
373       if m = /[a-f0-9]{32}\+\d+/.match(sp)
374         yield m[0], nil, key
375       elsif m = /[0-9a-z]{5}-4zz18-[0-9a-z]{15}/.match(sp)
376         yield nil, m[0], key
377       end
378     end
379   end
380 end