github.com/containerd/Containerd@v1.4.13/cmd/ctr/commands/events/events.go (about)

     1  /*
     2     Copyright The containerd Authors.
     3  
     4     Licensed under the Apache License, Version 2.0 (the "License");
     5     you may not use this file except in compliance with the License.
     6     You may obtain a copy of the License at
     7  
     8         http://www.apache.org/licenses/LICENSE-2.0
     9  
    10     Unless required by applicable law or agreed to in writing, software
    11     distributed under the License is distributed on an "AS IS" BASIS,
    12     WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    13     See the License for the specific language governing permissions and
    14     limitations under the License.
    15  */
    16  
    17  package events
    18  
    19  import (
    20  	"encoding/json"
    21  	"fmt"
    22  
    23  	"github.com/containerd/containerd/cmd/ctr/commands"
    24  	"github.com/containerd/containerd/events"
    25  	"github.com/containerd/containerd/log"
    26  	"github.com/containerd/typeurl"
    27  	"github.com/urfave/cli"
    28  
    29  	// Register grpc event types
    30  	_ "github.com/containerd/containerd/api/events"
    31  )
    32  
    33  // Command is the cli command for displaying containerd events
    34  var Command = cli.Command{
    35  	Name:    "events",
    36  	Aliases: []string{"event"},
    37  	Usage:   "display containerd events",
    38  	Action: func(context *cli.Context) error {
    39  		client, ctx, cancel, err := commands.NewClient(context)
    40  		if err != nil {
    41  			return err
    42  		}
    43  		defer cancel()
    44  		eventsClient := client.EventService()
    45  		eventsCh, errCh := eventsClient.Subscribe(ctx, context.Args()...)
    46  		for {
    47  			var e *events.Envelope
    48  			select {
    49  			case e = <-eventsCh:
    50  			case err = <-errCh:
    51  				return err
    52  			}
    53  			if e != nil {
    54  				var out []byte
    55  				if e.Event != nil {
    56  					v, err := typeurl.UnmarshalAny(e.Event)
    57  					if err != nil {
    58  						log.G(ctx).WithError(err).Warn("cannot unmarshal an event from Any")
    59  						continue
    60  					}
    61  					out, err = json.Marshal(v)
    62  					if err != nil {
    63  						log.G(ctx).WithError(err).Warn("cannot marshal Any into JSON")
    64  						continue
    65  					}
    66  				}
    67  				if _, err := fmt.Println(
    68  					e.Timestamp,
    69  					e.Namespace,
    70  					e.Topic,
    71  					string(out),
    72  				); err != nil {
    73  					return err
    74  				}
    75  			}
    76  		}
    77  	},
    78  }