-
Notifications
You must be signed in to change notification settings - Fork 1.7k
/
Copy pathRunDetails.tsx
1356 lines (1251 loc) · 50.9 KB
/
RunDetails.tsx
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
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Copyright 2018-2019 The Kubeflow Authors
*
* 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
*
* https://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 CircularProgress from '@material-ui/core/CircularProgress';
import InfoIcon from '@material-ui/icons/InfoOutlined';
import { flatten } from 'lodash';
import * as React from 'react';
import { Link, Redirect } from 'react-router-dom';
import { ExternalLink } from 'src/atoms/ExternalLink';
import InputOutputTab from 'src/components/tabs/InputOutputTab';
import { MetricsTab } from 'src/components/tabs/MetricsTab';
import { GkeMetadata, GkeMetadataContext } from 'src/lib/GkeMetadata';
import { useNamespaceChangeEvent } from 'src/lib/KubeflowClient';
import { ExecutionHelpers, getExecutionsFromContext, getRunContext } from 'src/mlmd/MlmdUtils';
import { isV2Pipeline } from 'src/lib/v2/WorkflowUtils';
import { Context, Execution } from 'src/third_party/mlmd';
import { classes, stylesheet } from 'typestyle';
import {
NodePhase as ArgoNodePhase,
NodeStatus,
Workflow,
} from 'src/third_party/mlmd/argo_template';
import { ApiExperiment } from 'src/apis/experiment';
import { ApiRun, ApiRunStorageState } from 'src/apis/run';
import { ApiVisualization, ApiVisualizationType } from 'src/apis/visualization';
import Hr from 'src/atoms/Hr';
import MD2Tabs from 'src/atoms/MD2Tabs';
import Separator from 'src/atoms/Separator';
import Banner, { Mode } from 'src/components/Banner';
import CompareTable from 'src/components/CompareTable';
import DetailsTable from 'src/components/DetailsTable';
import Graph from 'src/components/Graph';
import LogViewer from 'src/components/LogViewer';
import MinioArtifactPreview from 'src/components/MinioArtifactPreview';
import PlotCard from 'src/components/PlotCard';
import { PodEvents, PodInfo } from 'src/components/PodYaml';
import ReduceGraphSwitch from 'src/components/ReduceGraphSwitch';
import { RoutePage, RoutePageFactory, RouteParams } from 'src/components/Router';
import SidePanel from 'src/components/SidePanel';
import { ToolbarProps } from 'src/components/Toolbar';
import { HTMLViewerConfig } from 'src/components/viewers/HTMLViewer';
import { PlotType, ViewerConfig } from 'src/components/viewers/Viewer';
import { componentMap } from 'src/components/viewers/ViewerContainer';
import VisualizationCreator, {
VisualizationCreatorConfig,
} from 'src/components/viewers/VisualizationCreator';
import { color, commonCss, fonts, fontsize, padding } from 'src/Css';
import { Apis } from 'src/lib/Apis';
import Buttons, { ButtonKeys } from 'src/lib/Buttons';
import CompareUtils from 'src/lib/CompareUtils';
import { OutputArtifactLoader } from 'src/lib/OutputArtifactLoader';
import RunUtils from 'src/lib/RunUtils';
import { compareGraphEdges, KeyValue, transitiveReduction } from 'src/lib/StaticGraphParser';
import { hasFinished, NodePhase } from 'src/lib/StatusUtils';
import {
decodeCompressedNodes,
errorToMessage,
formatDateString,
getNodeNameFromNodeId,
getRunDurationFromNode,
getRunDurationFromWorkflow,
logger,
serviceErrorToString,
} from 'src/lib/Utils';
import WorkflowParser from 'src/lib/WorkflowParser';
import { ExecutionDetailsContent } from './ExecutionDetails';
import { Page, PageProps } from './Page';
import { statusToIcon } from './Status';
export enum SidePanelTab {
INPUT_OUTPUT,
VISUALIZATIONS,
TASK_DETAILS,
VOLUMES,
LOGS,
POD,
EVENTS,
ML_METADATA,
MANIFEST,
}
interface SelectedNodeDetails {
id: string;
logs?: string;
phase?: string;
phaseMessage?: string;
}
// exported only for testing
export interface RunDetailsInternalProps {
isLoading?: boolean;
runId?: string;
gkeMetadata: GkeMetadata;
}
export type RunDetailsProps = PageProps & Exclude<RunDetailsInternalProps, 'gkeMetadata'>;
interface AnnotatedConfig {
config: ViewerConfig;
stepName: string;
}
interface GeneratedVisualization {
config: HTMLViewerConfig;
nodeId: string;
}
interface RunDetailsState {
allArtifactConfigs: AnnotatedConfig[];
allowCustomVisualizations: boolean;
experiment?: ApiExperiment;
generatedVisualizations: GeneratedVisualization[];
isGeneratingVisualization: boolean;
logsBannerAdditionalInfo: string;
logsBannerMessage: string;
logsBannerMode: Mode;
graph?: dagre.graphlib.Graph;
reducedGraph?: dagre.graphlib.Graph;
runFinished: boolean;
runMetadata?: ApiRun;
selectedTab: number;
selectedNodeDetails: SelectedNodeDetails | null;
sidepanelBannerMode: Mode;
sidepanelBusy: boolean;
sidepanelSelectedTab: SidePanelTab;
workflow?: Workflow;
mlmdRunContext?: Context;
mlmdExecutions?: Execution[];
showReducedGraph?: boolean;
namespace?: string;
}
export const css = stylesheet({
footer: {
background: color.graphBg,
display: 'flex',
padding: '0 0 20px 20px',
},
graphPane: {
backgroundColor: color.graphBg,
overflow: 'hidden',
position: 'relative',
},
infoSpan: {
color: color.lowContrast,
fontFamily: fonts.secondary,
fontSize: fontsize.small,
letterSpacing: '0.21px',
lineHeight: '24px',
paddingLeft: 6,
},
link: {
color: '#77abda',
},
outputTitle: {
color: color.strong,
fontSize: fontsize.title,
fontWeight: 'bold',
paddingLeft: 20,
},
});
class RunDetails extends Page<RunDetailsInternalProps, RunDetailsState> {
public state: RunDetailsState = {
allArtifactConfigs: [],
allowCustomVisualizations: false,
generatedVisualizations: [],
isGeneratingVisualization: false,
logsBannerAdditionalInfo: '',
logsBannerMessage: '',
logsBannerMode: 'error',
runFinished: false,
selectedNodeDetails: null,
selectedTab: 0,
sidepanelBannerMode: 'warning',
sidepanelBusy: false,
sidepanelSelectedTab: SidePanelTab.INPUT_OUTPUT,
mlmdRunContext: undefined,
mlmdExecutions: undefined,
showReducedGraph: false,
};
private readonly AUTO_REFRESH_INTERVAL = 5000;
private _interval?: NodeJS.Timeout;
public getInitialToolbarState(): ToolbarProps {
const buttons = new Buttons(this.props, this.refresh.bind(this));
const runIdFromParams = this.props.match.params[RouteParams.runId];
return {
actions: buttons
.retryRun(
() =>
this.state.runMetadata
? [this.state.runMetadata!.id!]
: runIdFromParams
? [runIdFromParams]
: [],
true,
() => this.retry(),
)
.cloneRun(
() =>
this.state.runMetadata
? [this.state.runMetadata!.id!]
: runIdFromParams
? [runIdFromParams]
: [],
true,
)
.terminateRun(
() =>
this.state.runMetadata
? [this.state.runMetadata!.id!]
: runIdFromParams
? [runIdFromParams]
: [],
true,
() => this.refresh(),
)
.getToolbarActionMap(),
breadcrumbs: [{ displayName: 'Experiments', href: RoutePage.EXPERIMENTS }],
pageTitle: this.props.runId!,
};
}
public render(): JSX.Element {
if (this.props.isLoading) {
return <div>Currently loading run information</div>;
}
const {
allArtifactConfigs,
allowCustomVisualizations,
isGeneratingVisualization,
runFinished,
runMetadata,
selectedTab,
sidepanelBannerMode,
selectedNodeDetails,
sidepanelSelectedTab,
workflow,
mlmdExecutions,
showReducedGraph,
} = this.state;
const { projectId, clusterName } = this.props.gkeMetadata;
const selectedNodeId = selectedNodeDetails?.id || '';
const namespace = workflow?.metadata?.namespace;
const selectedNodeName = getNodeNameFromNodeId(workflow!, selectedNodeId);
let stackdriverK8sLogsUrl = '';
if (projectId && clusterName && selectedNodeDetails && selectedNodeDetails.id) {
stackdriverK8sLogsUrl = `https://console.cloud.google.com/logs/viewer?project=${projectId}&interval=NO_LIMIT&advancedFilter=resource.type%3D"k8s_container"%0Aresource.labels.cluster_name:"${clusterName}"%0Aresource.labels.pod_name:"${selectedNodeDetails.id}"`;
}
const workflowParameters = WorkflowParser.getParameters(workflow);
const { inputParams, outputParams } = WorkflowParser.getNodeInputOutputParams(
workflow,
selectedNodeId,
);
const { inputArtifacts, outputArtifacts } = WorkflowParser.getNodeInputOutputArtifacts(
workflow,
selectedNodeId,
);
const selectedExecution = mlmdExecutions?.find(
execution => ExecutionHelpers.getKfpPod(execution) === selectedNodeId,
);
const hasMetrics = runMetadata && runMetadata.metrics && runMetadata.metrics.length > 0;
const visualizationCreatorConfig: VisualizationCreatorConfig = {
allowCustomVisualizations,
isBusy: isGeneratingVisualization,
onGenerate: (visualizationArguments: string, source: string, type: ApiVisualizationType) => {
this._onGenerate(visualizationArguments, source, type, namespace || '');
},
type: PlotType.VISUALIZATION_CREATOR,
collapsedInitially: true,
};
const graphToShow =
this.state.showReducedGraph && this.state.reducedGraph
? this.state.reducedGraph
: this.state.graph;
return (
<div className={classes(commonCss.page, padding(20, 't'))}>
{!!workflow && (
<div className={commonCss.page}>
<MD2Tabs
selectedTab={selectedTab}
tabs={['Graph', 'Run output', 'Config']}
onSwitch={(tab: number) => this.setStateSafe({ selectedTab: tab })}
/>
<div className={commonCss.page}>
{/* Graph tab */}
{selectedTab === 0 && (
<div className={classes(commonCss.page, css.graphPane)}>
{graphToShow && (
<div className={commonCss.page}>
<Graph
graph={graphToShow}
selectedNodeId={selectedNodeId}
onClick={id => this._selectNode(id)}
onError={(message, additionalInfo) =>
this.props.updateBanner({ message, additionalInfo, mode: 'error' })
}
/>
<ReduceGraphSwitch
disabled={!this.state.reducedGraph}
checked={showReducedGraph}
onChange={_ => {
this.setState({ showReducedGraph: !this.state.showReducedGraph });
}}
/>
<SidePanel
isBusy={this.state.sidepanelBusy}
isOpen={!!selectedNodeDetails}
onClose={() => this.setStateSafe({ selectedNodeDetails: null })}
title={selectedNodeName}
>
{!!selectedNodeDetails && (
<React.Fragment>
{!!selectedNodeDetails.phaseMessage && (
<Banner
mode={sidepanelBannerMode}
message={selectedNodeDetails.phaseMessage}
/>
)}
<div className={commonCss.page}>
<MD2Tabs
tabs={this.getTabNames(workflow, selectedNodeId)}
selectedTab={sidepanelSelectedTab}
onSwitch={this._loadSidePaneTab.bind(this)}
/>
<div
data-testid='run-details-node-details'
className={commonCss.page}
>
{sidepanelSelectedTab === SidePanelTab.VISUALIZATIONS &&
this.state.selectedNodeDetails &&
this.state.workflow &&
!isV2Pipeline(workflow) && (
<VisualizationsTabContent
execution={selectedExecution}
nodeId={selectedNodeId}
nodeStatus={
this.state.workflow && this.state.workflow.status
? this.state.workflow.status.nodes[
this.state.selectedNodeDetails.id
]
: undefined
}
namespace={this.state.workflow?.metadata?.namespace}
visualizationCreatorConfig={visualizationCreatorConfig}
generatedVisualizations={this.state.generatedVisualizations.filter(
visualization =>
visualization.nodeId === selectedNodeDetails.id,
)}
onError={this.handleError}
/>
)}
{sidepanelSelectedTab === SidePanelTab.VISUALIZATIONS &&
this.state.selectedNodeDetails &&
this.state.workflow &&
isV2Pipeline(workflow) &&
selectedExecution && (
<MetricsTab
execution={selectedExecution}
namespace={this.state.workflow?.metadata?.namespace}
/>
)}
{sidepanelSelectedTab === SidePanelTab.INPUT_OUTPUT &&
!isV2Pipeline(workflow) && (
<div className={padding(20)}>
<DetailsTable
key={`input-parameters-${selectedNodeId}`}
title='Input parameters'
fields={inputParams}
/>
<DetailsTable
key={`input-artifacts-${selectedNodeId}`}
title='Input artifacts'
fields={inputArtifacts}
valueComponent={MinioArtifactPreview}
valueComponentProps={{
namespace: this.state.workflow?.metadata?.namespace,
}}
/>
<DetailsTable
key={`output-parameters-${selectedNodeId}`}
title='Output parameters'
fields={outputParams}
/>
<DetailsTable
key={`output-artifacts-${selectedNodeId}`}
title='Output artifacts'
fields={outputArtifacts}
valueComponent={MinioArtifactPreview}
valueComponentProps={{
namespace: this.state.workflow?.metadata?.namespace,
}}
/>
</div>
)}
{sidepanelSelectedTab === SidePanelTab.INPUT_OUTPUT &&
isV2Pipeline(workflow) &&
selectedExecution && (
<InputOutputTab
execution={selectedExecution}
namespace={namespace}
/>
)}
{sidepanelSelectedTab === SidePanelTab.TASK_DETAILS && (
<div className={padding(20)}>
<DetailsTable
title='Task Details'
fields={this._getTaskDetailsFields(workflow, selectedNodeId)}
/>
</div>
)}
{sidepanelSelectedTab === SidePanelTab.ML_METADATA &&
!isV2Pipeline(workflow) && (
<div className={padding(20)}>
{selectedExecution && (
<>
<div>
This step corresponds to execution{' '}
<Link
className={commonCss.link}
to={RoutePageFactory.executionDetails(
selectedExecution.getId(),
)}
>
"{ExecutionHelpers.getName(selectedExecution)}".
</Link>
</div>
<ExecutionDetailsContent
key={selectedExecution.getId()}
id={selectedExecution.getId()}
onError={
((msg: string, ...args: any[]) => {
// TODO: show a proper error banner and retry button
console.warn(msg);
}) as any
}
// No title here
onTitleUpdate={() => null}
/>
</>
)}
{!selectedExecution && (
<div>Corresponding ML Metadata not found.</div>
)}
</div>
)}
{sidepanelSelectedTab === SidePanelTab.VOLUMES && (
<div className={padding(20)}>
<DetailsTable
title='Volume Mounts'
fields={WorkflowParser.getNodeVolumeMounts(
workflow,
selectedNodeId,
)}
/>
</div>
)}
{sidepanelSelectedTab === SidePanelTab.MANIFEST && (
<div className={padding(20)}>
<DetailsTable
title='Resource Manifest'
fields={WorkflowParser.getNodeManifest(
workflow,
selectedNodeId,
)}
/>
</div>
)}
{sidepanelSelectedTab === SidePanelTab.POD &&
selectedNodeDetails.phase !== NodePhase.SKIPPED && (
<div className={commonCss.page}>
{selectedNodeId && namespace && (
<PodInfo name={selectedNodeName} namespace={namespace} />
)}
</div>
)}
{sidepanelSelectedTab === SidePanelTab.EVENTS &&
selectedNodeDetails.phase !== NodePhase.SKIPPED && (
<div className={commonCss.page}>
{selectedNodeId && namespace && (
<PodEvents name={selectedNodeName} namespace={namespace} />
)}
</div>
)}
{sidepanelSelectedTab === SidePanelTab.LOGS &&
selectedNodeDetails.phase !== NodePhase.SKIPPED && (
<div className={commonCss.page}>
{this.state.logsBannerMessage && (
<React.Fragment>
<Banner
message={this.state.logsBannerMessage}
mode={this.state.logsBannerMode}
additionalInfo={this.state.logsBannerAdditionalInfo}
showTroubleshootingGuideLink={false}
refresh={this._loadSelectedNodeLogs.bind(this)}
/>
</React.Fragment>
)}
{stackdriverK8sLogsUrl && (
<div className={padding(12)}>
Logs can also be viewed in{' '}
<a
href={stackdriverK8sLogsUrl}
target='_blank'
rel='noopener noreferrer'
className={classes(css.link, commonCss.unstyled)}
>
Stackdriver Kubernetes Monitoring
</a>
.
</div>
)}
{!this.state.logsBannerMessage &&
this.state.selectedNodeDetails && (
// Overflow hidden here, because scroll is handled inside
// LogViewer.
<div className={commonCss.pageOverflowHidden}>
<LogViewer
logLines={(
this.state.selectedNodeDetails.logs || ''
).split('\n')}
/>
</div>
)}
</div>
)}
</div>
</div>
</React.Fragment>
)}
</SidePanel>
<div className={css.footer}>
<div className={commonCss.flex}>
<InfoIcon className={commonCss.infoIcon} />
<span className={css.infoSpan}>
Runtime execution graph. Only steps that are currently running or have
already completed are shown.
</span>
</div>
</div>
</div>
)}
{!graphToShow && (
<div>
{runFinished && <span style={{ margin: '40px auto' }}>No graph to show</span>}
{!runFinished && (
<CircularProgress size={30} className={commonCss.absoluteCenter} />
)}
</div>
)}
</div>
)}
{/* Run outputs tab */}
{selectedTab === 1 && (
<div className={padding()}>
{hasMetrics && (
<div>
<div className={css.outputTitle}>Metrics</div>
<div className={padding(20, 'lt')}>
<CompareTable
{...CompareUtils.singleRunToMetricsCompareProps(runMetadata, workflow)}
/>
</div>
</div>
)}
{!hasMetrics && <span>No metrics found for this run.</span>}
<Separator orientation='vertical' />
<Hr />
{allArtifactConfigs.map((annotatedConfig, i) => (
<div key={i}>
<PlotCard
key={i}
configs={[annotatedConfig.config]}
title={annotatedConfig.stepName}
maxDimension={400}
/>
<Separator orientation='vertical' />
<Hr />
</div>
))}
{!allArtifactConfigs.length && (
<span>No output artifacts found for this run.</span>
)}
</div>
)}
{/* Config tab */}
{selectedTab === 2 && (
<div className={padding()}>
<DetailsTable
title='Run details'
fields={this._getDetailsFields(workflow, runMetadata)}
/>
{workflowParameters && !!workflowParameters.length && (
<div>
<DetailsTable
title='Run parameters'
fields={workflowParameters.map(p => [p.name, p.value || ''])}
/>
</div>
)}
</div>
)}
</div>
</div>
)}
</div>
);
}
getTabNames(workflow: Workflow, selectedNodeId: string): string[] {
// NOTE: it's only possible to conditionally add a tab at the end
const tabNameList = [];
for (let tab in SidePanelTab) {
// enum iterator will get both number key and string value of all cases.
// Skip string value because we only switch by numeric key later.
if (isNaN(Number(tab))) {
continue;
}
// plus symbol changes enum to number.
switch (+tab) {
case SidePanelTab.INPUT_OUTPUT: {
tabNameList.push('Input/Output');
break;
}
case SidePanelTab.VISUALIZATIONS: {
tabNameList.push('Visualizations');
break;
}
case SidePanelTab.ML_METADATA: {
if (isV2Pipeline(workflow)) {
break;
}
tabNameList.push('ML Metadata');
break;
}
case SidePanelTab.TASK_DETAILS: {
tabNameList.push('Details');
break;
}
case SidePanelTab.VOLUMES: {
tabNameList.push('Volumes');
break;
}
case SidePanelTab.LOGS: {
tabNameList.push('Logs');
break;
}
case SidePanelTab.POD: {
tabNameList.push('Pod');
break;
}
case SidePanelTab.EVENTS: {
tabNameList.push('Events');
break;
}
case SidePanelTab.MANIFEST: {
if (WorkflowParser.getNodeManifest(workflow, selectedNodeId).length === 0) {
break;
}
tabNameList.push('Manifest');
break;
}
default: {
console.error(`Unable to find corresponding tab name for ${tab}`);
break;
}
}
}
return tabNameList;
}
public async componentDidMount(): Promise<void> {
window.addEventListener('focus', this.onFocusHandler);
window.addEventListener('blur', this.onBlurHandler);
await this._startAutoRefresh();
}
public onBlurHandler = (): void => {
this._stopAutoRefresh();
};
public onFocusHandler = async (): Promise<void> => {
await this._startAutoRefresh();
};
public componentWillUnmount(): void {
this._stopAutoRefresh();
window.removeEventListener('focus', this.onFocusHandler);
window.removeEventListener('blur', this.onBlurHandler);
this.clearBanner();
}
public async retry(): Promise<void> {
const runFinished = false;
this.setStateSafe({
runFinished,
});
await this._startAutoRefresh();
}
public async refresh(): Promise<void> {
await this.load();
}
public async load(): Promise<void> {
this.clearBanner();
const runId = this.props.match.params[RouteParams.runId];
try {
const allowCustomVisualizations = await Apis.areCustomVisualizationsAllowed();
this.setState({ allowCustomVisualizations });
} catch (err) {
this.showPageError('Error: Unable to enable custom visualizations.', err);
}
try {
const runDetail = await Apis.runServiceApi.getRun(runId);
const relatedExperimentId = RunUtils.getFirstExperimentReferenceId(runDetail.run);
let experiment: ApiExperiment | undefined;
let namespace: string | undefined;
if (relatedExperimentId) {
experiment = await Apis.experimentServiceApi.getExperiment(relatedExperimentId);
namespace = RunUtils.getNamespaceReferenceName(experiment);
}
const runMetadata = runDetail.run!;
let runFinished = this.state.runFinished;
// If the run has finished, stop auto refreshing
if (hasFinished(runMetadata.status as NodePhase)) {
this._stopAutoRefresh();
// This prevents other events, such as onFocus, from resuming the autorefresh
runFinished = true;
}
const jsonWorkflow = JSON.parse(runDetail.pipeline_runtime!.workflow_manifest || '{}');
if (
jsonWorkflow.status &&
!jsonWorkflow.status.nodes &&
jsonWorkflow.status.compressedNodes
) {
try {
jsonWorkflow.status.nodes = await decodeCompressedNodes(
jsonWorkflow.status.compressedNodes,
);
delete jsonWorkflow.status.compressedNodes;
} catch (err) {
console.error(`Failed to decode compressedNodes: ${err}`);
}
}
const workflow = jsonWorkflow as Workflow;
// Show workflow errors
const workflowError = WorkflowParser.getWorkflowError(workflow);
if (workflowError) {
if (workflowError === 'terminated') {
this.props.updateBanner({
additionalInfo: `This run's workflow included the following message: ${workflowError}`,
message: 'This run was terminated',
mode: 'warning',
refresh: undefined,
});
} else {
this.showPageError(
`Error: found errors when executing run: ${runId}.`,
new Error(workflowError),
);
}
}
let mlmdRunContext: Context | undefined;
let mlmdExecutions: Execution[] | undefined;
// Get data about this workflow from MLMD
try {
mlmdRunContext = await getRunContext(workflow, runId);
mlmdExecutions = await getExecutionsFromContext(mlmdRunContext);
} catch (err) {
// Data in MLMD may not exist depending on this pipeline is a TFX pipeline.
// So we only log the error in console.
logger.warn(err);
}
// Build runtime graph
const graph =
workflow && workflow.status && workflow.status.nodes
? WorkflowParser.createRuntimeGraph(workflow, mlmdExecutions)
: undefined;
let reducedGraph = graph
? // copy graph before removing edges
transitiveReduction(graph)
: undefined;
if (graph && reducedGraph && compareGraphEdges(graph, reducedGraph)) {
reducedGraph = undefined; // disable reduction switch
}
const breadcrumbs: Array<{ displayName: string; href: string }> = [];
// If this is an archived run, only show Archive in breadcrumbs, otherwise show
// the full path, including the experiment if any.
if (runMetadata.storage_state === ApiRunStorageState.ARCHIVED) {
breadcrumbs.push({ displayName: 'Archive', href: RoutePage.ARCHIVED_RUNS });
} else {
if (experiment) {
breadcrumbs.push(
{ displayName: 'Experiments', href: RoutePage.EXPERIMENTS },
{
displayName: experiment.name!,
href: RoutePage.EXPERIMENT_DETAILS.replace(
':' + RouteParams.experimentId,
experiment.id!,
),
},
);
} else {
breadcrumbs.push({ displayName: 'All runs', href: RoutePage.RUNS });
}
}
const pageTitle = (
<div className={commonCss.flex}>
{statusToIcon(runMetadata.status as NodePhase, runDetail.run!.created_at)}
<span style={{ marginLeft: 10 }}>{runMetadata.name!}</span>
</div>
);
// Update the Archive/Restore button based on the storage state of this run
const buttons = new Buttons(
this.props,
this.refresh.bind(this),
this.getInitialToolbarState().actions,
);
const idGetter = () => (runMetadata ? [runMetadata!.id!] : []);
runMetadata!.storage_state === ApiRunStorageState.ARCHIVED
? buttons.restore('run', idGetter, true, () => this.refresh())
: buttons.archive('run', idGetter, true, () => this.refresh());
const actions = buttons.getToolbarActionMap();
actions[ButtonKeys.TERMINATE_RUN].disabled =
(runMetadata.status as NodePhase) === NodePhase.TERMINATING || runFinished;
actions[ButtonKeys.RETRY].disabled =
(runMetadata.status as NodePhase) !== NodePhase.FAILED &&
(runMetadata.status as NodePhase) !== NodePhase.ERROR;
this.props.updateToolbar({
actions,
breadcrumbs,
pageTitle,
pageTitleTooltip: runMetadata.name,
});
this.setStateSafe({
experiment,
graph,
reducedGraph,
runFinished,
runMetadata,
workflow,
mlmdRunContext,
mlmdExecutions,
namespace,
});
// Read optional exeuction id from query parameter. If valid, shows detail of selected node.
const paramExecutionId = this.props.match.params[RouteParams.executionId];
if (mlmdExecutions) {
const selectedExec = mlmdExecutions.find(
exec => exec.getId().toString() === paramExecutionId,
);
if (selectedExec) {
const selectedNodeId = ExecutionHelpers.getKfpPod(selectedExec);
if (typeof selectedNodeId === 'string') {
this.setStateSafe({ selectedNodeDetails: { id: selectedNodeId } });
}
}
}
} catch (err) {
await this.showPageError(`Error: failed to retrieve run: ${runId}.`, err);
logger.error('Error loading run:', runId, err);
}
// Make sure logs and artifacts in the side panel are refreshed when
// the user hits "Refresh", either in the top toolbar or in an error banner.
await this._loadSidePaneTab(this.state.sidepanelSelectedTab);
// Load all run's outputs
await this._loadAllOutputs();
}
private handleError = async (error: Error) => {
await this.showPageError(serviceErrorToString(error), error);
};
private async _startAutoRefresh(): Promise<void> {
// If the run was not finished last time we checked, check again in case anything changed
// before proceeding to set auto-refresh interval
if (!this.state.runFinished) {
// refresh() updates runFinished's value
await this.refresh();
}
// Only set interval if run has not finished, and verify that the interval is undefined to
// avoid setting multiple intervals
if (!this.state.runFinished && this._interval === undefined) {
this._interval = setInterval(() => this.refresh(), this.AUTO_REFRESH_INTERVAL);
}
}
private _stopAutoRefresh(): void {
if (this._interval !== undefined) {
clearInterval(this._interval);
// Reset interval to indicate that a new one can be set
this._interval = undefined;
}
}
private async _loadAllOutputs(): Promise<void> {
const workflow = this.state.workflow;
if (!workflow) {
return;
}
const outputPathsList = WorkflowParser.loadAllOutputPathsWithStepNames(workflow);
const configLists = await Promise.all(
outputPathsList.map(({ stepName, path }) =>
OutputArtifactLoader.load(path, workflow?.metadata?.namespace).then(configs =>
configs.map(config => ({ config, stepName })),
),
),
);
const allArtifactConfigs = flatten(configLists);
this.setStateSafe({ allArtifactConfigs });
}
private _getDetailsFields(workflow: Workflow, runMetadata?: ApiRun): Array<KeyValue<string>> {
return !workflow.status
? []
: [
['Run ID', runMetadata?.id || '-'],
['Workflow name', workflow.metadata?.name || '-'],
['Status', workflow.status.phase],
['Description', runMetadata ? runMetadata!.description! : ''],
[
'Created at',
workflow.metadata ? formatDateString(workflow.metadata.creationTimestamp) : '-',
],
['Started at', formatDateString(workflow.status.startedAt)],
['Finished at', formatDateString(workflow.status.finishedAt)],
['Duration', getRunDurationFromWorkflow(workflow)],
];
}
private _getTaskDetailsFields(workflow: Workflow, nodeId: string): Array<KeyValue<string>> {
return workflow?.status?.nodes?.[nodeId]
? [
['Task ID', workflow.status.nodes[nodeId].id || '-'],
['Task name', workflow.status.nodes[nodeId].displayName || '-'],
['Status', workflow.status.nodes[nodeId].phase || '-'],
['Started at', formatDateString(workflow.status.nodes[nodeId].startedAt) || '-'],
['Finished at', formatDateString(workflow.status.nodes[nodeId].finishedAt) || '-'],