15672: Update container runtime every 5 seconds
[arvados-workbench2.git] / src / views-components / data-explorer / renderers.tsx
1 // Copyright (C) The Arvados Authors. All rights reserved.
2 //
3 // SPDX-License-Identifier: AGPL-3.0
4
5 import * as React from 'react';
6 import { Grid, Typography, withStyles, Tooltip, IconButton, Checkbox } from '@material-ui/core';
7 import { FavoriteStar, PublicFavoriteStar } from '../favorite-star/favorite-star';
8 import { ResourceKind, TrashableResource } from '~/models/resource';
9 import { ProjectIcon, CollectionIcon, ProcessIcon, DefaultIcon, WorkflowIcon, ShareIcon } from '~/components/icon/icon';
10 import { formatDate, formatFileSize, formatTime } from '~/common/formatters';
11 import { resourceLabel } from '~/common/labels';
12 import { connect, DispatchProp } from 'react-redux';
13 import { RootState } from '~/store/store';
14 import { getResource } from '~/store/resources/resources';
15 import { GroupContentsResource } from '~/services/groups-service/groups-service';
16 import { getProcess, Process, getProcessStatus, getProcessStatusColor, getProcessRuntime } from '~/store/processes/process';
17 import { ArvadosTheme } from '~/common/custom-theme';
18 import { compose, Dispatch } from 'redux';
19 import { WorkflowResource } from '~/models/workflow';
20 import { ResourceStatus } from '~/views/workflow-panel/workflow-panel-view';
21 import { getUuidPrefix, openRunProcess } from '~/store/workflow-panel/workflow-panel-actions';
22 import { openSharingDialog } from '~/store/sharing-dialog/sharing-dialog-actions';
23 import { UserResource } from '~/models/user';
24 import { toggleIsActive, toggleIsAdmin } from '~/store/users/users-actions';
25 import { LinkResource } from '~/models/link';
26 import { navigateTo } from '~/store/navigation/navigation-action';
27 import { withResourceData } from '~/views-components/data-explorer/with-resources';
28 import { CollectionResource } from '~/models/collection';
29 import { IllegalNamingWarning } from '~/components/warning/warning';
30
31 const renderName = (dispatch: Dispatch, item: { name: string; uuid: string, kind: string }) =>
32     <Grid container alignItems="center" wrap="nowrap" spacing={16}>
33         <Grid item>
34             {renderIcon(item.kind)}
35         </Grid>
36         <Grid item>
37             <Typography color="primary" style={{ width: 'auto', cursor: 'pointer' }} onClick={() => dispatch<any>(navigateTo(item.uuid))}>
38                 {item.kind === ResourceKind.PROJECT || item.kind === ResourceKind.COLLECTION
39                     ? <IllegalNamingWarning name={item.name} />
40                     : null}
41                 {item.name}
42             </Typography>
43         </Grid>
44         <Grid item>
45             <Typography variant="caption">
46                 <FavoriteStar resourceUuid={item.uuid} />
47                 <PublicFavoriteStar resourceUuid={item.uuid} />
48             </Typography>
49         </Grid>
50     </Grid>;
51
52 export const ResourceName = connect(
53     (state: RootState, props: { uuid: string }) => {
54         const resource = getResource<GroupContentsResource>(props.uuid)(state.resources);
55         return resource || { name: '', uuid: '', kind: '' };
56     })((resource: { name: string; uuid: string, kind: string } & DispatchProp<any>) => renderName(resource.dispatch, resource));
57
58 const renderIcon = (kind: string) => {
59     switch (kind) {
60         case ResourceKind.PROJECT:
61             return <ProjectIcon />;
62         case ResourceKind.COLLECTION:
63             return <CollectionIcon />;
64         case ResourceKind.PROCESS:
65             return <ProcessIcon />;
66         case ResourceKind.WORKFLOW:
67             return <WorkflowIcon />;
68         default:
69             return <DefaultIcon />;
70     }
71 };
72
73 const renderDate = (date?: string) => {
74     return <Typography noWrap style={{ minWidth: '100px' }}>{formatDate(date)}</Typography>;
75 };
76
77 const renderWorkflowName = (item: { name: string; uuid: string, kind: string, ownerUuid: string }) =>
78     <Grid container alignItems="center" wrap="nowrap" spacing={16}>
79         <Grid item>
80             {renderIcon(item.kind)}
81         </Grid>
82         <Grid item>
83             <Typography color="primary" style={{ width: '100px' }}>
84                 {item.name}
85             </Typography>
86         </Grid>
87     </Grid>;
88
89 export const ResourceWorkflowName = connect(
90     (state: RootState, props: { uuid: string }) => {
91         const resource = getResource<WorkflowResource>(props.uuid)(state.resources);
92         return resource || { name: '', uuid: '', kind: '', ownerUuid: '' };
93     })(renderWorkflowName);
94
95 const getPublicUuid = (uuidPrefix: string) => {
96     return `${uuidPrefix}-tpzed-anonymouspublic`;
97 };
98
99 const resourceShare = (dispatch: Dispatch, uuidPrefix: string, ownerUuid?: string, uuid?: string) => {
100     const isPublic = ownerUuid === getPublicUuid(uuidPrefix);
101     return (
102         <div>
103             {!isPublic && uuid &&
104                 <Tooltip title="Share">
105                     <IconButton onClick={() => dispatch<any>(openSharingDialog(uuid))}>
106                         <ShareIcon />
107                     </IconButton>
108                 </Tooltip>
109             }
110         </div>
111     );
112 };
113
114 export const ResourceShare = connect(
115     (state: RootState, props: { uuid: string }) => {
116         const resource = getResource<WorkflowResource>(props.uuid)(state.resources);
117         const uuidPrefix = getUuidPrefix(state);
118         return {
119             uuid: resource ? resource.uuid : '',
120             ownerUuid: resource ? resource.ownerUuid : '',
121             uuidPrefix
122         };
123     })((props: { ownerUuid?: string, uuidPrefix: string, uuid?: string } & DispatchProp<any>) =>
124         resourceShare(props.dispatch, props.uuidPrefix, props.ownerUuid, props.uuid));
125
126 const renderFirstName = (item: { firstName: string }) => {
127     return <Typography noWrap>{item.firstName}</Typography>;
128 };
129
130 // User Resources
131 export const ResourceFirstName = connect(
132     (state: RootState, props: { uuid: string }) => {
133         const resource = getResource<UserResource>(props.uuid)(state.resources);
134         return resource || { firstName: '' };
135     })(renderFirstName);
136
137 const renderLastName = (item: { lastName: string }) =>
138     <Typography noWrap>{item.lastName}</Typography>;
139
140 export const ResourceLastName = connect(
141     (state: RootState, props: { uuid: string }) => {
142         const resource = getResource<UserResource>(props.uuid)(state.resources);
143         return resource || { lastName: '' };
144     })(renderLastName);
145
146 const renderUuid = (item: { uuid: string }) =>
147     <Typography noWrap>{item.uuid}</Typography>;
148
149 export const ResourceUuid = connect(
150     (state: RootState, props: { uuid: string }) => {
151         const resource = getResource<UserResource>(props.uuid)(state.resources);
152         return resource || { uuid: '' };
153     })(renderUuid);
154
155 const renderEmail = (item: { email: string }) =>
156     <Typography noWrap>{item.email}</Typography>;
157
158 export const ResourceEmail = connect(
159     (state: RootState, props: { uuid: string }) => {
160         const resource = getResource<UserResource>(props.uuid)(state.resources);
161         return resource || { email: '' };
162     })(renderEmail);
163
164 const renderIsActive = (props: { uuid: string, isActive: boolean, toggleIsActive: (uuid: string) => void }) =>
165     <Checkbox
166         color="primary"
167         checked={props.isActive}
168         onClick={() => props.toggleIsActive(props.uuid)} />;
169
170 export const ResourceIsActive = connect(
171     (state: RootState, props: { uuid: string }) => {
172         const resource = getResource<UserResource>(props.uuid)(state.resources);
173         return resource || { isActive: false };
174     }, { toggleIsActive }
175 )(renderIsActive);
176
177 const renderIsAdmin = (props: { uuid: string, isAdmin: boolean, toggleIsAdmin: (uuid: string) => void }) =>
178     <Checkbox
179         color="primary"
180         checked={props.isAdmin}
181         onClick={() => props.toggleIsAdmin(props.uuid)} />;
182
183 export const ResourceIsAdmin = connect(
184     (state: RootState, props: { uuid: string }) => {
185         const resource = getResource<UserResource>(props.uuid)(state.resources);
186         return resource || { isAdmin: false };
187     }, { toggleIsAdmin }
188 )(renderIsAdmin);
189
190 const renderUsername = (item: { username: string }) =>
191     <Typography noWrap>{item.username}</Typography>;
192
193 export const ResourceUsername = connect(
194     (state: RootState, props: { uuid: string }) => {
195         const resource = getResource<UserResource>(props.uuid)(state.resources);
196         return resource || { username: '' };
197     })(renderUsername);
198
199 // Common methods
200 const renderCommonData = (data: string) =>
201     <Typography noWrap>{data}</Typography>;
202
203 const renderCommonDate = (date: string) =>
204     <Typography noWrap>{formatDate(date)}</Typography>;
205
206 export const CommonUuid = withResourceData('uuid', renderCommonData);
207
208 // Api Client Authorizations
209 export const TokenApiClientId = withResourceData('apiClientId', renderCommonData);
210
211 export const TokenApiToken = withResourceData('apiToken', renderCommonData);
212
213 export const TokenCreatedByIpAddress = withResourceData('createdByIpAddress', renderCommonDate);
214
215 export const TokenDefaultOwnerUuid = withResourceData('defaultOwnerUuid', renderCommonData);
216
217 export const TokenExpiresAt = withResourceData('expiresAt', renderCommonDate);
218
219 export const TokenLastUsedAt = withResourceData('lastUsedAt', renderCommonDate);
220
221 export const TokenLastUsedByIpAddress = withResourceData('lastUsedByIpAddress', renderCommonData);
222
223 export const TokenScopes = withResourceData('scopes', renderCommonData);
224
225 export const TokenUserId = withResourceData('userId', renderCommonData);
226
227 // Compute Node Resources
228 const renderNodeInfo = (data: string) => {
229     return <Typography>{JSON.stringify(data, null, 4)}</Typography>;
230 };
231
232 const clusterColors = [
233     ['#f44336', '#fff'],
234     ['#2196f3', '#fff'],
235     ['#009688', '#fff'],
236     ['#cddc39', '#fff'],
237     ['#ff9800', '#fff']
238 ];
239
240 export const ResourceCluster = (props: { uuid: string }) => {
241     const CLUSTER_ID_LENGTH = 5;
242     const pos = props.uuid.length > CLUSTER_ID_LENGTH ? props.uuid.indexOf('-') : 5;
243     const clusterId = pos >= CLUSTER_ID_LENGTH ? props.uuid.substr(0, pos) : '';
244     const ci = pos >= CLUSTER_ID_LENGTH ? (((((
245         (props.uuid.charCodeAt(0) * props.uuid.charCodeAt(1))
246         + props.uuid.charCodeAt(2))
247         * props.uuid.charCodeAt(3))
248         + props.uuid.charCodeAt(4))) % clusterColors.length) : 0;
249     return <span style={{
250         backgroundColor: clusterColors[ci][0],
251         color: clusterColors[ci][1],
252         padding: "2px 7px",
253         borderRadius: 3
254     }}>{clusterId}</span>;
255 };
256
257 export const ComputeNodeInfo = withResourceData('info', renderNodeInfo);
258
259 export const ComputeNodeDomain = withResourceData('domain', renderCommonData);
260
261 export const ComputeNodeFirstPingAt = withResourceData('firstPingAt', renderCommonDate);
262
263 export const ComputeNodeHostname = withResourceData('hostname', renderCommonData);
264
265 export const ComputeNodeIpAddress = withResourceData('ipAddress', renderCommonData);
266
267 export const ComputeNodeJobUuid = withResourceData('jobUuid', renderCommonData);
268
269 export const ComputeNodeLastPingAt = withResourceData('lastPingAt', renderCommonDate);
270
271 // Links Resources
272 const renderLinkName = (item: { name: string }) =>
273     <Typography noWrap>{item.name || '(none)'}</Typography>;
274
275 export const ResourceLinkName = connect(
276     (state: RootState, props: { uuid: string }) => {
277         const resource = getResource<LinkResource>(props.uuid)(state.resources);
278         return resource || { name: '' };
279     })(renderLinkName);
280
281 const renderLinkClass = (item: { linkClass: string }) =>
282     <Typography noWrap>{item.linkClass}</Typography>;
283
284 export const ResourceLinkClass = connect(
285     (state: RootState, props: { uuid: string }) => {
286         const resource = getResource<LinkResource>(props.uuid)(state.resources);
287         return resource || { linkClass: '' };
288     })(renderLinkClass);
289
290 const renderLinkTail = (dispatch: Dispatch, item: { uuid: string, tailUuid: string, tailKind: string }) => {
291     const currentLabel = resourceLabel(item.tailKind);
292     const isUnknow = currentLabel === "Unknown";
293     return (<div>
294         {!isUnknow ? (
295             renderLink(dispatch, item.tailUuid, currentLabel)
296         ) : (
297                 <Typography noWrap color="default">
298                     {item.tailUuid}
299                 </Typography>
300             )}
301     </div>);
302 };
303
304 const renderLink = (dispatch: Dispatch, uuid: string, label: string) =>
305     <Typography noWrap color="primary" style={{ 'cursor': 'pointer' }} onClick={() => dispatch<any>(navigateTo(uuid))}>
306         {label}: {uuid}
307     </Typography>;
308
309 export const ResourceLinkTail = connect(
310     (state: RootState, props: { uuid: string }) => {
311         const resource = getResource<LinkResource>(props.uuid)(state.resources);
312         return {
313             item: resource || { uuid: '', tailUuid: '', tailKind: ResourceKind.NONE }
314         };
315     })((props: { item: any } & DispatchProp<any>) =>
316         renderLinkTail(props.dispatch, props.item));
317
318 const renderLinkHead = (dispatch: Dispatch, item: { uuid: string, headUuid: string, headKind: ResourceKind }) =>
319     renderLink(dispatch, item.headUuid, resourceLabel(item.headKind));
320
321 export const ResourceLinkHead = connect(
322     (state: RootState, props: { uuid: string }) => {
323         const resource = getResource<LinkResource>(props.uuid)(state.resources);
324         return {
325             item: resource || { uuid: '', headUuid: '', headKind: ResourceKind.NONE }
326         };
327     })((props: { item: any } & DispatchProp<any>) =>
328         renderLinkHead(props.dispatch, props.item));
329
330 export const ResourceLinkUuid = connect(
331     (state: RootState, props: { uuid: string }) => {
332         const resource = getResource<LinkResource>(props.uuid)(state.resources);
333         return resource || { uuid: '' };
334     })(renderUuid);
335
336 // Process Resources
337 const resourceRunProcess = (dispatch: Dispatch, uuid: string) => {
338     return (
339         <div>
340             {uuid &&
341                 <Tooltip title="Run process">
342                     <IconButton onClick={() => dispatch<any>(openRunProcess(uuid))}>
343                         <ProcessIcon />
344                     </IconButton>
345                 </Tooltip>}
346         </div>
347     );
348 };
349
350 export const ResourceRunProcess = connect(
351     (state: RootState, props: { uuid: string }) => {
352         const resource = getResource<WorkflowResource>(props.uuid)(state.resources);
353         return {
354             uuid: resource ? resource.uuid : ''
355         };
356     })((props: { uuid: string } & DispatchProp<any>) =>
357         resourceRunProcess(props.dispatch, props.uuid));
358
359 const renderWorkflowStatus = (uuidPrefix: string, ownerUuid?: string) => {
360     if (ownerUuid === getPublicUuid(uuidPrefix)) {
361         return renderStatus(ResourceStatus.PUBLIC);
362     } else {
363         return renderStatus(ResourceStatus.PRIVATE);
364     }
365 };
366
367 const renderStatus = (status: string) =>
368     <Typography noWrap style={{ width: '60px' }}>{status}</Typography>;
369
370 export const ResourceWorkflowStatus = connect(
371     (state: RootState, props: { uuid: string }) => {
372         const resource = getResource<WorkflowResource>(props.uuid)(state.resources);
373         const uuidPrefix = getUuidPrefix(state);
374         return {
375             ownerUuid: resource ? resource.ownerUuid : '',
376             uuidPrefix
377         };
378     })((props: { ownerUuid?: string, uuidPrefix: string }) => renderWorkflowStatus(props.uuidPrefix, props.ownerUuid));
379
380 export const ResourceLastModifiedDate = connect(
381     (state: RootState, props: { uuid: string }) => {
382         const resource = getResource<GroupContentsResource>(props.uuid)(state.resources);
383         return { date: resource ? resource.modifiedAt : '' };
384     })((props: { date: string }) => renderDate(props.date));
385
386 export const ResourceCreatedAtDate = connect(
387     (state: RootState, props: { uuid: string }) => {
388         const resource = getResource<GroupContentsResource>(props.uuid)(state.resources);
389         return { date: resource ? resource.createdAt : '' };
390     })((props: { date: string }) => renderDate(props.date));
391
392 export const ResourceTrashDate = connect(
393     (state: RootState, props: { uuid: string }) => {
394         const resource = getResource<TrashableResource>(props.uuid)(state.resources);
395         return { date: resource ? resource.trashAt : '' };
396     })((props: { date: string }) => renderDate(props.date));
397
398 export const ResourceDeleteDate = connect(
399     (state: RootState, props: { uuid: string }) => {
400         const resource = getResource<TrashableResource>(props.uuid)(state.resources);
401         return { date: resource ? resource.deleteAt : '' };
402     })((props: { date: string }) => renderDate(props.date));
403
404 export const renderFileSize = (fileSize?: number) =>
405     <Typography noWrap style={{ minWidth: '45px' }}>
406         {formatFileSize(fileSize)}
407     </Typography>;
408
409 export const ResourceFileSize = connect(
410     (state: RootState, props: { uuid: string }) => {
411         const resource = getResource<CollectionResource>(props.uuid)(state.resources);
412         return { fileSize: resource ? resource.fileSizeTotal : 0 };
413     })((props: { fileSize?: number }) => renderFileSize(props.fileSize));
414
415 const renderOwner = (owner: string) =>
416     <Typography noWrap>
417         {owner}
418     </Typography>;
419
420 export const ResourceOwner = connect(
421     (state: RootState, props: { uuid: string }) => {
422         const resource = getResource<GroupContentsResource>(props.uuid)(state.resources);
423         return { owner: resource ? resource.ownerUuid : '' };
424     })((props: { owner: string }) => renderOwner(props.owner));
425
426 export const ResourceOwnerName = connect(
427     (state: RootState, props: { uuid: string }) => {
428         const resource = getResource<GroupContentsResource>(props.uuid)(state.resources);
429         const ownerNameState = state.ownerName;
430         const ownerName = ownerNameState.find(it => it.uuid === resource!.ownerUuid);
431         return { owner: ownerName ? ownerName!.name : resource!.ownerUuid };
432     })((props: { owner: string }) => renderOwner(props.owner));
433
434 const renderType = (type: string) =>
435     <Typography noWrap>
436         {resourceLabel(type)}
437     </Typography>;
438
439 export const ResourceType = connect(
440     (state: RootState, props: { uuid: string }) => {
441         const resource = getResource<GroupContentsResource>(props.uuid)(state.resources);
442         return { type: resource ? resource.kind : '' };
443     })((props: { type: string }) => renderType(props.type));
444
445 export const ProcessStatus = compose(
446     connect((state: RootState, props: { uuid: string }) => {
447         return { process: getProcess(props.uuid)(state.resources) };
448     }),
449     withStyles({}, { withTheme: true }))
450     ((props: { process?: Process, theme: ArvadosTheme }) => {
451         const status = props.process ? getProcessStatus(props.process) : "-";
452         return <Typography
453             noWrap
454             style={{ color: getProcessStatusColor(status, props.theme) }} >
455             {status}
456         </Typography>;
457     });
458
459 export const renderRunTime = (time: number) =>
460     <Typography noWrap style={{ minWidth: '45px' }}>
461         {formatTime(time, true)}
462     </Typography>;
463
464 interface ContainerRunTimeProps {
465     process: Process;
466 }
467
468 interface ContainerRunTimeState {
469     runtime: number;
470 }
471
472 export const ContainerRunTime = connect((state: RootState, props: { uuid: string }) => {
473     return { process: getProcess(props.uuid)(state.resources) };
474 })(class extends React.Component<ContainerRunTimeProps, ContainerRunTimeState> {
475     private timer: any;
476
477     constructor(props: ContainerRunTimeProps) {
478         super(props);
479         this.state = { runtime: this.getRuntime() };
480     }
481
482     getRuntime() {
483         return this.props.process ? getProcessRuntime(this.props.process) : 0;
484     }
485
486     updateRuntime() {
487         this.setState({ runtime: this.getRuntime() });
488     }
489
490     componentDidMount() {
491         this.timer = setInterval(this.updateRuntime.bind(this), 5000);
492     }
493
494     componentWillUnmount() {
495         clearInterval(this.timer);
496     }
497
498     render() {
499         return renderRunTime(this.state.runtime);
500     }
501 });