20259: Add documentation for banner and tooltip features
[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 cr_edges cont, edge_opts={}
155       uuid = cont[:uuid]
156       gr = ""
157
158       gr += describe_node(cont[:uuid], {href: {controller: 'container_requests',
159                                              id: cont[:uuid]},
160                                         shape: 'oval',
161                                         label: cont[:name]})
162
163       ProvenanceHelper::find_collections cont[:mounts] do |collection_hash, collection_uuid, key|
164         if @opts[:pdh_to_uuid] and @opts[:pdh_to_uuid][collection_hash]
165           collection_uuid = @opts[:pdh_to_uuid][collection_hash].uuid
166           collection_hash = nil
167         end
168         if collection_uuid and @pdata[collection_uuid]
169           gr += describe_node(collection_uuid)
170           gr += edge(collection_uuid, uuid, {:label => key})
171         elsif collection_hash and @pdata[collection_hash]
172           gr += describe_node(collection_hash)
173           gr += edge(collection_hash, uuid, {:label => key})
174         end
175       end
176
177       if cont[:container_image] and !@opts[:no_docker] and @pdata[cont[:container_image]]
178         gr += describe_node(cont[:container_image], {label: cont[:container_image]})
179         gr += edge(cont[:container_image], uuid, {label: "docker_image"})
180       end
181
182       if cont[:output_uuid] and !edge_opts[:no_output] and @pdata[cont[:output_uuid]]
183         gr += describe_node(cont[:output_uuid])
184         gr += edge(uuid, cont[:output_uuid], {label: "output" })
185       end
186
187       if cont[:log_uuid] and !edge_opts[:no_log] and @pdata[cont[:log_uuid]]
188         gr += describe_node(cont[:log_uuid])
189         gr += edge(uuid, cont[:log_uuid], {label: "log"})
190       end
191
192       gr
193     end
194
195     def container_edges cont, edge_opts={}
196       uuid = cont[:uuid]
197       gr = ""
198
199       gr += describe_node(cont[:uuid], {href: {controller: 'containers',
200                                              id: cont[:uuid]},
201                                       shape: 'oval'})
202
203       ProvenanceHelper::find_collections cont[:mounts] do |collection_hash, collection_uuid, key|
204         if collection_uuid and @pdata[collection_uuid]
205           gr += describe_node(collection_uuid)
206           gr += edge(collection_uuid, uuid, {:label => key})
207         elsif collection_hash and @pdata[collection_hash]
208           gr += describe_node(collection_hash)
209           gr += edge(collection_hash, uuid, {:label => key})
210         end
211       end
212
213       if cont[:container_image] and !@opts[:no_docker] and @pdata[cont[:container_image]]
214         gr += describe_node(cont[:container_image], {label: cont[:container_image]})
215         gr += edge(cont[:container_image], uuid, {label: "docker_image"})
216       end
217
218       if cont[:output] and !edge_opts[:no_output] and @pdata[cont[:output]]
219         gr += describe_node(cont[:output])
220         gr += edge(uuid, cont[:output], {label: "output" })
221       end
222
223       if cont[:log] and !edge_opts[:no_log] and @pdata[cont[:log]]
224         gr += describe_node(cont[:log])
225         gr += edge(uuid, cont[:log], {label: "log"})
226       end
227
228       gr
229     end
230
231     def generate_provenance_edges(uuid)
232       gr = ""
233       m = GenerateGraph::collection_uuid(uuid)
234       uuid = m if m
235
236       if uuid.nil? or uuid.empty? or @visited[uuid]
237         return ""
238       end
239
240       if @pdata[uuid].nil?
241         return ""
242       else
243         @visited[uuid] = true
244       end
245
246       if uuid.start_with? "component_"
247         # Pipeline component inputs
248         job = @pdata[@pdata[uuid][:job].andand[:uuid]]
249
250         if job
251           gr += describe_node(job_uuid(job), {label: uuid[38..-1], pip: @opts[:pips].andand[job[:uuid]], shape: "oval",
252                                 href: {controller: 'jobs', id: job[:uuid]}})
253           gr += job_edges job, {no_output: true, no_log: true}
254         end
255
256         # Pipeline component output
257         outuuid = @pdata[uuid][:output_uuid]
258         if outuuid
259           outcollection = @pdata[outuuid]
260           if outcollection
261             gr += edge(job_uuid(job), outcollection[:portable_data_hash], {label: "output"})
262             gr += describe_node(outcollection[:portable_data_hash], {label: outcollection[:name]})
263           end
264         elsif job and job[:output]
265           gr += describe_node(job[:output])
266           gr += edge(job_uuid(job), job[:output], {label: "output" })
267         end
268       else
269         rsc = ArvadosBase::resource_class_for_uuid uuid
270
271         if rsc == Job
272           job = @pdata[uuid]
273           gr += job_edges job if job
274         elsif rsc == ContainerRequest
275           cr = @pdata[uuid]
276           gr += cr_edges cr if cr
277         elsif rsc == Container
278           cr = @pdata[uuid]
279           gr += container_edges cr if cr
280         end
281       end
282
283       @pdata.each do |k, link|
284         if link[:head_uuid] == uuid.to_s and link[:link_class] == "provenance"
285           href = url_for ({:controller => Link.to_s.tableize,
286                             :action => :show,
287                             :id => link[:uuid] })
288
289           gr += describe_node(link[:tail_uuid])
290           gr += edge(link[:head_uuid], link[:tail_uuid], {:label => link[:name], :href => href})
291           gr += generate_provenance_edges(link[:tail_uuid])
292         end
293       end
294
295       gr
296     end
297
298     def describe_jobs
299       gr = ""
300       @jobs.each do |k, v|
301         href = url_for ({:controller => Job.to_s.tableize,
302                           :action => :index })
303
304         gr += "\"#{k}\" [href=\"#{href}?"
305
306         n = 0
307         v.each do |u|
308           gr += ";" unless gr.end_with? "?"
309           gr += "uuid%5b%5d=#{u[:uuid]}"
310           n |= @opts[:pips][u[:uuid]] if @opts[:pips] and @opts[:pips][u[:uuid]]
311         end
312
313         gr += "\",label=\""
314
315         label = "#{v[0][:script]}"
316
317         if label == "run-command" and v[0][:script_parameters][:command].is_a? Array
318           label = v[0][:script_parameters][:command].join(' ')
319         end
320
321         if not @opts[:combine_jobs]
322           label += "\\n#{v[0][:finished_at]}"
323         end
324
325         gr += encode_quotes label
326
327         gr += "\",#{determine_fillcolor n}];\n"
328       end
329       gr
330     end
331
332     def encode_quotes value
333       value.to_s.gsub("\"", "\\\"").gsub("\n", "\\n")
334     end
335   end
336
337   def self.create_provenance_graph(pdata, svgId, opts={})
338     if pdata.is_a? Array or pdata.is_a? ArvadosResourceList
339       p2 = {}
340       pdata.each do |k|
341         p2[k[:uuid]] = k if k[:uuid]
342       end
343       pdata = p2
344     end
345
346     unless pdata.is_a? Hash
347       raise "create_provenance_graph accepts Array or Hash for pdata only, pdata is #{pdata.class}"
348     end
349
350     gr = """strict digraph {
351 node [fontsize=10,fontname=\"Helvetica,Arial,sans-serif\"];
352 edge [fontsize=10,fontname=\"Helvetica,Arial,sans-serif\"];
353 """
354     if ["LR", "RL"].include? opts[:direction]
355       gr += "rankdir=#{opts[:direction]};"
356     end
357
358     begin
359       pdata = pdata.stringify_keys
360
361       g = GenerateGraph.new(pdata, opts)
362
363       pdata.each do |k, v|
364         if !opts[:only_components] or k.start_with? "component_"
365           gr += g.generate_provenance_edges(k)
366         else
367           #gr += describe_node(k)
368         end
369       end
370
371       if !opts[:only_components]
372         gr += g.describe_jobs
373       end
374
375     rescue => e
376       Rails.logger.warn "#{e.inspect}"
377       Rails.logger.warn "#{e.backtrace.join("\n\t")}"
378       raise
379     end
380
381     gr += "}"
382     svg = ""
383
384     require 'open3'
385
386     Open3.popen2("dot", "-Tsvg") do |stdin, stdout, wait_thr|
387       stdin.print(gr)
388       stdin.close
389       svg = stdout.read()
390       wait_thr.value
391       stdout.close()
392     end
393
394     svg = svg.sub(/<\?xml.*?\?>/m, "")
395     svg = svg.sub(/<!DOCTYPE.*?>/m, "")
396     svg = svg.sub(/<svg /, "<svg id=\"#{svgId}\" ")
397   end
398
399   # yields hash, uuid
400   # Position indicates whether it is a content hash or arvados uuid.
401   # One will hold a value, the other will always be nil.
402   def self.find_collections(sp, key=nil, &b)
403     case sp
404     when ArvadosBase
405       sp.class.columns.each do |c|
406         find_collections(sp[c.name.to_sym], nil, &b)
407       end
408     when Hash
409       sp.each do |k, v|
410         find_collections(v, key || k, &b)
411       end
412     when Array
413       sp.each do |v|
414         find_collections(v, key, &b)
415       end
416     when String
417       if m = /[a-f0-9]{32}\+\d+/.match(sp)
418         yield m[0], nil, key
419       elsif m = /[0-9a-z]{5}-4zz18-[0-9a-z]{15}/.match(sp)
420         yield nil, m[0], key
421       end
422     end
423   end
424
425   def self.cr_input_pdhs cr
426     pdhs = []
427     input_obj = cr[:mounts].andand[:"/var/lib/cwl/cwl.input.json"].andand[:content] || cr[:mounts]
428     if input_obj
429       find_collections input_obj do |col_hash, col_uuid, key|
430         if col_hash
431           pdhs << col_hash
432         end
433       end
434     end
435     pdhs
436   end
437 end