Skip to content

Commit

Permalink
nerdctl events --format
Browse files Browse the repository at this point in the history
Signed-off-by: ning.mingxiao <ning.mingxiao@zte.com.cn>
  • Loading branch information
ningmingxiao committed Aug 27, 2021
1 parent cee3b6a commit 12a7989
Showing 1 changed file with 46 additions and 8 deletions.
54 changes: 46 additions & 8 deletions cmd/nerdctl/events.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,9 @@ package main
import (
"encoding/json"
"fmt"
"github.com/docker/cli/templates"
"text/template"
"time"

"github.com/containerd/containerd/events"
"github.com/containerd/containerd/log"
Expand All @@ -35,6 +38,19 @@ var eventsCommand = &cli.Command{
Usage: "Get real time events from the server",
Description: "NOTE: The output format is not compatible with Docker.",
Action: eventsAction,
Flags: []cli.Flag{
&cli.StringFlag{
Name: "format",
Usage: "Format the output using the given Go template, e.g, '{{json .}}'",
},
},
}

type Event struct {
Timestamp time.Time
Namespace string
Topic string
Out string
}

// eventsActions is from https://github.com/containerd/containerd/blob/v1.4.3/cmd/ctr/commands/events/events.go
Expand All @@ -50,6 +66,17 @@ func eventsAction(clicontext *cli.Context) error {
defer cancel()
eventsClient := client.EventService()
eventsCh, errCh := eventsClient.Subscribe(ctx)

var tmpl *template.Template
switch format := clicontext.String("format"); format {
case "raw", "table":
return errors.New("unsupported format: \"raw\" and \"table\"")
default:
tmpl, err = templates.Parse(format)
if err != nil {
return err
}
}
for {
var e *events.Envelope
select {
Expand All @@ -71,14 +98,25 @@ func eventsAction(clicontext *cli.Context) error {
continue
}
}
if _, err := fmt.Fprintln(
clicontext.App.Writer,
e.Timestamp,
e.Namespace,
e.Topic,
string(out),
); err != nil {
return err
if tmpl != nil {
event := Event{e.Timestamp, e.Namespace, e.Topic, string(out)}
jsonEvent, err := json.Marshal(event)
if err != nil {
return err
}
if _, err := fmt.Fprintln(clicontext.App.Writer, string(jsonEvent)); err != nil {
return err
}
} else {
if _, err := fmt.Fprintln(
clicontext.App.Writer,
e.Timestamp,
e.Namespace,
e.Topic,
string(out),
); err != nil {
return err
}
}
}
}
Expand Down

0 comments on commit 12a7989

Please sign in to comment.