-
Notifications
You must be signed in to change notification settings - Fork 166
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
feat(cmd/log): initial implementation of the
kubectl trace logs
com…
…mand Signed-off-by: Lorenzo Fontana <lo@linux.com>
- Loading branch information
Showing
7 changed files
with
276 additions
and
10 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,150 @@ | ||
package cmd | ||
|
||
import ( | ||
"context" | ||
"fmt" | ||
|
||
"github.com/fntlnz/kubectl-trace/pkg/factory" | ||
"github.com/fntlnz/kubectl-trace/pkg/logs" | ||
"github.com/fntlnz/kubectl-trace/pkg/meta" | ||
"github.com/fntlnz/kubectl-trace/pkg/signals" | ||
"github.com/fntlnz/kubectl-trace/pkg/tracejob" | ||
"github.com/spf13/cobra" | ||
"k8s.io/apimachinery/pkg/types" | ||
"k8s.io/cli-runtime/pkg/genericclioptions" | ||
batchv1client "k8s.io/client-go/kubernetes/typed/batch/v1" | ||
corev1client "k8s.io/client-go/kubernetes/typed/core/v1" | ||
"k8s.io/client-go/rest" | ||
) | ||
|
||
var ( | ||
logShort = `` // Wrap with i18n.T() | ||
logLong = logShort + ` | ||
...` | ||
|
||
logExamples = ` | ||
# ... | ||
%[1]s trace log -h | ||
# ... | ||
%[1]s trace log` | ||
) | ||
|
||
// LogOptions ... | ||
type LogOptions struct { | ||
genericclioptions.IOStreams | ||
traceID *types.UID | ||
traceName *string | ||
namespace string | ||
clientConfig *rest.Config | ||
} | ||
|
||
// NewLogOptions provides an instance of LogOptions with default values. | ||
func NewLogOptions(streams genericclioptions.IOStreams) *LogOptions { | ||
return &LogOptions{ | ||
IOStreams: streams, | ||
} | ||
} | ||
|
||
// NewLogCommand provides the log command wrapping LogOptions. | ||
func NewLogCommand(factory factory.Factory, streams genericclioptions.IOStreams) *cobra.Command { | ||
o := NewLogOptions(streams) | ||
|
||
cmd := &cobra.Command{ | ||
Use: "log (TRACE_ID | TRACE_NAME)", | ||
DisableFlagsInUseLine: true, | ||
Short: logShort, | ||
Long: logLong, // Wrap with templates.LongDesc() | ||
Example: fmt.Sprintf(logExamples, "kubectl"), // Wrap with templates.Examples() | ||
PreRunE: func(c *cobra.Command, args []string) error { | ||
return o.Validate(c, args) | ||
}, | ||
RunE: func(c *cobra.Command, args []string) error { | ||
if err := o.Complete(factory, c, args); err != nil { | ||
return err | ||
} | ||
if err := o.Run(); err != nil { | ||
fmt.Fprintln(o.ErrOut, err.Error()) | ||
return nil | ||
} | ||
return nil | ||
}, | ||
} | ||
|
||
return cmd | ||
} | ||
|
||
func (o *LogOptions) Validate(cmd *cobra.Command, args []string) error { | ||
switch len(args) { | ||
case 1: | ||
if meta.IsObjectName(args[0]) { | ||
o.traceName = &args[0] | ||
} else { | ||
tid := types.UID(args[0]) | ||
o.traceID = &tid | ||
} | ||
break | ||
default: | ||
return fmt.Errorf("(TRACE_ID | TRACE_NAME) is a required argument for the log command") | ||
} | ||
|
||
return nil | ||
} | ||
|
||
func (o *LogOptions) Complete(factory factory.Factory, cmd *cobra.Command, args []string) error { | ||
// Prepare namespace | ||
var err error | ||
o.namespace, _, err = factory.ToRawKubeConfigLoader().Namespace() | ||
if err != nil { | ||
return err | ||
} | ||
|
||
// Prepare client | ||
o.clientConfig, err = factory.ToRESTConfig() | ||
if err != nil { | ||
return err | ||
} | ||
|
||
return nil | ||
} | ||
|
||
func (o *LogOptions) Run() error { | ||
jobsClient, err := batchv1client.NewForConfig(o.clientConfig) | ||
if err != nil { | ||
return err | ||
} | ||
|
||
client, err := corev1client.NewForConfig(o.clientConfig) | ||
if err != nil { | ||
return err | ||
} | ||
|
||
tc := &tracejob.TraceJobClient{ | ||
JobClient: jobsClient.Jobs(o.namespace), | ||
} | ||
|
||
tf := tracejob.TraceJobFilter{ | ||
Name: o.traceName, | ||
ID: o.traceID, | ||
} | ||
|
||
jobs, err := tc.GetJob(tf) | ||
|
||
if err != nil { | ||
return err | ||
} | ||
|
||
if len(jobs) == 0 { | ||
return fmt.Errorf("no trace found with the provided criterias") | ||
} | ||
|
||
job := jobs[0] | ||
|
||
ctx := context.Background() | ||
ctx = signals.WithStandardSignals(ctx) | ||
nl := logs.NewLogs(client, o.IOStreams) | ||
nl.WithContext(ctx) | ||
nl.Run(job.ID, job.Namespace) | ||
return nil | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,94 @@ | ||
package logs | ||
|
||
import ( | ||
"github.com/fntlnz/kubectl-trace/pkg/meta" | ||
tcorev1 "k8s.io/client-go/kubernetes/typed/core/v1" | ||
|
||
corev1 "k8s.io/api/core/v1" | ||
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" | ||
"k8s.io/apimachinery/pkg/types" | ||
"k8s.io/client-go/rest" | ||
|
||
"fmt" | ||
"io" | ||
|
||
"context" | ||
|
||
"k8s.io/cli-runtime/pkg/genericclioptions" | ||
) | ||
|
||
type Logs struct { | ||
genericclioptions.IOStreams | ||
coreV1Client tcorev1.CoreV1Interface | ||
ctx context.Context | ||
} | ||
|
||
func NewLogs(client tcorev1.CoreV1Interface, streams genericclioptions.IOStreams) *Logs { | ||
return &Logs{ | ||
coreV1Client: client, | ||
IOStreams: streams, | ||
ctx: context.TODO(), | ||
} | ||
} | ||
|
||
const ( | ||
podNotFoundError = "no trace found to get logs from with the given selector" | ||
podPhaseNotAcceptedError = "cannot get logs from a completed trace; current phase is %s" | ||
invalidPodContainersSizeError = "unexpected number of containers in trace job pod" | ||
) | ||
|
||
func (l *Logs) WithContext(c context.Context) { | ||
l.ctx = c | ||
} | ||
|
||
func (l *Logs) Run(jobID types.UID, namespace string) error { | ||
pl, err := l.coreV1Client.Pods(namespace).List(metav1.ListOptions{ | ||
LabelSelector: fmt.Sprintf("%s=%s", meta.TraceIDLabelKey, jobID), | ||
}) | ||
|
||
if err != nil { | ||
return err | ||
} | ||
|
||
if len(pl.Items) == 0 { | ||
return fmt.Errorf(podNotFoundError) | ||
} | ||
|
||
pod := &pl.Items[0] | ||
if pod.Status.Phase == corev1.PodSucceeded || pod.Status.Phase == corev1.PodFailed { | ||
return fmt.Errorf(podPhaseNotAcceptedError, pod.Status.Phase) | ||
} | ||
|
||
if len(pod.Spec.Containers) != 1 { | ||
return fmt.Errorf(invalidPodContainersSizeError) | ||
} | ||
|
||
containerName := pod.Spec.Containers[0].Name | ||
|
||
// TODO(fntlnz): let the user choose to follow or not | ||
logOptions := &corev1.PodLogOptions{ | ||
Container: containerName, | ||
Follow: true, | ||
Previous: false, | ||
Timestamps: false, | ||
} | ||
|
||
logsRequest := l.coreV1Client.Pods(namespace).GetLogs(pod.Name, logOptions) | ||
|
||
go consumeRequest(logsRequest, l.IOStreams.Out) | ||
<-l.ctx.Done() | ||
|
||
return nil | ||
} | ||
|
||
func consumeRequest(request *rest.Request, out io.Writer) error { | ||
readCloser, err := request.Stream() | ||
if err != nil { | ||
return err | ||
} | ||
defer readCloser.Close() | ||
|
||
_, err = io.Copy(out, readCloser) | ||
return err | ||
} | ||
|
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
Oops, something went wrong.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters