Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add EventListener Logs Command #1192

Merged
merged 1 commit into from
Oct 7, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions docs/cmd/tkn_eventlistener.md
Original file line number Diff line number Diff line change
Expand Up @@ -30,4 +30,5 @@ Manage eventlisteners
* [tkn eventlistener delete](tkn_eventlistener_delete.md) - Delete EventListeners in a namespace
* [tkn eventlistener describe](tkn_eventlistener_describe.md) - Describe EventListener in a namespace
* [tkn eventlistener list](tkn_eventlistener_list.md) - Lists eventlisteners in a namespace
* [tkn eventlistener logs](tkn_eventlistener_logs.md) - Show EventListener logs

45 changes: 45 additions & 0 deletions docs/cmd/tkn_eventlistener_logs.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
## tkn eventlistener logs

Show EventListener logs

### Usage

```
tkn eventlistener logs
```

### Synopsis

Show EventListener logs

### Examples


Show logs of EventListener pods:

tkn eventlistener logs eventlistenerName

Show 2 lines of most recent logs from all EventListener pods:

tkn eventlistener logs eventListenerName -t 2

### Options

```
-h, --help help for logs
-t, --tail int Number of most recent log lines to show. Specify -1 for all logs from each pod. (default 10)
```

### Options inherited from parent commands

```
-c, --context string name of the kubeconfig context to use (default: kubectl config current-context)
-k, --kubeconfig string kubectl config file (default: $HOME/.kube/config)
-n, --namespace string namespace to use (default: from $KUBECONFIG)
-C, --nocolour disable colouring (default: false)
```

### SEE ALSO

* [tkn eventlistener](tkn_eventlistener.md) - Manage eventlisteners

1 change: 1 addition & 0 deletions docs/cmd/tkn_taskrun_logs.md
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ Show TaskRuns logs

### Examples


Show the logs of TaskRun named 'foo' from the namespace 'bar':

tkn taskrun logs foo -n bar
Expand Down
77 changes: 77 additions & 0 deletions docs/man/man1/tkn-eventlistener-logs.1
Original file line number Diff line number Diff line change
@@ -0,0 +1,77 @@
.TH "TKN\-EVENTLISTENER\-LOGS" "1" "" "Auto generated by spf13/cobra" ""
.nh
.ad l


.SH NAME
.PP
tkn\-eventlistener\-logs \- Show EventListener logs


.SH SYNOPSIS
.PP
\fBtkn eventlistener logs\fP


.SH DESCRIPTION
.PP
Show EventListener logs


.SH OPTIONS
.PP
\fB\-h\fP, \fB\-\-help\fP[=false]
help for logs

.PP
\fB\-t\fP, \fB\-\-tail\fP=10
Number of most recent log lines to show. Specify \-1 for all logs from each pod.


.SH OPTIONS INHERITED FROM PARENT COMMANDS
.PP
\fB\-c\fP, \fB\-\-context\fP=""
name of the kubeconfig context to use (default: kubectl config current\-context)

.PP
\fB\-k\fP, \fB\-\-kubeconfig\fP=""
kubectl config file (default: $HOME/.kube/config)

.PP
\fB\-n\fP, \fB\-\-namespace\fP=""
namespace to use (default: from $KUBECONFIG)

.PP
\fB\-C\fP, \fB\-\-nocolour\fP[=false]
disable colouring (default: false)


.SH EXAMPLE
.PP
Show logs of EventListener pods:

.PP
.RS

.nf
tkn eventlistener logs eventlistenerName

.fi
.RE

.PP
Show 2 lines of most recent logs from all EventListener pods:

.PP
.RS

.nf
tkn eventlistener logs eventListenerName \-t 2

.fi
.RE


.SH SEE ALSO
.PP
\fBtkn\-eventlistener(1)\fP
2 changes: 1 addition & 1 deletion docs/man/man1/tkn-eventlistener.1
Original file line number Diff line number Diff line change
Expand Up @@ -42,4 +42,4 @@ Manage eventlisteners

