summaryrefslogtreecommitdiff
path: root/doc/invocations-http-server/server.py
blob: f9f57aff44eedc4461c94bf0dc1e88d29685cd2d (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
#!/usr/bin/env python3
# Copyright 2025 Huawei Cloud Computing Technology Co., Ltd.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

import jinja2
import json
import re
import os
import subprocess
import werkzeug.exceptions
import werkzeug.routing
import werkzeug.utils

from werkzeug.wrappers import Request, Response
from werkzeug.middleware.shared_data import SharedDataMiddleware
from functools import cache

def core_config(conf):
    new_conf = {}
    for k, v in conf.items():
        if v is not None:
            new_conf[k] = v
    return new_conf

class HexIdentifierConverter(werkzeug.routing.BaseConverter):
    regex = '[a-zA-Z0-9]{2,300}'

class HashIdentifierConverter(werkzeug.routing.BaseConverter):
    regex = '[a-zA-Z0-9]{40,64}'

class InvocationIdentifierConverter(werkzeug.routing.BaseConverter):
    regex = '[-:_a-zA-Z0-9]{1,200}'

class FileIdentifierConverter(werkzeug.routing.BaseConverter):
    regex = '[-:_.a-zA-Z0-9]{3,200}'

class InvocationServer:
    MAX_FULL_INVOCATIONS = 50
    MAX_REDUCED_INVOCATIONS = 450

    def __init__(self, logsdir, *,
                 just_mr = None,
                 graph = "graph.json",
                 artifacts = "artifacts.json",
                 artifacts_to_build = "to-build.json",
                 profile = "profile.json",
                 meta = "meta.json"):
        self.logsdir = logsdir
        if just_mr is None:
            self.just_mr = ["just-mr"]
        else:
            self.just_mr = just_mr
        self.profile = profile
        self.graph = graph
        self.artifacts = artifacts
        self.artifacts_to_build = artifacts_to_build
        self.meta = meta
        self.templatepath = os.path.join(os.path.dirname(__file__), "templates")
        self.jinjaenv = jinja2.Environment(
                loader=jinja2.FileSystemLoader(self.templatepath))
        rule = werkzeug.routing.Rule
        self.routingmap = werkzeug.routing.Map([
            rule("/", methods=("GET",), endpoint="list_invocations"),
            rule("/filterinvocations/context/<hexidentifier:key>/<hexidentifier:value>",
                 methods=("GET",), endpoint="filter_context"),
            rule("/filterinvocations/noncached",
                 methods=("GET",), endpoint="filter_noncached"),
            rule("/filterinvocations/remote/prop/<hexidentifier:key>/<hexidentifier:value>",
                 methods=("GET",), endpoint="filter_remote_prop"),
            rule("/filterinvocations/remote/address/<hexidentifier:value>",
                 methods=("GET",), endpoint="filter_remote_address"),
            rule("/filterinvocations/target/<hexidentifier:value>",
                 methods=("GET",), endpoint="filter_target"),
            rule("/blob/<hashidentifier:blob>",
                 methods=("GET",),
                 endpoint="get_blob"),
            rule("/blob/<hashidentifier:blob>/<fileidentifier:name>",
                 methods=("GET",),
                 endpoint="get_blob_as"),
            rule("/tree/<hashidentifier:tree>",
                 methods=("GET",),
                 endpoint="get_tree"),
            rule("/invocations/<invocationidentifier:invocation>",
                 methods=("GET",),
                 endpoint="get_invocation"),
            rule("/critical_path/<invocationidentifier:invocation>",
                 methods=("GET",),
                 endpoint="get_critical_path"),
        ], converters=dict(
            invocationidentifier=InvocationIdentifierConverter,
            hashidentifier=HashIdentifierConverter,
            hexidentifier=HexIdentifierConverter,
            fileidentifier=FileIdentifierConverter,
        ))

    @Request.application
    def __call__(self, request):
        mapadapter = self.routingmap.bind_to_environ(request.environ)
        try:
            endpoint, args = mapadapter.match()
            return getattr(self, "do_%s" % (endpoint,))(**args)
        except werkzeug.exceptions.HTTPException as e:
            return e

    def render(self, templatename, params):
        response = Response()
        response.content_type = "text/html; charset=utf8"
        template = self.jinjaenv.get_template(templatename)
        response.data = template.render(params).encode("utf8")
        return response

    def do_list_invocations(self, *,
                            filter_info="",
                            profile_filter = lambda p : True,
                            metadata_filter = lambda p : True):
        entries = sorted(os.listdir(self.logsdir), reverse=True)
        context_filters = {}
        remote_props_filters = {}
        remote_address_filters = set()
        target_filters = set()
        def add_filter(data, filters):
            if isinstance(filters, set):
                filters.add(json.dumps(data))
            elif isinstance(filters, dict):
                for k, v in data.items():
                    key = json.dumps(k)
                    value = json.dumps(v)
                    if key not in filters:
                        filters[key] = set()
                    filters[key].add(value)

        # Load full invocation data (profile data + metadata).
        index = 0
        full_invocations = []
        full_invocations_count = 0
        while index < len(entries):
            e = entries[index]
            index += 1
            profile = os.path.join(self.logsdir, e, self.profile)
            if not os.path.exists(profile):
                # only consider invocations that provide a profile; unfinished
                # invocations as well as not build related ones (like
                # install-cas) are not relevant.
                continue
            try:
                with open(profile) as f:
                    profile_data = json.load(f)
            except:
                profile_data = {}

            meta = os.path.join(self.logsdir, e, self.meta)
            try:
                with open(meta) as f:
                    meta_data = json.load(f)
            except:
                meta_data = {}

            if (not profile_filter(profile_data)) or (not metadata_filter(meta_data)):
                continue
            full_invocations_count += 1
            target = profile_data.get("target")
            build_start_time = profile_data.get("build start time")
            build_stop_time = profile_data.get("build stop time")
            stop_time = profile_data.get("stop time")
            build_wall_clock_time = build_stop_time - build_start_time if (build_start_time is not None and build_stop_time is not None) else None
            config = core_config(profile_data.get("configuration", {}))
            context = meta_data.get("context", {})
            remote = profile_data.get('remote', {})
            remote_props = remote.get('properties', {})
            remote_address = remote.get('address')
            add_filter(context, context_filters)
            add_filter(remote_props, remote_props_filters)
            add_filter(remote_address, remote_address_filters)
            add_filter(target, target_filters)
            invocation = {
                "name": e,
                "subcommand": profile_data.get("subcommand"),
                "target": json.dumps(target) if target else None,
                "config": json.dumps(config) if config else None,
                "context": json.dumps(context) if context else None,
                "build_wall_clock_time": "%5ds" % (build_wall_clock_time,) if build_wall_clock_time else None,
                "exit_code": profile_data.get('exit code', 0),
                "remote_address": remote_address,
                "remote_props": json.dumps(remote_props) if remote_props else None,
            }
            full_invocations.append(invocation)
            if full_invocations_count >= InvocationServer.MAX_FULL_INVOCATIONS:
                break

        # Load reduced invocation data (metadata only).
        reduced_invocations = []
        reduced_invocations_count = 0
        if not filter_info:
            while index < len(entries):
                e = entries[index]
                index += 1
                profile = os.path.join(self.logsdir, e, self.profile)
                if not os.path.exists(profile):
                    # only consider invocations that provide a profile; unfinished
                    # invocations as well as not build related ones (like
                    # install-cas) are not relevant.
                    continue
                meta = os.path.join(self.logsdir, e, self.meta)
                try:
                    with open(meta) as f:
                        meta_data = json.load(f)
                except:
                    meta_data = {}
                reduced_invocations_count += 1
                context = meta_data.get("context", {})
                add_filter(context, context_filters)
                invocation = {
                    "name": e,
                    "context": json.dumps(context) if context else None,
                }
                reduced_invocations.append(invocation)
                if reduced_invocations_count >= InvocationServer.MAX_REDUCED_INVOCATIONS:
                    break

        def convert_filters(filters):
            def convert_values(values):
                return sorted([{
                    "value": v,
                    "value_hex": v.encode().hex(),
                } for v in values], key=lambda x: x["value"])
            if isinstance(filters, set):
                return convert_values(filters) if len(filters) > 1 else []
            elif isinstance(filters, dict):
                return sorted([{
                    "key": key,
                    "key_hex": key.encode().hex(),
                    "values": convert_values(values)
                } for key, values in filters.items() if len(values) > 1], key=lambda x: x["key"])
            else:
                return []

        return self.render("invocations.html",
                           {"full_invocations": full_invocations,
                            "full_invocations_count": full_invocations_count,
                            "reduced_invocations": reduced_invocations,
                            "reduced_invocations_count": reduced_invocations_count,
                            "filter_info": filter_info,
                            "context_filters": convert_filters(context_filters),
                            "remote_props_filters": convert_filters(remote_props_filters),
                            "remote_address_filters": convert_filters(remote_address_filters),
                            "target_filters": convert_filters(target_filters)})

    def do_filter_remote_prop(self, key, value):
        filter_info = "remote-execution property"
        try:
            key_string = json.loads(bytes.fromhex(key).decode('utf-8'))
            value_string = json.loads(bytes.fromhex(value).decode('utf-8'))
            filter_info += " " + json.dumps({key_string: value_string})
        except:
            pass

        def check_prop(p):
            for k, v in p.get('remote', {}).get('properties', {}).items():
                if (json.dumps(k).encode().hex() == key) and (json.dumps(v).encode().hex() == value):
                    return True
            return False

        return self.do_list_invocations(
            filter_info = filter_info,
            profile_filter = check_prop,
        )

    def do_filter_remote_address(self, value):
        filter_info = "remote address"
        try:
            value_string = json.loads(bytes.fromhex(value).decode('utf-8'))
            filter_info += " " + json.dumps(value_string)
        except:
            pass

        def check_prop(p):
            v = p.get('remote', {}).get('address')
            return (json.dumps(v).encode().hex() == value)

        return self.do_list_invocations(
            filter_info = filter_info,
            profile_filter = check_prop,
        )

    def do_filter_context(self, key, value):
        filter_info = "context variable"
        try:
            key_string = json.loads(bytes.fromhex(key).decode('utf-8'))
            value_string = json.loads(bytes.fromhex(value).decode('utf-8'))
            filter_info += " " + json.dumps({key_string: value_string})
        except:
            pass

        def check_prop(p):
            for k, v in p.get('context', {}).items():
                if (json.dumps(k).encode().hex() == key) and (json.dumps(v).encode().hex() == value):
                    return True
            return False

        return self.do_list_invocations(
            filter_info = filter_info,
            metadata_filter = check_prop,
        )

    def do_filter_target(self, value):
        filter_info = "target"
        try:
            value_string = json.loads(bytes.fromhex(value).decode('utf-8'))
            filter_info += " " + json.dumps(value_string)
        except:
            pass

        def check_prop(p):
            v = p.get('target')
            return (json.dumps(v).encode().hex() == value)

        return self.do_list_invocations(
            filter_info = filter_info,
            profile_filter = check_prop,
        )

    def do_filter_noncached(self):
        def check_noncached(p):
            for v in p.get('actions', {}).values():
                if not v.get('cached'):
                    return True
            return False
        return self.do_list_invocations(
            filter_info = "not fully cached",
            profile_filter = check_noncached,
        )

    def process_failure(self, cmd, procobj, *, failure_kind=None):
        params = {"stdout": None, "stderr": None, "failure_kind": failure_kind}
        params["cmd"] = json.dumps(cmd)
        params["exit_code"] = procobj.returncode
        try:
            params["stdout"] = procobj.stdout.decode('utf-8')
        except:
            pass
        try:
            params["stderr"] = procobj.stderr.decode('utf-8')
        except:
            pass
        return self.render("failure.html", params)

    def do_get_blob(self, blob, *, download_as=None):
        cmd = self.just_mr + ["install-cas", "--remember", blob]
        blob_data = subprocess.run(cmd,
                                   stdout=subprocess.PIPE,
                                   stderr=subprocess.PIPE)
        if blob_data.returncode !=0:
            return self.process_failure(cmd, blob_data)
        try:
            blob_content = blob_data.stdout.decode('utf-8')
        except:
            # Not utf-8, so return as binary file to download separately
            download_as = download_as or blob
        if download_as:
            response = Response()
            response.content_type = "application/octet-stream"
            response.data = blob_data.stdout
            response.headers['Content-Disposition'] = \
                "attachement; filename=%s" %(download_as,)
            return response
        return self.render("blob.html",
                           {"name": blob,
                            "data": blob_content})

    def do_get_blob_as(self, blob, name):
        return self.do_get_blob(blob, download_as=name)

    def do_get_tree(self, tree):
        cmd = self.just_mr + ["install-cas", "%s::t" % (tree,)]
        tree_data = subprocess.run(cmd,
                                   stdout=subprocess.PIPE,
                                   stderr=subprocess.PIPE)
        if tree_data.returncode !=0:
            return self.process_failure(cmd, tree_data)
        try:
            tree_info = json.loads(tree_data.stdout.decode('utf-8'))
        except Exception as e:
            return self.process_failure(
                cmd, tree_data,
                failure_kind = "Malformed output: %s" % (e,))

        entries = []
        for k, v in tree_info.items():
            h, s, t = v.strip('[]').split(':')
            entries.append({"path": k,
                            "hash": h,
                            "type": "tree" if t == 't' else "blob"})
        return self.render("tree.html", {"name": tree,
                                         "entries": entries})

    def do_get_invocation(self, invocation):
        params = {"invocation": invocation,
                  "have_profile": False}

        try:
            with open(os.path.join(
                    self.logsdir, invocation, self.profile)) as f:
                profile = json.load(f)
                params["have_profile"] = True
        except:
            profile = {}

        try:
            with open(os.path.join(
                    self.logsdir, invocation, self.meta)) as f:
                meta = json.load(f)
        except:
            meta = {}

        try:
            with open(os.path.join(
                    self.logsdir, invocation, self.graph)) as f:
                graph = json.load(f)
        except:
            graph = {}

        try:
            with open(os.path.join(
                    self.logsdir, invocation, self.artifacts)) as f:
                artifacts = json.load(f)
        except:
            artifacts = {}

        params["repo_config"] = meta.get('configuration')
        params["exit_code"] = profile.get('exit code')
        analysis_errors = []
        blob_pattern = re.compile(r'blob ([0-9A-Za-z]{40,64})')
        for s in profile.get('analysis errors', []):
            analysis_errors.append({
                "msg": s,
                "blobs": blob_pattern.findall(s),
            })
        params["analysis_errors"] = analysis_errors
        params["has_remote"] = profile.get('remote') is not None
        remote_address = profile.get('remote', {}).get('address')
        params["is_remote"] = remote_address is not None
        params["remote_address"] = {
            "value": json.dumps(remote_address),
            "value_hex": json.dumps(remote_address).encode().hex(),
        }
        remote_props = []
        for k, v in profile.get('remote', {}).get('properties', {}).items():
            key = json.dumps(k)
            value = json.dumps(v)
            remote_props.append({
                "key": key,
                "key_hex": key.encode().hex(),
                "value": value,
                "value_hex": value.encode().hex(),
            })
        params["remote_props"] = remote_props
        remote_dispatch = profile.get('remote', {}).get('dispatch', [])
        params["remote_dispatch"] = json.dumps(remote_dispatch) if remote_dispatch else None
        # For complex conditional data fill with None as default
        for k in ["cmdline", "cmd", "target", "config"]:
            params[k] = None
        # Fill this data, if available
        if meta.get('cmdline'):
            params["cmdline"] = json.dumps(meta.get('cmdline'))
        context = []
        for k, v in meta.get('context', {}).items():
            key = json.dumps(k)
            value = json.dumps(v)
            context.append({
                "key": key,
                "key_hex": key.encode().hex(),
                "value": value,
                "value_hex": value.encode().hex(),
            })
        params["context"] = context
        if profile.get('subcommand'):
            params["cmd"] = json.dumps(
                [profile.get('subcommand')] + profile.get('subcommand args', []))
        target = profile.get('target')
        if target:
            params["target"] = {
                "value": json.dumps(target),
                "value_hex": json.dumps(target).encode().hex()
            }
        if profile.get('configuration') is not None:
            params["config"] = json.dumps(core_config(
                profile.get('configuration')))

        output_artifacts = []
        for k, v in artifacts.items():
            output_artifacts.append({
                "path": k,
                "basename": os.path.basename(k),
                "hash": v["id"],
                "type": "tree" if v["file_type"] == "t" else "blob",
            })
        params["artifacts"] = output_artifacts
        params["artifacts_count"] = len(output_artifacts)

        actions_considered = set()
        failed_build_actions = []
        failed_test_actions = []
        for k, v in profile.get('actions', {}).items():
            if v.get('exit code', 0) != 0:
                actions_considered.add(k)
                if graph.get('actions', {}).get(k, {}).get('may_fail') != None:
                    failed_test_actions.append(action_data(k, v, graph))
                else:
                    failed_build_actions.append(action_data(k, v, graph))
        params["failed_actions"] = failed_build_actions + failed_test_actions
        params["failed_actions_count"] = len(params["failed_actions"])

        # non-failed actions with output
        output_actions = []
        for k, v in profile.get('actions', {}).items():
            if k not in actions_considered:
               if v.get('stdout') or v.get('stderr'):
                   actions_considered.add(k)
                   output_actions.append(action_data(k, v, graph))
        params["output_actions"] = output_actions
        params["output_actions_count"] = len(output_actions)

        # longest running non-cached non-failed actions without output
        candidates = []
        action_count = 0
        action_count_cached = 0
        for k, v in profile.get('actions', {}).items():
            action_count += 1
            if not v.get('cached'):
                if k not in actions_considered:
                    candidates.append((v.get('duration', 0.0), k, v))
            else:
                action_count_cached += 1
        params["action_count"] = action_count
        params["action_count_cached"] = action_count_cached
        params["fully_cached"] = (action_count == action_count_cached)
        candidates.sort(reverse=True)
        non_cached = []
        params["more_noncached"] = None
        if len(candidates) > 30:
            params["more_non_cached"] = len(candidates) - 30
            candidates = candidates[:30]
        for t, k, v in candidates:
            action = action_data(k, v, graph)
            action["name_prefix"] = "%5.1fs" % (t,)
            non_cached.append(action)
        params["non_cached"] = non_cached
        params["non_cached_count"] = len(non_cached)
        start_time = profile.get("start time")
        build_start_time = profile.get("build start time")
        build_stop_time = profile.get("build stop time")
        stop_time = profile.get("stop time")
        wall_clock_time = stop_time - start_time if (start_time is not None and stop_time is not None) else None
        build_wall_clock_time = build_stop_time - build_start_time if (build_start_time is not None and build_stop_time is not None) else None
        params["wall_clock_time"] = "%ds" % (wall_clock_time,) if wall_clock_time else None
        params["build_wall_clock_time"] = "%ds" % (build_wall_clock_time,) if build_wall_clock_time else None

        return self.render("invocation.html", params)

    def do_get_critical_path(self, invocation):
        params = {"invocation": invocation}

        try:
            with open(os.path.join(
                    self.logsdir, invocation, self.profile)) as f:
                profile = json.load(f)
        except:
            profile = {}

        try:
            with open(os.path.join(
                    self.logsdir, invocation, self.graph)) as f:
                graph = json.load(f)
        except:
            graph = {}

        try:
            with open(os.path.join(
                    self.logsdir, invocation, self.artifacts_to_build)) as f:
                artifacts_to_build = json.load(f)
        except:
            artifacts_to_build = {}

        @cache
        def critical_path(artifact_type, source_id):
            input_artifacts = []
            source_duration = 0.0
            if artifact_type == "ACTION":
                input_artifacts = graph.get("actions", {}).get(source_id, {}).get("input", {}).values()
                source_duration = profile.get("actions", {}).get(source_id, {}).get("duration", 0.0)
            elif artifact_type == "TREE":
                input_artifacts = graph.get("trees", {}).get(source_id, {}).values()
            elif artifact_type == "TREE_OVERLAY":
                input_artifacts = graph.get("tree_overlays", {}).get(source_id, {}).get("trees", [])
            else:
                return ([], 0.0)

            max_path  = []
            max_duration = 0.0
            for artifact_desc in input_artifacts:
                path, duration = critical_path(
                    artifact_desc.get("type", {}),
                    artifact_desc.get("data", {}).get("id"))
                if duration > max_duration:
                    max_duration = duration
                    max_path = path

            path = max_path + [(artifact_type, source_id)]
            duration = max_duration + source_duration
            return (path, duration)

        max_path = []
        max_name = None
        max_duration = 0.0
        for artifact_name, artifact_desc in artifacts_to_build.items():
            path, duration = critical_path(
                artifact_desc.get("type", {}),
                artifact_desc.get("data", {}).get("id"))
            if duration > max_duration:
                max_duration = duration
                max_path = path
                max_name = artifact_name

        max_path_data = []
        for artifact_type, source_id in reversed(max_path):
            source_data = {}
            if artifact_type == "ACTION":
                action_profile = profile.get('actions', {}).get(source_id, {})
                source_data = action_data(source_id, action_profile, graph)
                source_data["name_prefix"] = "%5.1fs" % (action_profile.get("duration", 0.0),)
            else:
                source_data = {"name": source_id}
            max_path_data.append({
                "type": artifact_type,
                "data": source_data
            })

        build_start_time = profile.get("build start time")
        build_stop_time = profile.get("build stop time")
        build_wall_clock_time = build_stop_time - build_start_time if (build_start_time is not None and build_stop_time is not None) else None
        params["critical_artifact"] = {
            "name": max_name,
            "path": max_path_data if max_path_data else None,
            "duration": '%0.3fs' % (max_duration,) if max_duration > 0 else None,
            "build_wall_clock_time": "%ds" % (build_wall_clock_time,) if build_wall_clock_time else None,
        }
        return self.render("critical_path.html", params)

def action_data(name, profile_value, graph):
    data = { "name_prefix": "",
             "name": name,
             "cached": profile_value.get('cached'),
             "exit_code": profile_value.get('exit code', 0)}
    duration = profile_value.get('duration', 0.0)
    data["duration"] = '%0.3fs' % (duration,) if duration > 0 else None
    desc = graph.get('actions', {}).get(name, {})
    cmd = desc.get('command', [])
    data["cmd"] = json.dumps(cmd) if cmd else None
    data["may_fail"] = desc.get("may_fail")
    data["stdout"] = profile_value.get('stdout')
    data["stderr"] = profile_value.get('stderr')
    data["output"] = desc.get('output', [])
    data["output_dirs"] = desc.get('output_dirs', [])
    if len(data["output"]) == 1:
        data["primary_output"] = data["output"][0]
    elif len(data["output"]) == 0 and len(data["output_dirs"]) == 1:
        data["primary_output"] = data["output_dirs"][0]
    else:
        data["primary_output"] = None
    data["artifacts"] = profile_value.get('artifacts', {})
    data["basenames"] = { name : os.path.basename(name)
                          for name in data["artifacts"].keys() }
    origins = []
    for origin in desc.get('origins', []):
        origins.append("%s#%d@%s" % (
            json.dumps(origin.get('target', [])),
            origin.get('subtask', 0),
            core_config(origin.get('config', {})),))
    data["origins"] = origins
    return data

def create_app(logsdir, **kwargs):
    app = InvocationServer(logsdir, **kwargs)
    app = SharedDataMiddleware(app, {
      '/static': os.path.join(os.path.dirname(__file__), 'static')
    })
    return app

if __name__ == '__main__':
    import sys
    from argparse import ArgumentParser
    from wsgiref.simple_server import make_server
    parser = ArgumentParser(
        description="Serve invocations of a given directory")
    parser.add_argument("--meta", dest="meta", default="meta.json",
                        help="Name of the logged metadata file")
    parser.add_argument("--graph", dest="graph", default="graph.json",
                        help="Name of the logged action-graph file")
    parser.add_argument("--artifacts", dest="artifacts", default="artifacts.json",
                        help="Name of the logged artifacts file")
    parser.add_argument("--artifacts-to-build", dest="artifacts_to_build", default="to-build.json",
                        help="Name of the logged artifacts-to-build file")
    parser.add_argument("--profile", dest="profile", default="profile.json",
                        help="Name of the logged profile file")
    parser.add_argument(
        "--just-mr", dest="just_mr", default='["just-mr"]',
        help="The correct way of invoking just-mr, as JSON vector of strings")
    parser.add_argument("-i", dest="interface", default='127.0.0.1',
                        help="The interface to listen on")
    parser.add_argument("-p", dest="port", default=9000, type=int,
                        help="The port to listen on")
    parser.add_argument("DIR",
                        help="Directory (for a single project id) to serve")
    args = parser.parse_args()
    try:
        just_mr = json.loads(args.just_mr)
    except Exception as e:
        print("just-mr argument should be valid json, but %r is not: %s"
              % (args.just_mr, e), file=sys.stderr)
        sys.exit(1)
    app = create_app(args.DIR,
                     just_mr=just_mr,
                     graph=args.graph,
                     artifacts=args.artifacts,
                     artifacts_to_build=args.artifacts_to_build,
                     meta=args.meta,
                     profile=args.profile)
    make_server(args.interface, args.port, app).serve_forever()