-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.vue
1446 lines (1261 loc) · 44.6 KB
/
app.vue
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
<template>
<div class="p-grid p-jc-between p-ai-center topbar">
<div class="p-col-12 p-md-4 p-lg-3 p-d-flex p-ai-center">
<img style="width: 64px; height: 64px;" :src="logo"/>
<h2 class="p-ml-4 logo">Calabash Panel</h2>
</div>
<div class="p-col-12 p-md-8 p-lg-6 p-input-icon-left p-d-flex p-ai-center">
<i class="pi pi-caret-right p-pl-3"></i>
<InputText type="text" v-model="input_job" style="flex-grow: 1;"
placeholder="Run job ..." class="p-inputtext-sm p-m-2"/>
<SplitButton label="Run" :model="run_btn_model" @click="runJob()"/>
<SplitButton label="Info" class="p-ml-2 p-button-secondary" :model="log_btn_model"
@click="showJob()"/>
</div>
<div class="p-col-12 p-md-12 p-lg-3 p-d-flex p-jc-end">
<div class="p-d-flex p-ai-center p-mr-4">
<i class="las la-sun"></i>
<i class="hspacer"></i>
<InputSwitch v-model="nightTheme"/>
<i class="hspacer"></i>
<i class="las la-moon"></i>
</div>
<Button icon="pi pi-cog" class="p-button-text p-button-rounded" @click="showConfigs"/>
<Button icon="lab la-github" class="p-button-text p-button-rounded" @click="onClickGithub"/>
</div>
<div class="p-col-12 p-md-12 p-lg-12" v-if="tabViewActiveIndex === 5">
<Toolbar>
<template v-slot:left>
<div class="p-grid p-pt-4">
<Button class="p-mx-2 p-button-text" label="Add node" icon="las la-server"
@click="center_dialog_show = true; center_dialog_for = 'Add Node'"/>
<Button class="p-mx-2 p-button-text" label="Create service" icon="las la-microchip"
@click="center_dialog_show = true; center_dialog_for = 'Create Service'"/>
<Button v-for="item in clusterTreeSelModel" :key="item.label"
class="p-mx-2 p-button-text" :label="item.label" :icon="item.icon"
@click="input_job = item.query" />
</div>
</template>
</Toolbar>
</div>
</div>
<Toast position="top-right"/>
<Dialog :header="top_dialog_title" position="top" v-model:visible="top_dialog_show"
:maximizable="top_dialog_maximizable">
<Textarea v-model="top_dialog_content" class="top_dialog" :disabled="true"/>
</Dialog>
<Dialog :header="center_dialog_for" v-model:visible="center_dialog_show" style="min-width: 500px">
<div v-for="field in center_dialog_model[center_dialog_for]" :key="field.label">
<h4> {{field.label}} </h4>
<Listbox v-model="field.value" :options="field.options" optionLabel="name"/>
<h4 v-if="field.value">Description:</h4>
<pre style="overflow-x: auto">{{ field.value && field.value['desc'] }}</pre>
</div>
<template #footer>
<Button label="Query" icon="pi pi-check" @click="onCenterDialogConfirm()"
:disabled="!center_dialog_model[center_dialog_for].every(field => field.value)"/>
</template>
</Dialog>
<div class="p-d-flex">
<div style="width:12em">
<Listbox v-model="selectedHistory" :options="jobHistory" optionLabel="jobname"
listStyle="max-height:250px" :filter="true" filterPlaceholder="History"/>
<Menu :model="menu_model" style="width:100%"/>
</div>
<div style="flex-grow: 1;" class="p-d-flex p-jc-center">
<div class="main">
<Fieldset legend="Server List" class="p-mt-4">
<TabView v-model:activeIndex="tabViewActiveIndex">
<TabPanel header="Blank">
</TabPanel>
<TabPanel header="IaaS">
<DataTable :value="cluster_iaas_nodes" :scrollable="true" style="width: 100%">
<Column field="provider" header="Provider"></Column>
<Column field="id" header="ID"></Column>
<Column field="label" header="Label"></Column>
<Column field="inject_ip" header="IP"></Column>
<Column field="description" header="Specs"></Column>
<Column field="create_time" header="Creation"></Column>
<Column field="status" header="Status"></Column>
</DataTable>
</TabPanel>
<TabPanel header="Swarm Nodes">
<DataTable :value="cluster_swarm_nodes" :scrollable="true" style="width: 100%">
<Column field="ID" header="ID"></Column>
<Column field="Spec.Role" header="Role"></Column>
<Column field="Description.Hostname" header="Hostname"></Column>
<Column field="Status.Addr" header="Address"></Column>
<Column field="Description.Engine.EngineVersion" header="Docker"></Column>
<Column field="inject_cpu" header="Nano CPU"></Column>
<Column field="inject_memory" header="Memory"></Column>
<Column field="Status.State" header="State"></Column>
<Column field="inject_labels" header="Labels"></Column>
</DataTable>
</TabPanel>
<TabPanel header="Swarm Services">
<DataTable :value="cluster_services" :scrollable="true" style="width: 100%">
<Column field="ID" header="ID"></Column>
<Column field="Spec.Name" header="Name"></Column>
<Column field="inject_ports" header="Ports"></Column>
<Column field="inject_constraints" header="Constraints"></Column>
<Column field="Spec.Mode.Replicated.Replicas" header="Replicas"></Column>
<Column field="inject_createtime" header="Created"></Column>
<Column field="inject_updatetime" header="Updated"></Column>
<Column field="inject_labels" header="Labels"></Column>
</DataTable>
</TabPanel>
<TabPanel header="Swarm Tasks">
<DataTable :value="cluster_tasks" :scrollable="true" style="width: 100%">
<Column field="NodeID" header="Node" sortable="true"></Column>
<Column field="ServiceID" header="Service"></Column>
<Column field="inject_createtime" header="Created"></Column>
<Column field="inject_updatetime" header="Updated"></Column>
<Column field="Status.State" header="State" sortable="true"></Column>
<Column field="inject_timestamp" header="Timestamp" sortable="true"></Column>
<Column field="Status.Err" header="Error"></Column>
</DataTable>
</TabPanel>
<TabPanel header="Cluster Tree">
<Toolbar>
<template v-slot:right>
<div class="p-grid p-pt-4 p-pr-4 p-ai-center">
<i class="las la-tree"></i>
Top-level
<i class="hspacer"></i>
<InputSwitch v-model="clusterTreeTopLevel"/>
</div>
</template>
</Toolbar>
<Tree :value="clusterTree" selectionMode="single" v-model:selectionKeys="clusterTreeSel">
</Tree>
</TabPanel>
</TabView>
</Fieldset>
<Fieldset legend="Calabash Tasks" class="p-mt-4" style="position: relative">
<Toolbar>
<template v-slot:right>
<Dropdown v-model="taskFilter" class="p-m-2" :options="taskFilterOptions"
optionLabel="optionName" placeholder="Filter tasks"/>
<Button class="p-button-raised p-m-2" label="Master Logs"
icon="las la-terminal" @click="showConsole('log/MASTER')"/>
<Button class="p-button-raised p-button-secondary p-m-2" label="Tasks Cleanup"
icon="las la-trash" @click="onClickTasksCleanup()"/>
</template>
</Toolbar>
<Toolbar v-for="task in tasks" :key="task.taskid">
<template v-slot:left>
<div style="width: 100%; overflow-x: auto;" class="p-d-flex p-ai-center">
<span>#{{task.taskid}}</span>
<i class="hspacer"></i>
<Button v-for="(job, idx) in task.runList" :key="idx" :label="job.jobname"
:icon="chipIcon(job)" :class="chipClass(job)" :badge="chipBadge(job)"
badgeClass="p-badge-warning" @click="onClickTaskLog(task.taskid, idx)"/>
</div>
</template>
<template v-slot:right>
<Button class="p-button-text p-m-2" icon="las la-terminal"
@click="onClickTaskLog(task.taskid)"/>
<Button class="p-button-text p-m-2" icon="las la-user-secret"
@click="onClickLog('task', task.taskid)"/>
<Button class="p-button-text p-m-2" icon="las la-times"
@click="onClickDeleteTask(task.taskid)"/>
</template>
</Toolbar>
<ProgressBar mode="indeterminate" v-show="task_loading" class="bottom_progress"/>
</Fieldset>
<Fieldset legend="Github Workflows" class="p-mt-4">
<Toolbar>
<template v-slot:right>
<InputText type="text" placeholder="Filter Repository ..." v-model="gh_filter"/>
</template>
</Toolbar>
<div v-for="(wf, key) in gh_workflows" :key="key" style="position: relative">
<div v-show="gh_filter.trim() === '' || key.includes(gh_filter)" class="p-py-6">
<ProgressBar mode="indeterminate" v-show="wf.loading" class="bottom_progress"/>
<Toolbar>
<template v-slot:left>
<i class="lab la-github-alt"></i>
<i class="hspacer"></i>
<a :href="'https://github.com/' + wf.repo" target="_blank">{{wf.repo}}</a>
</template>
<template v-slot:right>
<div class="p-m-2">
<i class="las la-sync"></i>
Refresh
<i class="hspacer"></i>
<InputSwitch v-model="wf.refresh"/>
</div>
</template>
</Toolbar>
<DataTable :value="wf.recent_runs" style="width: 100%"
:scrollable="true" selectionMode="single">
<Column field="workflow_name" header="Workflow"></Column>
<Column field="head_branch" header="Branch"></Column>
<Column field="head_sha" header="Commit"></Column>
<Column field="created" header="Created"></Column>
<Column field="updated" header="Updated"></Column>
<Column header="State">
<template #body="slotProps">
<div :class="slotProps.data.css_class">
<a :href="slotProps.data.url" target="_blank"
style="color: var(--primary-color-text);">
{{slotProps.data.state}}
</a>
</div>
</template>
</Column>
</DataTable>
</div>
</div>
</Fieldset>
</div>
</div>
</div>
<!-- placeholder to compensate bottom overlay console -->
<div style="height: 500px"></div>
<Sidebar :visible="console_show" class="p-sidebar-lg" :showCloseIcon="false"
:position="console_full ? 'full' : 'bottom'" :modal="false">
<div class="p-grid p-fluid p-jc-between console_head">
<h4 class="p-ml-4">{{console_title}}</h4>
<div class="p-d-flex p-ai-center">
<span class="p-mr-2">
<i class="pi pi-refresh"></i>
Auto refresh
</span>
<Checkbox v-model="console_refresh" :binary="true"/>
</div>
<div class="p-d-flex p-ai-center">
<span class="p-mr-2">
<i class="pi pi-sort-down"></i>
Stick to bottom
</span>
<Checkbox v-model="console_stickbt" :binary="true"/>
</div>
<div class="p-d-flex p-ai-center">
<span class="p-mr-2">
<i class="pi pi-palette"></i>
Use Xterm
</span>
<Checkbox v-model="use_xterm" :binary="true"/>
</div>
<div>
<Button class="p-button-text" :icon="console_full ? 'las la-download' : 'las la-upload'"
@click="console_full=!console_full"/>
<Button class="p-button-text" icon="las la-times"
@click="updateRecurFetcher('console_fetcher'); console_show = false"/>
</div>
</div>
<div style="height: 100%; position: relative" class="p-mt-3">
<ProgressBar mode="indeterminate" v-show="console_loading" style="z-index:9"/>
<div v-if="use_xterm" id="xterm_console" class="p-shadow-4 abstop"></div>
<pre v-else id="console" class="console p-shadow-4 abstop">
{{console_content}}
</pre>
</div>
</Sidebar>
</template>
<script>
const calabash_url = CALABASH_URL
const workflow_num = 6
const axios = require('axios')
const dayjs = require('dayjs')
const relativeTime = require('dayjs/plugin/relativeTime')
dayjs.extend(relativeTime)
const Terminal = require('xterm').Terminal
const FitAddon = require('xterm-addon-fit').FitAddon
module.exports = {
mounted: function() {
const vm = this
vm.attachDefaultTheme()
vm.updateConfigs()
vm.updateJobList()
vm.updateTaskList()
setTimeout(vm.updateWorkflows, 1 * 1000)
setInterval(vm.updateWorkflows, 10 * 1000)
vm.xterm = new Terminal({
disableStdin: true,
cols: 160,
convertEol: true /* important to make newline alignment correct */
})
vm.xterm_fit_addon = new FitAddon()
vm.xterm.loadAddon(vm.xterm_fit_addon)
},
watch: {
use_xterm: function(inUse) {
if (inUse) {
this.$nextTick(function() {
this.xterm.open(document.getElementById('xterm_console'))
this.xterm_fit_addon.fit()
this.xterm.clear()
this.xterm.write(this.console_content)
})
}
},
console_content: function(newContent, oldContent) {
if (this.use_xterm) {
if (newContent.startsWith(oldContent)) {
const appendContent = newContent.slice(oldContent.length)
this.xterm.write(appendContent)
} else {
this.xterm.clear()
this.xterm.write(newContent)
}
if (this.console_stickbt) {
const vm = this
setTimeout(function() {
vm.xterm.scrollToBottom()
}, 100)
}
}
},
nightTheme: function(becomeNightTheme, _) {
if (becomeNightTheme) {
this.changeTheme('night.css')
} else {
this.changeTheme('light.css')
}
},
selectedHistory: function(selectedJob) {
if (selectedJob && 'jobname' in selectedJob)
this.input_job = selectedJob['jobname']
},
taskFilter: function(filter) {
this.updateTaskList()
},
tasks: function(newTasks) {
vm = this
newTasks.forEach((task) => {
/* copy run list */
const runList = JSON.parse(JSON.stringify(task.runList))
/* allocate an pseudo item to ensure item[0] and [1] are accessible */
runList.push({exitcode: 0})
/* prohibit loading task output from unfinished job */
if (runList.some(j => j.exitcode !== 0)) {
return
}
if (task.taskid == 1) {
const log = runList[1].log || ''
vm.cluster_iaas_nodes = vm.parseJSON(log, vm.cluster_iaas_nodes)
vm.cluster_iaas_nodes = vm.cluster_iaas_nodes.map(item => {
item.inject_ip = item.ip.join(', ')
return item
})
} else if (task.taskid == 2) {
const log = runList[0].log || ''
vm.cluster_swarm_nodes = vm.parseJSON(log, vm.cluster_swarm_nodes)
vm.cluster_swarm_nodes = vm.cluster_swarm_nodes.map(item => {
const MemoryBytes = item['Description']['Resources']['MemoryBytes']
const MemoryGB = Math.round(MemoryBytes / (1024 * 1024 * 1024))
item.inject_memory = `${MemoryGB} GB`
/* See https://github.com/moby/moby/blob/v1.12.0-rc4
/daemon/cluster/executor/container/container.go#L328-L332 */
const CPUPeriod = 100
const NanoCPUs = item['Description']['Resources']['NanoCPUs']
item.inject_cpu = NanoCPUs * CPUPeriod / parseFloat('1e9')
const Labels = item['Spec']['Labels']
item.inject_labels = JSON.stringify(Labels)
return item
})
} else if (task.taskid == 3) {
const log = runList[0].log || ''
vm.cluster_services = vm.parseJSON(log, vm.cluster_services)
vm.cluster_services = vm.cluster_services.map(item => {
const Labels = item['Spec']['Labels']
item.inject_labels = JSON.stringify(Labels)
const createtime = item['CreatedAt']
item.inject_createtime = dayjs(createtime).fromNow()
const updatetime = item['UpdatedAt']
item.inject_updatetime = dayjs(updatetime).fromNow()
const Constraints = item['Spec']['TaskTemplate']['Placement']['Constraints']
item.inject_constraints = JSON.stringify(Constraints)
const Ports = item['Endpoint']['Ports']
item.inject_ports = JSON.stringify(Ports)
return item
})
} else if (task.taskid == 4) {
const log = runList[0].log || ''
vm.cluster_tasks = vm.parseJSON(log, vm.cluster_tasks)
vm.cluster_tasks = vm.cluster_tasks.map(item => {
const createtime = item['CreatedAt']
item.inject_createtime = dayjs(createtime).fromNow()
const updatetime = item['UpdatedAt']
item.inject_updatetime = dayjs(updatetime).fromNow()
const timestamp = item['CreatedAt']
item.inject_timestamp = dayjs(timestamp).format('YYYY/MM/DD HH:mm')
return item
})
}
})
},
cluster_iaas_nodes: function() {
this.updateClusterTree()
},
cluster_swarm_nodes: function() {
this.updateClusterTree()
},
cluster_services: function() {
this.updateClusterTree()
},
cluster_tasks: function() {
this.updateClusterTree()
},
clusterTreeSel: function() {
this.clusterTreeOnSelected()
},
center_dialog_show: function(onShow) {
if (!onShow) return
const about = this.center_dialog_for
const fields = this.center_dialog_model[about]
const vm = this
fields.forEach(field => {
field.options = []
if (field.label === 'Usage') {
const obj = vm.configs.node_usage
field.options = Object.keys(obj).map(name => {
return {
name: name,
meta: obj[name],
desc: vm.prettyJSON(obj[name])
}
})
} else if (field.label === 'IaaS Config') {
vm.configs.iaas.providers.forEach(provider => {
const cfg = vm.configs.iaas[provider]
const keys = Object.keys(cfg).filter(nm => nm.startsWith('config_'))
keys.forEach(key => {
field.options.push({
name: `${provider}_${key}`,
meta: cfg[key],
desc: vm.prettyJSON(cfg[key])
})
})
})
} else if (field.label === 'Service') {
field.options = vm.services.map(srv => {
return {
name: srv.name,
meta: srv.meta,
desc: vm.prettyJSON(srv.meta)
}
})
} else {
throw new Error('No desired config entry!')
}
})
}
},
computed: {
services() {
const vm = this
const raw_services = vm.configs.service || {}
return Object.keys(raw_services).reduce((dict, key) => {
const val = raw_services[key]
if (!Array.isArray(val) && typeof(val) !== 'string') {
dict.push({
name: key,
meta: val
})
}
return dict
}, [])
}
},
data: function() {
return {
logo: require('./resource/logo-128.png'),
gh_workflows: {},
gh_filter: '',
tasks: [],
task_loading: false,
taskFetcher: null,
taskFilter: {name: 'recent'},
taskFilterOptions: [
{name: 'recent', optionName: 'Recent and active tasks'},
{name: 'active', optionName: 'Only active tasks'},
{name: 'inactive', optionName: 'Only inactive tasks'}
],
configs: {},
nightTheme: false,
input_job: '',
menu_model: [],
selectedHistory: '',
jobHistory: [],
tabViewActiveIndex: 0,
top_dialog_show: false,
top_dialog_title: '',
top_dialog_content: '',
top_dialog_maximizable: false,
center_dialog_show: false,
center_dialog_for: '',
center_dialog_model: {
'Add Node': [
{
label: 'Usage',
value: '', /* chosen option */
options: []
},
{
label: 'IaaS Config',
value: '',
options: []
}
],
'Create Service': [
{
label: 'Service',
value: '', /* chosen option */
options: []
}
]
},
lastDisplayError: null,
run_btn_model: [
{
label: 'Run and follow logs',
icon: 'pi pi-circle-on',
command: () => {
this.runJob(false, false, true)
}
},
{
label: 'Run as single job',
icon: 'pi pi-chevron-circle-right',
command: () => {
this.runJob(false, true, false)
}
},
{
label: 'Dry run',
icon: 'pi pi-minus-circle',
command: () => {
this.runJob(true, false, false)
}
}
],
log_btn_model: [
{
label: 'Job logs',
icon: 'pi pi-file',
command: () => {
this.onClickLog('job', this.input_job)
}
}
],
clusterTree: [],
clusterTreeTopLevel: false,
clusterTreeSel: null,
clusterTreeSelModel: [],
cluster_iaas_nodes: [],
cluster_swarm_nodes: [],
cluster_services: [],
cluster_tasks: [],
xterm: null,
xterm_fit_addon: null,
use_xterm: false,
console_show: false,
console_full: false,
console_refresh: true,
console_stickbt: true,
console_title: 'Console',
console_content: '',
console_loading: false,
console_fetcher: null
}
},
methods: {
parseJSON(json, oldObj) {
if (json.trim() === '')
return oldObj
try {
const obj = JSON.parse(json)
return obj
} catch (err) {
vm.displayMessage('error', err.toString(), json)
return oldObj
}
},
prettyJSON(json) {
return JSON.stringify(json, null, 2).replaceAll('\\n', '\n')
},
chipIcon(taskJob) {
/* Example:
jobname: "ucloud:source"
alive: false
exitcode: 0
pid: -1
spawn_time: 1603881900897
exit_time: 1603881900898
*/
if (taskJob.alive)
return 'las la-running'
else if (taskJob.exitcode == 0)
return 'las la-check'
else if (taskJob.pid < 0)
return 'las la-clock'
else
return 'las la-exclamation-triangle'
},
chipClass(taskJob) {
const baseclass = "p-ml-2 p-mt-2 p-button-sm p-button-rounded "
if (taskJob.alive)
return baseclass + 'p-button-info'
else if (taskJob.exitcode == 0)
return baseclass + 'p-button-success'
else if (taskJob.pid < 0)
return baseclass + 'p-button-outlined p-button-text p-button-plain'
else
return baseclass + 'p-button-danger'
},
chipBadge(taskJob) {
if (!taskJob.alive && taskJob.pid >= 0) {
const spawn_time = taskJob.spawn_time
const exit_time = taskJob.exit_time
const time_cost = Math.round((exit_time - spawn_time) / 1000)
if (time_cost == 0) {
return ''
} else {
return `${time_cost}`
}
} else {
return ''
}
},
changeTheme(cssFile) {
let theme = document.getElementById("theme")
theme.href = cssFile
},
attachDefaultTheme() {
const theme = document.createElement('link')
theme.type = "text/css"
theme.rel = "stylesheet"
theme.id = "theme"
theme.href = 'light.css' /* default */
document.head.appendChild(theme)
},
displayMessage(type, summary, detail, life) {
const displayLife = 5000
const vm = this
if (vm.lastDisplayError !== null && type === 'error') {
/* to avoid too frequent error messages */
return
}
const max_detail_len = 256
if (detail && detail.length > max_detail_len)
detail = detail.substr(0, max_detail_len) + ' ...'
vm.$toast.add({
severity: type || 'success',
summary: summary,
detail: detail,
life: life || displayLife
})
vm.lastDisplayError = setTimeout(function() {
vm.lastDisplayError = null
}, displayLife)
},
extractRequiredArgs(exec) {
let exes = exec
if (!Array.isArray(exes)) {
exes = exes.split('\n')
}
for (var i = 0; i < exes.length; i ++) {
const str = exes[i]
if (str.includes('require_args')) {
let args = str.split(' ')
args.shift()
args = args.map(v => v + '=' + v.toUpperCase())
return '?' + args.join('&')
}
}
return ''
},
loginRedirect(axiosRet) {
/* rewrite original AJAX target URL to this page */
const redirectURI = axiosRet.request.responseURL.split('?')[0]
const currentURL = window.location.href
const redirectURL = redirectURI + '?next=' + encodeURIComponent(currentURL)
setTimeout(function() {
window.location.replace(redirectURL)
/* replace() is better than `window.location.href = ...' because
* it does not keep the originating page in the session history,
* meaning the user won't get stuck in a never-ending back-button fiasco.
*/
}, 3000)
this.displayMessage('error', 'No permission', 'Redirecting in a few seconds...')
},
updateConfigs() {
const vm = this
axios.get(`${calabash_url}/get/config`)
.then(res => {
const data = res.data
vm.configs = data
})
.catch(err => {
vm.displayMessage('error', 'Error', err.toString())
})
},
updateJobList() {
const vm = this
axios.get(`${calabash_url}/get/jobs`)
.then(res => {
const data = res.data
const items = data.jobs.reduce((dict, cur) => {
const [scope, act] = cur.name.split(':')
const exec = cur.props.exec || ''
const params = vm.extractRequiredArgs(exec)
if (scope in dict) {
dict[scope].push({
label: act,
command: () => {
vm.input_job = cur.name + params
}
})
} else {
dict[scope] = [{
label: act,
command: () => {
vm.input_job = cur.name + params
}
}]
}
vm.pushJobHistory(cur.name + params)
return dict
}, {})
const model = Object.keys(items).map((key) => {
return {
label: key,
items: items[key]
}
})
vm.menu_model = [
{label: 'Job List', icon: 'pi pi-fw pi-list'},
{separator: true},
...model
]
})
.catch(err => {
vm.displayMessage('error', 'Error', err.toString())
})
},
showJob() {
const jobname = this.input_job
const vm = this
if (jobname.trim() === '') {
vm.displayMessage('warn', 'Please enter a job name')
return
}
axios.get(`${calabash_url}/get/job/${jobname}`)
.then(res => {
const data = res.data
vm.top_dialog_show = true
vm.top_dialog_maximizable = false
vm.top_dialog_content = JSON.stringify(data.props, null, 2)
vm.top_dialog_title = data.jobname
})
.catch(err => {
vm.displayMessage('error', 'Error', err.toString())
})
},
showConfigs() {
const cfg = this.configs
this.top_dialog_show = true
this.top_dialog_maximizable = true
this.top_dialog_content = JSON.stringify(cfg, null, 2).replaceAll('\\n', '\n')
this.top_dialog_title = 'Configurations'
},
pushJobHistory(jobname) {
const jobnames = this.jobHistory.map(item => item.jobname)
if (jobnames.indexOf(jobname) == -1) {
this.jobHistory.unshift({jobname})
if (this.jobHistory.length > 30)
this.jobHistory.pop()
}
},
updateRecurFetcher(fetcherName, callbk) {
if (this[fetcherName] !== null) {
clearTimeout(this[fetcherName])
}
this[fetcherName] = (callbk || null)
},
updateTaskList() {
const vm = this
const taskFilter = this.taskFilter.name
function fetcher() {
vm.task_loading = true
axios.get(`${calabash_url}/get/tasks/${taskFilter}`)
.then(res => {
const data = res.data
vm.tasks = data.all_tasks.reverse()
vm.task_loading = false
vm.updateRecurFetcher('taskFetcher', setTimeout(fetcher, 2000))
})
.catch(err => {
vm.displayMessage('error', 'Error', err.toString())
vm.updateRecurFetcher('taskFetcher', setTimeout(fetcher, 2000))
})
}
vm.updateRecurFetcher('taskFetcher', setTimeout(fetcher, 0))
},
runJob(dryrun, single, follow) {
const jobname = this.input_job
const vm = this
if (jobname.trim() === '') {
vm.displayMessage('warn', 'Please enter a job name')
return
}
const options = {
goal: jobname,
dry_run: dryrun || false,
single_job: single || false,
insist_job: false,
pin_id_job: false
}
axios.post(`${calabash_url}/runjob`, options)
.then(function (res) {
const contentType = res.headers['content-type']
if (contentType.includes('application/json')) {
const data = res.data
if (data.error)
throw new Error(data.error)
vm.displayMessage('success', jobname, JSON.stringify(data))
vm.updateTaskList()
/* do we open console to follow logs? */
if (follow) {
const taskID = data['task_id']
taskID && vm.onClickTaskLog(taskID)
}
} else {
vm.loginRedirect(res)
}
})
.catch(function (err) {
vm.displayMessage('error', 'Error', err.toString())
})
/* push to job history */
this.pushJobHistory(jobname)
},
onClickTaskLog(taskID, idx) {
this.showConsole(`task/${taskID}`, idx)
},
onClickLog(type, id) {
if (typeof id === 'string' && id.trim() === '') {
this.displayMessage('warn', 'Please enter a log ID')
return
}
this.showConsole(`log/${type}-${id}`)
},
collectTaskJobLogs(runList) {
return runList.reduce((logs, taskJob) => {
logs += taskJob['log']
return logs
}, '')
},
onClickTasksCleanup() {
axios.delete(`${calabash_url}/del/inactive_tasks`)
.then(res => {
const data = res.data
if (data.error)
throw new Error(data.error)
vm.displayMessage('success', 'Task Cleanup', JSON.stringify(data))
})