|
1 | 1 | package client |
2 | 2 |
|
3 | 3 | import ( |
| 4 | + "encoding/json" |
| 5 | + "fmt" |
| 6 | + "io" |
| 7 | + "strings" |
| 8 | + "time" |
| 9 | + |
4 | 10 | "github.com/docker/docker/api/types" |
| 11 | + eventtypes "github.com/docker/docker/api/types/events" |
5 | 12 | "github.com/docker/docker/api/types/filters" |
6 | 13 | Cli "github.com/docker/docker/cli" |
7 | 14 | "github.com/docker/docker/opts" |
8 | | - "github.com/docker/docker/pkg/jsonmessage" |
| 15 | + "github.com/docker/docker/pkg/jsonlog" |
9 | 16 | flag "github.com/docker/docker/pkg/mflag" |
10 | 17 | ) |
11 | 18 |
|
@@ -46,5 +53,56 @@ func (cli *DockerCli) CmdEvents(args ...string) error { |
46 | 53 | } |
47 | 54 | defer responseBody.Close() |
48 | 55 |
|
49 | | - return jsonmessage.DisplayJSONMessagesStream(responseBody, cli.out, cli.outFd, cli.isTerminalOut) |
| 56 | + return streamEvents(responseBody, cli.out) |
| 57 | +} |
| 58 | + |
| 59 | +// streamEvents decodes prints the incoming events in the provided output. |
| 60 | +func streamEvents(input io.Reader, output io.Writer) error { |
| 61 | + return decodeEvents(input, func(event eventtypes.Message, err error) error { |
| 62 | + if err != nil { |
| 63 | + return err |
| 64 | + } |
| 65 | + printOutput(event, output) |
| 66 | + return nil |
| 67 | + }) |
| 68 | +} |
| 69 | + |
| 70 | +type eventProcessor func(event eventtypes.Message, err error) error |
| 71 | + |
| 72 | +func decodeEvents(input io.Reader, ep eventProcessor) error { |
| 73 | + dec := json.NewDecoder(input) |
| 74 | + for { |
| 75 | + var event eventtypes.Message |
| 76 | + err := dec.Decode(&event) |
| 77 | + if err != nil && err == io.EOF { |
| 78 | + break |
| 79 | + } |
| 80 | + |
| 81 | + if procErr := ep(event, err); procErr != nil { |
| 82 | + return procErr |
| 83 | + } |
| 84 | + } |
| 85 | + return nil |
| 86 | +} |
| 87 | + |
| 88 | +// printOutput prints all types of event information. |
| 89 | +// Each output includes the event type, actor id, name and action. |
| 90 | +// Actor attributes are printed at the end if the actor has any. |
| 91 | +func printOutput(event eventtypes.Message, output io.Writer) { |
| 92 | + if event.TimeNano != 0 { |
| 93 | + fmt.Fprintf(output, "%s ", time.Unix(0, event.TimeNano).Format(jsonlog.RFC3339NanoFixed)) |
| 94 | + } else if event.Time != 0 { |
| 95 | + fmt.Fprintf(output, "%s ", time.Unix(event.Time, 0).Format(jsonlog.RFC3339NanoFixed)) |
| 96 | + } |
| 97 | + |
| 98 | + fmt.Fprintf(output, "%s %s %s", event.Type, event.Action, event.Actor.ID) |
| 99 | + |
| 100 | + if len(event.Actor.Attributes) > 0 { |
| 101 | + var attrs []string |
| 102 | + for k, v := range event.Actor.Attributes { |
| 103 | + attrs = append(attrs, fmt.Sprintf("%s=%s", k, v)) |
| 104 | + } |
| 105 | + fmt.Fprintf(output, " (%s)", strings.Join(attrs, ", ")) |
| 106 | + } |
| 107 | + fmt.Fprint(output, "\n") |
50 | 108 | } |
0 commit comments