github.com/tompao/docker@v1.9.1/daemon/events/filter.go (about)

     1  package events
     2  
     3  import (
     4  	"github.com/docker/docker/pkg/jsonmessage"
     5  	"github.com/docker/docker/pkg/parsers"
     6  	"github.com/docker/docker/pkg/parsers/filters"
     7  )
     8  
     9  // Filter can filter out docker events from a stream
    10  type Filter struct {
    11  	filter    filters.Args
    12  	getLabels func(id string) map[string]string
    13  }
    14  
    15  // NewFilter creates a new Filter
    16  func NewFilter(filter filters.Args, getLabels func(id string) map[string]string) *Filter {
    17  	return &Filter{filter: filter, getLabels: getLabels}
    18  }
    19  
    20  // Include returns true when the event ev is included by the filters
    21  func (ef *Filter) Include(ev *jsonmessage.JSONMessage) bool {
    22  	return isFieldIncluded(ev.Status, ef.filter["event"]) &&
    23  		isFieldIncluded(ev.ID, ef.filter["container"]) &&
    24  		ef.isImageIncluded(ev.ID, ev.From) &&
    25  		ef.isLabelFieldIncluded(ev.ID)
    26  }
    27  
    28  func (ef *Filter) isLabelFieldIncluded(id string) bool {
    29  	if _, ok := ef.filter["label"]; !ok {
    30  		return true
    31  	}
    32  	return ef.filter.MatchKVList("label", ef.getLabels(id))
    33  }
    34  
    35  // The image filter will be matched against both event.ID (for image events)
    36  // and event.From (for container events), so that any container that was created
    37  // from an image will be included in the image events. Also compare both
    38  // against the stripped repo name without any tags.
    39  func (ef *Filter) isImageIncluded(eventID string, eventFrom string) bool {
    40  	stripTag := func(image string) string {
    41  		repo, _ := parsers.ParseRepositoryTag(image)
    42  		return repo
    43  	}
    44  
    45  	return isFieldIncluded(eventID, ef.filter["image"]) ||
    46  		isFieldIncluded(eventFrom, ef.filter["image"]) ||
    47  		isFieldIncluded(stripTag(eventID), ef.filter["image"]) ||
    48  		isFieldIncluded(stripTag(eventFrom), ef.filter["image"])
    49  }
    50  
    51  func isFieldIncluded(field string, filter []string) bool {
    52  	if len(field) == 0 {
    53  		return true
    54  	}
    55  	if len(filter) == 0 {
    56  		return true
    57  	}
    58  	for _, v := range filter {
    59  		if v == field {
    60  			return true
    61  		}
    62  	}
    63  	return false
    64  }