665f3d542b88fbe63278607d1e042ba1143b3d7b
[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 col_name_for_project(col_pdh, project_uuid)
108       [
109         # Search for collections within the same project first.
110         {portable_data_hash: col_pdh, owner_uuid: project_uuid},
111         # then, earch for collections in any project.
112         {portable_data_hash: col_pdh},
113       ].each do |query_args|
114         col = Collection.where(query_args).limit(1)
115         if col.results.any?
116           if col.items_available == 1
117             return col.results.first.name
118           else
119             return "#{col.results.first.name} + #{col.items_available - 1} more"
120           end
121         end
122       end
123
124       # No collections found with this pdh
125       col_pdh
126     end
127
128     def cr_edges cr
129       uuid = cr[:uuid]
130       gr = ""
131
132       # Search for input mounts
133       input_obj = cr[:mounts].andand[:"/var/lib/cwl/cwl.input.json"].andand[:content] || cr[:mounts] || {}
134       if input_obj
135         ProvenanceHelper::find_collections input_obj, 'input' do |col_hash, col_uuid, key|
136           # Only include input PDHs
137           if col_hash
138             gr += describe_node(col_hash,
139                                 {label: col_name_for_project(col_hash, cr[:owner_uuid])})
140             gr += edge(col_hash, uuid, {:label => key})
141           end
142         end
143       end
144
145       # Add CR outputs by PDH so they connect with the child CR's inputs.
146       if cr[:output_uuid]
147         output_pdh = Collection.find(cr[:output_uuid])[:portable_data_hash]
148         if output_pdh
149           gr += describe_node(output_pdh,
150                               {label: col_name_for_project(output_pdh, cr[:owner_uuid])})
151           gr += edge(uuid, output_pdh, {label: 'output'})
152         end
153       end
154
155       gr
156     end
157
158     def job_edges job, edge_opts={}
159       uuid = job_uuid(job)
160       gr = ""
161
162       ProvenanceHelper::find_collections job[:script_parameters] do |collection_hash, collection_uuid, key|
163         if collection_uuid
164           gr += describe_node(collection_uuid)
165           gr += edge(collection_uuid, uuid, {:label => key})
166         else
167           gr += describe_node(collection_hash)
168           gr += edge(collection_hash, uuid, {:label => key})
169         end
170       end
171
172       if job[:docker_image_locator] and !@opts[:no_docker]
173         gr += describe_node(job[:docker_image_locator], {label: (job[:runtime_constraints].andand[:docker_image] || job[:docker_image_locator])})
174         gr += edge(job[:docker_image_locator], uuid, {label: "docker_image"})
175       end
176
177       if @opts[:script_version_nodes]
178         gr += describe_node(job[:script_version], {:label => "git:#{job[:script_version]}"})
179         gr += edge(job[:script_version], uuid, {:label => "script_version"})
180       end
181
182       if job[:output] and !edge_opts[:no_output]
183         gr += describe_node(job[:output])
184         gr += edge(uuid, job[:output], {label: "output" })
185       end
186
187       if job[:log] and !edge_opts[:no_log]
188         gr += describe_node(job[:log])
189         gr += edge(uuid, job[:log], {label: "log"})
190       end
191
192       gr
193     end
194
195     def generate_provenance_edges(uuid)
196       gr = ""
197       m = GenerateGraph::collection_uuid(uuid)
198       uuid = m if m
199
200       if uuid.nil? or uuid.empty? or @visited[uuid]
201         return ""
202       end
203
204       if @pdata[uuid].nil?
205         return ""
206       else
207         @visited[uuid] = true
208       end
209
210       if uuid.start_with? "component_"
211         # Pipeline component inputs
212         job = @pdata[@pdata[uuid][:job].andand[:uuid]]
213
214         if job
215           gr += describe_node(job_uuid(job), {label: uuid[38..-1], pip: @opts[:pips].andand[job[:uuid]], shape: "oval",
216                                 href: {controller: 'jobs', id: job[:uuid]}})
217           gr += job_edges job, {no_output: true, no_log: true}
218         end
219
220         # Pipeline component output
221         outuuid = @pdata[uuid][:output_uuid]
222         if outuuid
223           outcollection = @pdata[outuuid]
224           if outcollection
225             gr += edge(job_uuid(job), outcollection[:portable_data_hash], {label: "output"})
226             gr += describe_node(outcollection[:portable_data_hash], {label: outcollection[:name]})
227           end
228         elsif job and job[:output]
229           gr += describe_node(job[:output])
230           gr += edge(job_uuid(job), job[:output], {label: "output" })
231         end
232       else
233         rsc = ArvadosBase::resource_class_for_uuid uuid
234
235         if rsc == Job
236           job = @pdata[uuid]
237           gr += job_edges job if job
238         elsif rsc == ContainerRequest
239           cr = @pdata[uuid]
240           if cr
241             gr += cr_edges cr
242             gr += describe_node(uuid, {href: {controller: 'container_requests',
243                                               id: uuid},
244                                        label: @pdata[uuid][:name],
245                                        shape: 'oval'})
246             # Search for child CRs
247             if cr[:container_uuid]
248               child_crs = ContainerRequest.where(requesting_container_uuid: cr[:container_uuid])
249               child_crs.each do |child|
250                 gr += generate_provenance_edges(child[:uuid])
251                 gr += edge(child[:uuid], uuid, {label: 'child'})
252               end
253             end
254           end
255         end
256       end
257
258       @pdata.each do |k, link|
259         if link[:head_uuid] == uuid.to_s and link[:link_class] == "provenance"
260           href = url_for ({:controller => Link.to_s.tableize,
261                             :action => :show,
262                             :id => link[:uuid] })
263
264           gr += describe_node(link[:tail_uuid])
265           gr += edge(link[:head_uuid], link[:tail_uuid], {:label => link[:name], :href => href})
266           gr += generate_provenance_edges(link[:tail_uuid])
267         end
268       end
269
270       gr
271     end
272
273     def describe_jobs
274       gr = ""
275       @jobs.each do |k, v|
276         href = url_for ({:controller => Job.to_s.tableize,
277                           :action => :index })
278
279         gr += "\"#{k}\" [href=\"#{href}?"
280
281         n = 0
282         v.each do |u|
283           gr += ";" unless gr.end_with? "?"
284           gr += "uuid%5b%5d=#{u[:uuid]}"
285           n |= @opts[:pips][u[:uuid]] if @opts[:pips] and @opts[:pips][u[:uuid]]
286         end
287
288         gr += "\",label=\""
289
290         label = "#{v[0][:script]}"
291
292         if label == "run-command" and v[0][:script_parameters][:command].is_a? Array
293           label = v[0][:script_parameters][:command].join(' ')
294         end
295
296         if not @opts[:combine_jobs]
297           label += "\\n#{v[0][:finished_at]}"
298         end
299
300         gr += encode_quotes label
301
302         gr += "\",#{determine_fillcolor n}];\n"
303       end
304       gr
305     end
306
307     def encode_quotes value
308       value.to_s.gsub("\"", "\\\"").gsub("\n", "\\n")
309     end
310   end
311
312   def self.create_provenance_graph(pdata, svgId, opts={})
313     if pdata.is_a? Array or pdata.is_a? ArvadosResourceList
314       p2 = {}
315       pdata.each do |k|
316         p2[k[:uuid]] = k if k[:uuid]
317       end
318       pdata = p2
319     end
320
321     unless pdata.is_a? Hash
322       raise "create_provenance_graph accepts Array or Hash for pdata only, pdata is #{pdata.class}"
323     end
324
325     gr = """strict digraph {
326 node [fontsize=10,fontname=\"Helvetica,Arial,sans-serif\"];
327 edge [fontsize=10,fontname=\"Helvetica,Arial,sans-serif\"];
328 """
329
330     if opts[:direction] == :bottom_up
331       gr += "edge [dir=back];"
332     end
333
334     begin
335       pdata = pdata.stringify_keys
336
337       g = GenerateGraph.new(pdata, opts)
338
339       pdata.each do |k, v|
340         if !opts[:only_components] or k.start_with? "component_"
341           gr += g.generate_provenance_edges(k)
342         else
343           #gr += describe_node(k)
344         end
345       end
346
347       if !opts[:only_components]
348         gr += g.describe_jobs
349       end
350
351     rescue => e
352       Rails.logger.warn "#{e.inspect}"
353       Rails.logger.warn "#{e.backtrace.join("\n\t")}"
354       raise
355     end
356
357     gr += "}"
358     svg = ""
359
360     require 'open3'
361
362     Open3.popen2("dot", "-Tsvg") do |stdin, stdout, wait_thr|
363       stdin.print(gr)
364       stdin.close
365       svg = stdout.read()
366       wait_thr.value
367       stdout.close()
368     end
369
370     svg = svg.sub(/<\?xml.*?\?>/m, "")
371     svg = svg.sub(/<!DOCTYPE.*?>/m, "")
372     svg = svg.sub(/<svg /, "<svg id=\"#{svgId}\" ")
373   end
374
375   # yields hash, uuid
376   # Position indicates whether it is a content hash or arvados uuid.
377   # One will hold a value, the other will always be nil.
378   def self.find_collections(sp, key=nil, &b)
379     case sp
380     when ArvadosBase
381       sp.class.columns.each do |c|
382         find_collections(sp[c.name.to_sym], nil, &b)
383       end
384     when Hash
385       sp.each do |k, v|
386         find_collections(v, key || k, &b)
387       end
388     when Array
389       sp.each do |v|
390         find_collections(v, key, &b)
391       end
392     when String
393       if m = /[a-f0-9]{32}\+\d+/.match(sp)
394         yield m[0], nil, key
395       elsif m = /[0-9a-z]{5}-4zz18-[0-9a-z]{15}/.match(sp)
396         yield nil, m[0], key
397       end
398     end
399   end
400 end