.SH SEE ALSO
.PP
\fBtkn(1)\fP, \fBtkn\-eventlistener\-delete(1)\fP, \fBtkn\-eventlistener\-describe(1)\fP, \fBtkn\-eventlistener\-list(1)\fP
\fBtkn(1)\fP, \fBtkn\-eventlistener\-delete(1)\fP, \fBtkn\-eventlistener\-describe(1)\fP, \fBtkn\-eventlistener\-list(1)\fP, \fBtkn\-eventlistener\-logs(1)\fP
1 change: 1 addition & 0 deletions pkg/cmd/eventlistener/eventlistener.go
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,7 @@ func Command(p cli.Params) *cobra.Command {
deleteCommand(p),
describeCommand(p),
listCommand(p),
logCommand(p),
)

return cmd
Expand Down
132 changes: 132 additions & 0 deletions pkg/cmd/eventlistener/logs.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,132 @@
// Copyright © 2020 The Tekton Authors.
//
// 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.

package eventlistener

import (
"bufio"
"bytes"
"fmt"
"io"

"github.com/spf13/cobra"
"github.com/tektoncd/cli/pkg/cli"
"github.com/tektoncd/cli/pkg/options"
corev1 "k8s.io/api/core/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
)

func logCommand(p cli.Params) *cobra.Command {
opts := options.NewLogOptions(p)

eg := `
Show logs of EventListener pods:

tkn eventlistener logs eventlistenerName

Show 2 lines of most recent logs from all EventListener pods:

tkn eventlistener logs eventListenerName -t 2`
c := &cobra.Command{
Use: "logs",
DisableFlagsInUseLine: true,
Short: "Show EventListener logs",
Example: eg,
SilenceUsage: true,
Annotations: map[string]string{
"commandType": "main",
},
Args: cobra.ExactValidArgs(1),
RunE: func(cmd *cobra.Command, args []string) error {
if opts.Tail <= 0 && opts.Tail != -1 {
return fmt.Errorf("tail cannot be 0 or less than 0 unless -1 for all pods")
}

err := getEventListener(args[0], p)
if err != nil {
return err
}

s := &cli.Stream{
Out: cmd.OutOrStdout(),
Err: cmd.OutOrStderr(),
}

return logs(args[0], p, s, opts)
},
}
c.Flags().Int64VarP(&opts.Tail, "tail", "t", 10, "Number of most recent log lines to show. Specify -1 for all logs from each pod.")
_ = c.MarkZshCompPositionalArgumentCustom(1, "__tkn_get_eventlistener")
return c
}

func getEventListener(elName string, p cli.Params) error {
cs, err := p.Clients()
if err != nil {
return fmt.Errorf("failed to create tekton client")
}

_, err = cs.Triggers.TriggersV1alpha1().EventListeners(p.Namespace()).Get(elName, metav1.GetOptions{})
if err != nil {
return fmt.Errorf("failed to get EventListener %s: %v", elName, err)
}

return nil
}

func logs(elName string, p cli.Params, s *cli.Stream, opts *options.LogOptions) error {
cs, err := p.Clients()
if err != nil {
return fmt.Errorf("failed to create tekton client")
}

elPods, err := cs.Kube.CoreV1().Pods(p.Namespace()).List(metav1.ListOptions{LabelSelector: "eventlistener=" + elName})
if err != nil {
return fmt.Errorf("failed to get pods for EventListener %s", elName)
}

if len(elPods.Items) == 0 {
fmt.Fprintf(s.Out, "No pods available for EventListener %s\n", elName)
return nil
}

for _, pod := range elPods.Items {
podName := pod.Name
podLopOpts := &corev1.PodLogOptions{}
// -1 represents getting all logs from each pod. Tail is 10 by default.
if opts.Tail != -1 {
podLopOpts.TailLines = &opts.Tail
}
podLogReq := cs.Kube.CoreV1().Pods(p.Namespace()).GetLogs(podName, podLopOpts)
podLogs, err := podLogReq.Stream()
if err != nil {
return err
}
defer podLogs.Close()

buf := new(bytes.Buffer)
_, err = io.Copy(buf, podLogs)
if err != nil {
return err
}

fmt.Println()
scanner := bufio.NewScanner(buf)
for scanner.Scan() {
fmt.Printf("[%s-%s]: "+scanner.Text()+"\n", elName, podName)
}
}

return nil
}
104 changes: 104 additions & 0 deletions pkg/cmd/eventlistener/logs_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,104 @@
package eventlistener

