summaryrefslogtreecommitdiff
path: root/web/src/containers/build/Console.jsx
blob: 9cd10df9275ee99dbf575206230871ba61213e73 (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
// Copyright 2018 Red Hat, Inc
//
// 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 * as moment from 'moment'
import 'moment-duration-format'
import * as React from 'react'
import ReAnsi from '@softwarefactory-project/re-ansi'
import PropTypes from 'prop-types'
import ReactJson from 'react-json-view'

import {
  Button,
  Chip,
  DataList,
  DataListItem,
  DataListItemRow,
  DataListCell,
  DataListItemCells,
  DataListToggle,
  DataListContent,
  Divider,
  Flex,
  FlexItem,
  Label,
  Modal,
  Tooltip
} from '@patternfly/react-core'

import {
  AngleRightIcon,
  ContainerNodeIcon,
  InfoCircleIcon,
  SearchPlusIcon,
  LinkIcon,
} from '@patternfly/react-icons'

import {
  hasInterestingKeys,
  findLoopLabel,
  shouldIncludeKey,
  makeTaskPath,
  taskPathMatches,
} from '../../actions/build'

const INTERESTING_KEYS = ['msg', 'cmd', 'stdout', 'stderr']


class TaskOutput extends React.Component {
  static propTypes = {
    data: PropTypes.object,
    include: PropTypes.array,
  }

  renderResults(value) {
    const interesting_results = []

    // This was written to assume "value" is an array of key/value
    // mappings to output.  This seems to be a good assumption for the
    // most part, but "package:" on at least some distros --
    // RedHat/yum/dnf we've found -- outputs a result that is just an
    // array of strings with what packages were installed.  So, if we
    // see an array of strings as the value, we just swizzle that into
    // a key/value so it displays usefully.
    const isAllStrings = value.every(i => typeof i === 'string')
    if (isAllStrings) {
      value = [ {output: [...value]} ]
    }

    value.forEach((result, idx) => {
      const keys = Object.entries(result).filter(
        ([key, value]) => shouldIncludeKey(
          key, value, true, this.props.include))
      if (keys.length) {
        interesting_results.push(idx)
      }
    })

    return (
      <div key='results'>
        {interesting_results.length>0 &&
         <React.Fragment>
           <h5 key='results-header'>results</h5>
           {interesting_results.map((idx) => (
             <div className='zuul-console-task-result' key={idx}>
               <h4 key={idx}>{idx}: {findLoopLabel(value[idx])}</h4>
               {Object.entries(value[idx]).map(([key, value]) => (
                 this.renderData(key, value, true)
               ))}
             </div>
           ))}
         </React.Fragment>
        }
      </div>
    )
  }

  renderData(key, value, ignore_underscore) {
    let ret
    if (!shouldIncludeKey(key, value, ignore_underscore, this.props.include)) {
      return (<React.Fragment key={key}/>)
    }
    if (value === null) {
      ret = (
        <pre>
          null
        </pre>
      )
    } else if (typeof(value) === 'string') {
      ret = (
        <pre>
          <ReAnsi log={value} />
        </pre>
      )
    } else if (typeof(value) === 'object') {
      ret = (
        <pre>
          <ReactJson
            src={value}
            name={null}
            sortKeys={true}
            enableClipboard={false}
            displayDataTypes={false}/>
        </pre>
      )
    } else {
      ret = (
        <pre>
          {value.toString()}
        </pre>
      )
    }

    return (
      <div key={key}>
        {ret && <h5>{key}</h5>}
        {ret && ret}
      </div>
    )
  }

  render () {
    const { data } = this.props

    return (
      <React.Fragment>
        {Object.entries(data).map(([key, value]) => (
          key==='results'?this.renderResults(value):this.renderData(key, value)
        ))}
      </React.Fragment>
    )
  }
}

class HostTask extends React.Component {
  static propTypes = {
    hostname: PropTypes.string,
    task: PropTypes.object,
    host: PropTypes.object,
    errorIds: PropTypes.object,
    taskPath: PropTypes.array,
    displayPath: PropTypes.array,
  }

  state = {
    showModal: false,
    failed: false,
    changed: false,
    skipped: false,
    ok: false
  }

  open = () => {
    this.setState({showModal: true})
  }

  close = () => {
    this.setState({showModal: false})
  }

  constructor (props) {
    super(props)

    const { host, taskPath, displayPath } = this.props

    if (host.failed) {
      this.state.failed = true
    } else if (host.changed) {
      this.state.changed = true
    } else if (host.skipped) {
      this.state.skipped = true
    } else {
      this.state.ok = true
    }

    if (taskPathMatches(taskPath, displayPath))
      this.state.showModal = true

    // If it has errors, expand by default
    this.state.expanded = this.props.errorIds.has(this.props.task.task.id)
  }

  render () {
    const { hostname, task, host, taskPath } = this.props
    const dataListCells = []

    // "interesting" result tasks are those that have some values in
    // their results that show command output, etc.  These plays get
    // an expansion that shows these values without having to click
    // and bring up the full insepction modal.
    const interestingKeys = hasInterestingKeys(host, INTERESTING_KEYS)

    let name = task.task.name
    if (!name) {
      name = host.action
    }
    if (task.role) {
      name = task.role.name + ': ' + name
    }

    dataListCells.push(
      <DataListCell key='name' width={4}>{name}</DataListCell>
    )

    let labelColor = null
    let labelString = null

    if (this.state.failed) {
      labelColor = 'red'
      labelString = 'Failed'
    } else if (this.state.changed) {
      labelColor = 'orange'
      labelString = 'Changed'
    } else if (this.state.skipped) {
      labelColor = 'grey'
      labelString = 'Skipped'
    } else if (this.state.ok) {
      labelColor = 'green'
      labelString = 'OK'
    }

    dataListCells.push(
      <DataListCell key='state'>
        <Tooltip content={<div>Click for details</div>}>
          <Label color={labelColor} onClick={this.open}
                 style={{cursor: 'pointer'}}>
            <Flex flexWrap={{default: 'nowrap' }}>
              <FlexItem style={{minWidth: '7ch'}}>
                {labelString}
              </FlexItem>
              <Divider align={{default: 'alignRight'}} orientation={{default: 'vertical'}} />
              <FlexItem>
                <SearchPlusIcon color='var(--pf-global--Color--200)' style={{cursor: 'pointer'}} />
              </FlexItem>
            </Flex>
          </Label>
        </Tooltip>
      </DataListCell>)

    dataListCells.push(
      <DataListCell key='node'>
        <Chip isReadOnly={true} textMaxWidth='50ch'>
          <span style={{ fontSize: 'var(--pf-global--FontSize--md)' }}>
          <ContainerNodeIcon />&nbsp;{hostname}</span>
        </Chip>
      </DataListCell>
    )

    let duration = moment.duration(
      moment(task.task.duration.end).diff(task.task.duration.start)
    ).format({
      template: 'h [hr] m [min] s [sec]',
      largest: 2,
      minValue: 1,
    })

    dataListCells.push(
      <DataListCell key='task-duration'>
        <span className='task-duration'>{duration}</span>
      </DataListCell>
    )

    const content = <TaskOutput data={this.props.host} include={INTERESTING_KEYS}/>

    let item = null
    if (interestingKeys) {
      item = <DataListItem
               isExpanded={this.state.expanded}
               className={this.state.failed ? 'zuul-console-task-failed' : ''}>
               <DataListItemRow>
                 <DataListToggle
                   onClick={() => {this.setState({expanded: !this.state.expanded})}}
                   isExpanded={this.state.expanded}
                 />
                 <DataListItemCells dataListCells={ dataListCells } />
               </DataListItemRow>
               <DataListContent
                 isHidden={!this.state.expanded}>
                 { content }
               </DataListContent>
             </DataListItem>
    } else {
      // We currently have to build the data-list item/row/control manually
      // as we don't have a way to hide the toggle.  Hopefully PF will
      // add a prop that does this so we can get rid of this, see:
      //   https://github.com/patternfly/patternfly/issues/5055
      item = <li className="pf-c-data-list__item">
               <div className="pf-c-data-list__item-row">
                 <div className="pf-c-data-list__item-control"
                      style={{visibility: 'hidden'}}>
                   <div className="pf-c-data-list__toggle">
                     <Button disabled>
                       <AngleRightIcon />
                     </Button>
                   </div>
                 </div>
                 <DataListItemCells dataListCells={ dataListCells } />
               </div>
             </li>
    }

    const modalDescription = <Flex>
                               <FlexItem>
                                 <Label color={labelColor}>{labelString}</Label>
                               </FlexItem>
                               <FlexItem>
                                 <Chip isReadOnly={true} textMaxWidth='50ch'>
                                   <span style={{ fontSize: 'var(--pf-global--FontSize--md)' }}>
                                   <ContainerNodeIcon />&nbsp;{hostname}</span>
                                 </Chip>
                               </FlexItem>
                               <FlexItem>
                                 <a href={'#'+makeTaskPath(taskPath)}>
                                   <LinkIcon name='link' title='Permalink' />
                                 </a>
                               </FlexItem>
                             </Flex>

    return (
      <>
        {item}
        <Modal
          title={name}
          isOpen={this.state.showModal}
          onClose={this.close}
          description={modalDescription}>
          <TaskOutput data={host}/>
        </Modal>
      </>
    )
  }
}

class PlayBook extends React.Component {
  static propTypes = {
    playbook: PropTypes.object,
    errorIds: PropTypes.object,
    taskPath: PropTypes.array,
    displayPath: PropTypes.array,
  }

  constructor(props) {
    super(props)
    this.state = {
      // Start the playbook expanded if
      //  * has errror in it
      //  * direct link
      //  * it is a run playbook
      expanded: (this.props.errorIds.has(this.props.playbook.phase + this.props.playbook.index) ||
                 taskPathMatches(this.props.taskPath, this.props.displayPath) ||
                 this.props.playbook.phase === 'run'),
      // NOTE(ianw) 2022-08-26 : Plays start expanded because that is
      // what it has always done; most playbooks probably only have
      // one play.  Maybe if there's multiple plays things could start
      // rolled up?
      playsExpanded: this.props.playbook.plays.map((play, idx) => this.makePlayId(play, idx))
    }
  }

  makePlayId = (play, idx) => play.play.name + '-' + idx

  render () {
    const { playbook, errorIds, taskPath, displayPath } = this.props

    const togglePlays = id => {
      const index = this.state.playsExpanded.indexOf(id)
      const newExpanded =
            index >= 0 ? [...this.state.playsExpanded.slice(0, index), ...this.state.playsExpanded.slice(index + 1, this.state.playsExpanded.length)] : [...this.state.playsExpanded, id]
      this.setState({playsExpanded: newExpanded})
    }

    // This is the header for each playbook
    let dataListCells = []
    dataListCells.push(
      <DataListCell key='name' width={1}>
        <strong>
          {playbook.phase[0].toUpperCase() + playbook.phase.slice(1)} playbook<
          /strong>
      </DataListCell>)
        dataListCells.push(
        <DataListCell key='path' width={5}>
          {playbook.playbook}
        </DataListCell>)
    if (playbook.trusted) {
      dataListCells.push(
        <DataListCell key='trust'>
          <Tooltip content={<div>This playbook runs in a trusted execution context, which permits executing code on the Zuul executor and allows access to all Ansible features.</div>}>
          <Label color='blue' icon={<InfoCircleIcon />} style={{cursor: 'pointer'}}>Trusted</Label></Tooltip></DataListCell>)
    } else {
        // NOTE(ianw) : This empty cell keeps things lined up
        // correctly.  We tried a "untrusted" label but preferred
        // without.
        dataListCells.push(<DataListCell key='trust' width={1}/>)
    }

    return (
      <DataListItem isExpanded={this.state.expanded}>

        <DataListItemRow>
          <DataListToggle
            onClick={() => this.setState({expanded: !this.state.expanded})}
            isExpanded={this.state.expanded}/>
          <DataListItemCells
            dataListCells={dataListCells} />
        </DataListItemRow>

        <DataListContent isHidden={!this.state.expanded}>

          {playbook.plays.map((play, idx) => (
            <DataList isCompact={true}
                      key={this.makePlayId(play, idx)}
                      className="zuul-console-plays"
                      style={{ fontSize: 'var(--pf-global--FontSize--md)' }}>
              <DataListItem isExpanded={this.state.playsExpanded.includes(this.makePlayId(play, idx))}>
                <DataListItemRow>
                  <DataListToggle
                    onClick={() => togglePlays(this.makePlayId(play, idx))}
                    isExpanded={this.state.playsExpanded.includes(this.makePlayId(play, idx))}
                    id={this.makePlayId(play, idx)}/>
                  <DataListItemCells dataListCells={[
                                       <DataListCell key='play'>Play: {play.play.name}</DataListCell>
                                     ]}
                  />
                </DataListItemRow>
                <DataListContent
                  isHidden={!this.state.playsExpanded.includes(this.makePlayId(play, idx))}>

                  <DataList isCompact={true} style={{ fontSize: 'var(--pf-global--FontSize--md)' }} >
                    {play.tasks.map((task, idx2) => (
                      Object.entries(task.hosts).map(([hostname, host]) => (
                        <HostTask key={idx+idx2+hostname}
                          hostname={hostname}
                          taskPath={taskPath.concat([
                            idx.toString(), idx2.toString(), hostname])}
                          displayPath={displayPath} task={task} host={host}
                          errorIds={errorIds}/>
                      ))))}
                  </DataList>

                </DataListContent>
              </DataListItem>
            </DataList>
          ))}

        </DataListContent>
      </DataListItem>
    )
  }
}


class Console extends React.Component {
  static propTypes = {
    errorIds: PropTypes.object,
    output: PropTypes.array,
    displayPath: PropTypes.array,
  }

  render () {
    const { errorIds, output, displayPath } = this.props

    return (
      <React.Fragment>
        <br />
        <span className="zuul-console">
          <DataList isCompact={true}
                    style={{ fontSize: 'var(--pf-global--FontSize--md)' }}>
            {
              output.map((playbook, idx) => (
                <PlayBook
                  key={idx} playbook={playbook} taskPath={[idx.toString()]}
                  displayPath={displayPath} errorIds={errorIds}
                />))
            }
          </DataList>
        </span>
      </React.Fragment>
    )
  }
}


export default Console