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