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