github.com/containers/libpod@v1.9.4-0.20220419124438-4284fd425507/pkg/bindings/system/system.go (about)

     1  package system
     2  
     3  import (
     4  	"context"
     5  	"encoding/json"
     6  	"io"
     7  	"net/http"
     8  	"net/url"
     9  
    10  	"github.com/containers/libpod/pkg/api/handlers"
    11  	"github.com/containers/libpod/pkg/bindings"
    12  	"github.com/pkg/errors"
    13  	"github.com/sirupsen/logrus"
    14  )
    15  
    16  // Events allows you to monitor libdpod related events like container creation and
    17  // removal.  The events are then passed to the eventChan provided. The optional cancelChan
    18  // can be used to cancel the read of events and close down the HTTP connection.
    19  func Events(ctx context.Context, eventChan chan (handlers.Event), cancelChan chan bool, since, until *string, filters map[string][]string) error {
    20  	conn, err := bindings.GetClient(ctx)
    21  	if err != nil {
    22  		return err
    23  	}
    24  	params := url.Values{}
    25  	if since != nil {
    26  		params.Set("since", *since)
    27  	}
    28  	if until != nil {
    29  		params.Set("until", *until)
    30  	}
    31  	if filters != nil {
    32  		filterString, err := bindings.FiltersToString(filters)
    33  		if err != nil {
    34  			return errors.Wrap(err, "invalid filters")
    35  		}
    36  		params.Set("filters", filterString)
    37  	}
    38  	response, err := conn.DoRequest(nil, http.MethodGet, "/events", params)
    39  	if err != nil {
    40  		return err
    41  	}
    42  	if cancelChan != nil {
    43  		go func() {
    44  			<-cancelChan
    45  			err = response.Body.Close()
    46  			logrus.Error(errors.Wrap(err, "unable to close event response body"))
    47  		}()
    48  	}
    49  	dec := json.NewDecoder(response.Body)
    50  	for {
    51  		e := handlers.Event{}
    52  		if err := dec.Decode(&e); err != nil {
    53  			if err == io.EOF {
    54  				break
    55  			}
    56  			return errors.Wrap(err, "unable to decode event response")
    57  		}
    58  		eventChan <- e
    59  	}
    60  	return nil
    61  }