import (
"fmt"
"strings"
"testing"
"time"

"github.com/jonboulle/clockwork"
"github.com/spf13/cobra"
"github.com/tektoncd/cli/pkg/test"
"github.com/tektoncd/triggers/pkg/apis/triggers/v1alpha1"
triggertest "github.com/tektoncd/triggers/test"
"gotest.tools/v3/golden"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
)

func TestLogsEventListener(t *testing.T) {
now := time.Now()

els := []*v1alpha1.EventListener{
{
ObjectMeta: metav1.ObjectMeta{
Name: "eventlistener-no-pods",
},
},
}

tests := []struct {
name string
command *cobra.Command
args []string
wantError bool
goldenFile bool
want string
}{
{
name: "No arguments passed",
command: commandLogs(t, els, now),
args: []string{"logs"},
wantError: true,
goldenFile: false,
want: "accepts 1 arg(s), received 0",
},
{
name: "No EventListener found",
command: commandLogs(t, els, now),
args: []string{"logs", "notFound"},
wantError: true,
goldenFile: false,
want: "failed to get EventListener notFound: eventlisteners.triggers.tekton.dev \"notFound\" not found",
},
{
name: "No EventListener pods",
command: commandLogs(t, els, now),
args: []string{"logs", "eventlistener-no-pods"},
wantError: false,
goldenFile: false,
want: "No pods available for EventListener eventlistener-no-pods\n",
},
{
name: "Tail option as 0 results in error",
command: commandLogs(t, els, now),
args: []string{"logs", "eventlistener-no-pods", "-t", "0"},
wantError: true,
goldenFile: false,
want: "tail cannot be 0 or less than 0 unless -1 for all pods",
},
{
name: "Tail option as -2 results in error",
command: commandLogs(t, els, now),
args: []string{"logs", "eventlistener-no-pods", "-t", "-2"},
wantError: true,
goldenFile: false,
want: "tail cannot be 0 or less than 0 unless -1 for all pods",
},
}

for _, td := range tests {
t.Run(td.name, func(t *testing.T) {
got, err := test.ExecuteCommand(td.command, td.args...)

if err != nil && !td.wantError {
t.Errorf("Unexpected error: %v", err)
}
if td.goldenFile {
golden.Assert(t, got, strings.ReplaceAll(fmt.Sprintf("%s.golden", t.Name()), "/", "-"))
} else {
if err != nil {
test.AssertOutput(t, td.want, err.Error())
} else {
test.AssertOutput(t, td.want, got)
}
}
})
}
}

func commandLogs(t *testing.T, els []*v1alpha1.EventListener, now time.Time) *cobra.Command {
clock := clockwork.NewFakeClockAt(now)
cs := test.SeedTestResources(t, triggertest.Resources{EventListeners: els})
p := &test.Params{Tekton: cs.Pipeline, Clock: clock, Kube: cs.Kube, Triggers: cs.Triggers}
return Command(p)
}
3 changes: 2 additions & 1 deletion pkg/cmd/taskrun/logs.go
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,8 @@ const (

func logCommand(p cli.Params) *cobra.Command {
opts := &options.LogOptions{Params: p}
eg := `Show the logs of TaskRun named 'foo' from the namespace 'bar':
eg := `
Show the logs of TaskRun named 'foo' from the namespace 'bar':

tkn taskrun logs foo -n bar

Expand Down
Loading