-
Notifications
You must be signed in to change notification settings - Fork 83
/
logs.go
260 lines (222 loc) · 6.75 KB
/
logs.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
248
249
250
251
252
253
254
255
256
257
258
259
260
package logs
import (
"context"
"fmt"
"os"
"os/exec"
"path/filepath"
"strings"
"syscall"
"github.com/AlecAivazis/survey/v2"
"github.com/jonboulle/clockwork"
"github.com/openshift-pipelines/pipelines-as-code/pkg/apis/pipelinesascode/keys"
"github.com/openshift-pipelines/pipelines-as-code/pkg/apis/pipelinesascode/v1alpha1"
"github.com/openshift-pipelines/pipelines-as-code/pkg/cli"
"github.com/openshift-pipelines/pipelines-as-code/pkg/cli/browser"
"github.com/openshift-pipelines/pipelines-as-code/pkg/cli/prompt"
"github.com/openshift-pipelines/pipelines-as-code/pkg/cmd/tknpac/completion"
"github.com/openshift-pipelines/pipelines-as-code/pkg/consoleui"
"github.com/openshift-pipelines/pipelines-as-code/pkg/formatting"
"github.com/openshift-pipelines/pipelines-as-code/pkg/params"
"github.com/openshift-pipelines/pipelines-as-code/pkg/sort"
"github.com/spf13/cobra"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
)
const longhelp = `
logs - show the PipelineRun logs attached to a Repository
tkn pac logs will get the logs of a PipelineRun belonging to a Repository.
the PipelineRun needs to exist on the kubernetes cluster to be able to display the logs.`
const (
namespaceFlag = "namespace"
limitFlag = "limit"
tknPathFlag = "tkn-path"
defaultLimit = -1
openWebBrowserFlag = "web"
useLastPipelineRunFlag = "last"
)
type logOption struct {
cs *params.Run
cw clockwork.Clock
opts *cli.PacCliOpts
ioStreams *cli.IOStreams
repoName string
tknPath string
limit int
webBrowser bool
useLastPR bool
}
func Command(run *params.Run, ioStreams *cli.IOStreams) *cobra.Command {
cmd := &cobra.Command{
Use: "logs",
Long: longhelp,
Short: "Display the PipelineRun logs from a Repository",
Annotations: map[string]string{
"commandType": "main",
},
ValidArgsFunction: completion.ParentCompletion,
RunE: func(cmd *cobra.Command, args []string) error {
var err error
var repoName string
opts := cli.NewCliOptions(cmd)
opts.Namespace, err = cmd.Flags().GetString(namespaceFlag)
if err != nil {
return err
}
if len(args) > 0 {
repoName = args[0]
}
ctx := context.Background()
err = run.Clients.NewClients(ctx, &run.Info)
if err != nil {
return err
}
limit, err := cmd.Flags().GetInt(limitFlag)
if err != nil {
return err
}
webBrowser, err := cmd.Flags().GetBool(openWebBrowserFlag)
if err != nil {
return err
}
useLastPR, err := cmd.Flags().GetBool(useLastPipelineRunFlag)
if err != nil {
return err
}
tknPath, err := cmd.Flags().GetString(tknPathFlag)
if err != nil {
return err
}
if tknPath == "" {
if tknPath, err = getTknPath(); err != nil {
return err
}
if tknPath == "" {
return fmt.Errorf("cannot find tkn binary in Path")
}
}
lopts := &logOption{
cs: run,
cw: clockwork.NewRealClock(),
opts: opts,
ioStreams: ioStreams,
repoName: repoName,
limit: limit,
webBrowser: webBrowser,
tknPath: tknPath,
useLastPR: useLastPR,
}
return log(ctx, lopts)
},
}
cmd.Flags().StringP(
tknPathFlag, "", "", "Path to the tkn binary (default to search for it in you $PATH)")
cmd.Flags().StringP(
namespaceFlag, "n", "", "If present, the namespace scope for this CLI request")
_ = cmd.RegisterFlagCompletionFunc(namespaceFlag,
func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) {
return completion.BaseCompletion(namespaceFlag, args)
},
)
cmd.Flags().BoolP(
openWebBrowserFlag, "w", false, "Open Web browser to detected console instead of using tkn")
cmd.Flags().BoolP(
useLastPipelineRunFlag, "L", false, "show logs of the last PipelineRun")
cmd.Flags().IntP(
limitFlag, "", defaultLimit, "Limit the number of PipelineRun to show (-1 is unlimited)")
return cmd
}
func getTknPath() (string, error) {
fname, err := exec.LookPath("tkn")
if err != nil {
return "", err
}
return filepath.Abs(fname)
}
// getPipelineRunsToRepo returns all pipelinesruns running in a namespace
func getPipelineRunsToRepo(ctx context.Context, lopt *logOption, repoName string) ([]string, error) {
opts := metav1.ListOptions{
LabelSelector: fmt.Sprintf("%s=%s",
keys.Repository, repoName),
}
runs, err := lopt.cs.Clients.Tekton.TektonV1beta1().PipelineRuns(lopt.opts.Namespace).List(ctx, opts)
if err != nil {
return []string{}, err
}
runslen := len(runs.Items)
if runslen > 1 {
sort.PipelineRunSortByStartTime(runs.Items)
}
if lopt.limit > runslen {
lopt.limit = runslen
}
ret := []string{}
for i, run := range runs.Items {
label := "running since"
date := run.Status.StartTime
if run.Status.CompletionTime != nil {
label = "completed"
date = run.Status.CompletionTime
}
if lopt.limit > -1 && i > lopt.limit {
continue
}
ret = append(ret, fmt.Sprintf("%s %s %s", run.ObjectMeta.Name, label, formatting.Age(date, lopt.cw)))
}
return ret, nil
}
func log(ctx context.Context, lo *logOption) error {
var repository *v1alpha1.Repository
var err error
if lo.opts.Namespace != "" {
lo.cs.Info.Kube.Namespace = lo.opts.Namespace
}
if lo.repoName != "" {
repository, err = lo.cs.Clients.PipelineAsCode.PipelinesascodeV1alpha1().Repositories(lo.cs.Info.Kube.Namespace).Get(ctx,
lo.repoName, metav1.GetOptions{})
if err != nil {
return err
}
} else {
repository, err = prompt.SelectRepo(ctx, lo.cs, lo.cs.Info.Kube.Namespace)
if err != nil {
return err
}
}
allprs, err := getPipelineRunsToRepo(ctx, lo, repository.GetName())
if err != nil {
return err
}
if len(allprs) == 0 {
return fmt.Errorf("cannot detect pipelineruns belonging to repository: %s", repository.GetName())
}
var replyString string
if lo.useLastPR || len(allprs) == 1 {
replyString = allprs[0]
} else {
if err := prompt.SurveyAskOne(&survey.Select{
Message: "Select a PipelineRun",
Options: allprs,
}, &replyString); err != nil {
return err
}
}
replyName := strings.Fields(replyString)[0]
if lo.webBrowser {
return showLogsWithWebConsole(lo, replyName)
}
return showlogswithtkn(lo.tknPath, replyName, lo.cs.Info.Kube.Namespace)
}
func showLogsWithWebConsole(lo *logOption, pr string) error {
if os.Getenv("PAC_TEKTON_DASHBOARD_URL") != "" {
lo.cs.Clients.ConsoleUI = &consoleui.TektonDashboard{BaseURL: os.Getenv("PAC_TEKTON_DASHBOARD_URL")}
}
return browser.OpenWebBrowser(lo.cs.Clients.ConsoleUI.DetailURL(lo.cs.Info.Kube.Namespace, pr))
}
func showlogswithtkn(tknPath, pr, ns string) error {
//nolint: gosec
if err := syscall.Exec(tknPath, []string{tknPath, "pr", "logs", "-f", "-n", ns, pr}, os.Environ()); err != nil {
fmt.Fprintf(os.Stderr, "Command finished with error: %v", err)
os.Exit(127)
}
return nil
}