forked from argoproj/argo-workflows
/
list.go
247 lines (232 loc) · 7.25 KB
/
list.go
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
package commands
import (
"fmt"
"log"
"os"
"regexp"
"sort"
"strconv"
"strings"
"text/tabwriter"
"time"
wfv1 "github.com/argoproj/argo/pkg/apis/workflow/v1alpha1"
"github.com/argoproj/argo/pkg/client/clientset/versioned/typed/workflow/v1alpha1"
"github.com/argoproj/argo/workflow/common"
humanize "github.com/dustin/go-humanize"
"github.com/spf13/cobra"
apiv1 "k8s.io/api/core/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/labels"
"k8s.io/apimachinery/pkg/selection"
)
type listFlags struct {
allNamespaces bool // --all-namespaces
status string // --status
completed bool // --completed
running bool // --running
output string // --output
since string // --since
}
func NewListCommand() *cobra.Command {
var (
listArgs listFlags
)
var command = &cobra.Command{
Use: "list",
Short: "list workflows",
Run: func(cmd *cobra.Command, args []string) {
var wfClient v1alpha1.WorkflowInterface
if listArgs.allNamespaces {
wfClient = InitWorkflowClient(apiv1.NamespaceAll)
} else {
wfClient = InitWorkflowClient()
}
listOpts := metav1.ListOptions{}
labelSelector := labels.NewSelector()
if listArgs.status != "" {
req, _ := labels.NewRequirement(common.LabelKeyPhase, selection.In, strings.Split(listArgs.status, ","))
labelSelector = labelSelector.Add(*req)
}
if listArgs.completed {
req, _ := labels.NewRequirement(common.LabelKeyCompleted, selection.Equals, []string{"true"})
labelSelector = labelSelector.Add(*req)
}
if listArgs.running {
req, _ := labels.NewRequirement(common.LabelKeyCompleted, selection.NotEquals, []string{"true"})
labelSelector = labelSelector.Add(*req)
}
listOpts.LabelSelector = labelSelector.String()
wfList, err := wfClient.List(listOpts)
if err != nil {
log.Fatal(err)
}
var workflows []wfv1.Workflow
if listArgs.since == "" {
workflows = wfList.Items
} else {
workflows = make([]wfv1.Workflow, 0)
minTime := parseSince(listArgs.since)
for _, wf := range wfList.Items {
if wf.Status.FinishedAt.IsZero() || wf.ObjectMeta.CreationTimestamp.After(minTime) {
workflows = append(workflows, wf)
}
}
}
sort.Sort(ByFinishedAt(workflows))
switch listArgs.output {
case "", "wide":
printTable(workflows, &listArgs)
case "name":
for _, wf := range workflows {
fmt.Println(wf.ObjectMeta.Name)
}
default:
log.Fatalf("Unknown output mode: %s", listArgs.output)
}
},
}
command.Flags().BoolVar(&listArgs.allNamespaces, "all-namespaces", false, "Show workflows from all namespaces")
command.Flags().StringVar(&listArgs.status, "status", "", "Filter by status (comma separated)")
command.Flags().BoolVar(&listArgs.completed, "completed", false, "Show only completed workflows")
command.Flags().BoolVar(&listArgs.running, "running", false, "Show only running workflows")
command.Flags().StringVarP(&listArgs.output, "output", "o", "", "Output format. One of: wide|name")
command.Flags().StringVar(&listArgs.since, "since", "", "Show only workflows newer than a relative duration")
return command
}
var sinceRegex = regexp.MustCompile("^(\\d+)([smhd])$")
var timeMagnitudes = []humanize.RelTimeMagnitude{
{D: time.Second, Format: "0s", DivBy: time.Second},
{D: 2 * time.Second, Format: "1s %s", DivBy: 1},
{D: time.Minute, Format: "%ds %s", DivBy: time.Second},
{D: 2 * time.Minute, Format: "1m %s", DivBy: 1},
{D: time.Hour, Format: "%dm %s", DivBy: time.Minute},
{D: 2 * time.Hour, Format: "1h %s", DivBy: 1},
{D: humanize.Day, Format: "%dh %s", DivBy: time.Hour},
{D: 2 * humanize.Day, Format: "1d %s", DivBy: 1},
}
func printTable(wfList []wfv1.Workflow, listArgs *listFlags) {
w := tabwriter.NewWriter(os.Stdout, 0, 0, 3, ' ', 0)
if listArgs.allNamespaces {
fmt.Fprint(w, "NAMESPACE\t")
}
fmt.Fprint(w, "NAME\tSTATUS\tAGE\tDURATION")
if listArgs.output == "wide" {
fmt.Fprint(w, "\tR/C\tPARAMETERS")
}
fmt.Fprint(w, "\n")
for _, wf := range wfList {
cTime := time.Unix(wf.ObjectMeta.CreationTimestamp.Unix(), 0)
ageStr := humanize.CustomRelTime(cTime, time.Now(), "", "", timeMagnitudes)
durationStr := humanizeDurationShort(wf.Status.StartedAt, wf.Status.FinishedAt)
if listArgs.allNamespaces {
fmt.Fprintf(w, "%s\t", wf.ObjectMeta.Namespace)
}
fmt.Fprintf(w, "%s\t%s\t%s\t%s", wf.ObjectMeta.Name, worklowStatus(&wf), ageStr, durationStr)
if listArgs.output == "wide" {
running, completed := countCompletedRunning(&wf)
fmt.Fprintf(w, "\t%d/%d", running, completed)
fmt.Fprintf(w, "\t%s", parameterString(wf.Spec.Arguments.Parameters))
}
fmt.Fprintf(w, "\n")
}
_ = w.Flush()
}
func countCompletedRunning(wf *wfv1.Workflow) (int, int) {
completed := 0
running := 0
for _, node := range wf.Status.Nodes {
if len(node.Children) > 0 {
// not a pod
// TODO: this will change after DAG implementation
continue
}
if node.Completed() {
completed++
} else {
running++
}
}
return running, completed
}
// parameterString returns a human readable display string of the parameters, truncating if necessary
func parameterString(params []wfv1.Parameter) string {
truncateString := func(str string, num int) string {
bnoden := str
if len(str) > num {
if num > 3 {
num -= 3
}
bnoden = str[0:num-15] + "..." + str[len(str)-15:]
}
return bnoden
}
pStrs := make([]string, 0)
for _, p := range params {
if p.Value != nil {
str := fmt.Sprintf("%s=%s", p.Name, truncateString(*p.Value, 50))
pStrs = append(pStrs, str)
}
}
return strings.Join(pStrs, ",")
}
// ByFinishedAt is a sort interface which sorts running jobs earlier before considering FinishedAt
type ByFinishedAt []wfv1.Workflow
func (f ByFinishedAt) Len() int { return len(f) }
func (f ByFinishedAt) Swap(i, j int) { f[i], f[j] = f[j], f[i] }
func (f ByFinishedAt) Less(i, j int) bool {
iStart := f[i].ObjectMeta.CreationTimestamp
iFinish := f[i].Status.FinishedAt
jStart := f[j].ObjectMeta.CreationTimestamp
jFinish := f[j].Status.FinishedAt
if iFinish.IsZero() && jFinish.IsZero() {
return !iStart.Before(&jStart)
}
if iFinish.IsZero() && !jFinish.IsZero() {
return true
}
if !iFinish.IsZero() && jFinish.IsZero() {
return false
}
return jFinish.Before(&iFinish)
}
// workflowStatus returns a human readable inferred workflow status based on workflow phase and conditions
func worklowStatus(wf *wfv1.Workflow) wfv1.NodePhase {
switch wf.Status.Phase {
case wfv1.NodeRunning:
if common.IsWorkflowSuspended(wf) {
return "Running (Suspended)"
}
return wf.Status.Phase
case "":
if !wf.ObjectMeta.CreationTimestamp.IsZero() {
return "Pending"
}
return "Unknown"
default:
return wf.Status.Phase
}
}
// parseSince parses a since string and returns the time.Time in UTC
func parseSince(since string) time.Time {
matches := sinceRegex.FindStringSubmatch(since)
if len(matches) != 3 {
log.Fatalf("Invalid since format '%s'. Expected format <duration><unit> (e.g. 3h)\n", since)
}
amount, err := strconv.ParseInt(matches[1], 10, 64)
if err != nil {
log.Fatal(err)
}
var unit time.Duration
switch matches[2] {
case "s":
unit = time.Second
case "m":
unit = time.Minute
case "h":
unit = time.Hour
case "d":
unit = time.Hour * 24
}
ago := unit * time.Duration(amount)
return time.Now().UTC().Add(-ago)
}