filter.mx raw

   1  // Copyright 2014 The Go Authors. All rights reserved.
   2  // Use of this source code is governed by a BSD-style
   3  // license that can be found in the LICENSE file.
   4  
   5  // Implements methods to filter samples from profiles.
   6  
   7  package profile
   8  
   9  // TagMatch selects tags for filtering
  10  type TagMatch func(key, val []byte, nval int64) bool
  11  
  12  // FilterSamplesByTag removes all samples from the profile, except
  13  // those that match focus and do not match the ignore regular
  14  // expression.
  15  func (p *Profile) FilterSamplesByTag(focus, ignore TagMatch) (fm, im bool) {
  16  	samples := []*Sample{:0:len(p.Sample)}
  17  	for _, s := range p.Sample {
  18  		focused, ignored := focusedSample(s, focus, ignore)
  19  		fm = fm || focused
  20  		im = im || ignored
  21  		if focused && !ignored {
  22  			samples = append(samples, s)
  23  		}
  24  	}
  25  	p.Sample = samples
  26  	return
  27  }
  28  
  29  // focusedSample checks a sample against focus and ignore regexps.
  30  // Returns whether the focus/ignore regexps match any tags.
  31  func focusedSample(s *Sample, focus, ignore TagMatch) (fm, im bool) {
  32  	fm = focus == nil
  33  	for key, vals := range s.Label {
  34  		for _, val := range vals {
  35  			if ignore != nil && ignore(key, val, 0) {
  36  				im = true
  37  			}
  38  			if !fm && focus(key, val, 0) {
  39  				fm = true
  40  			}
  41  		}
  42  	}
  43  	for key, vals := range s.NumLabel {
  44  		for _, val := range vals {
  45  			if ignore != nil && ignore(key, "", val) {
  46  				im = true
  47  			}
  48  			if !fm && focus(key, "", val) {
  49  				fm = true
  50  			}
  51  		}
  52  	}
  53  	return fm, im
  54  }
  55