code
stringlengths 12
335k
| docstring
stringlengths 20
20.8k
| func_name
stringlengths 1
105
| language
stringclasses 1
value | repo
stringclasses 498
values | path
stringlengths 5
172
| url
stringlengths 43
235
| license
stringclasses 4
values |
---|---|---|---|---|---|---|---|
func newKqueue() (kq int, closepipe [2]int, err error) {
kq, err = unix.Kqueue()
if kq == -1 {
return kq, closepipe, err
}
// Register the close pipe.
err = unix.Pipe(closepipe[:])
if err != nil {
unix.Close(kq)
return kq, closepipe, err
}
// Register changes to listen on the closepipe.
changes := make([]unix.Kevent_t, 1)
// SetKevent converts int to the platform-specific types.
unix.SetKevent(&changes[0], closepipe[0], unix.EVFILT_READ,
unix.EV_ADD|unix.EV_ENABLE|unix.EV_ONESHOT)
ok, err := unix.Kevent(kq, changes, nil, nil)
if ok == -1 {
unix.Close(kq)
unix.Close(closepipe[0])
unix.Close(closepipe[1])
return kq, closepipe, err
}
return kq, closepipe, nil
} | newKqueue creates a new kernel event queue and returns a descriptor.
This registers a new event on closepipe, which will trigger an event when
it's closed. This way we can use kevent() without timeout/polling; without
the closepipe, it would block forever and we wouldn't be able to stop it at
all. | newKqueue | go | k8snetworkplumbingwg/multus-cni | vendor/github.com/fsnotify/fsnotify/backend_kqueue.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/github.com/fsnotify/fsnotify/backend_kqueue.go | Apache-2.0 |
func (w *Watcher) sendEvent(e Event) bool {
select {
case w.Events <- e:
return true
case <-w.done:
}
return false
} | Returns true if the event was sent, or false if watcher is closed. | sendEvent | go | k8snetworkplumbingwg/multus-cni | vendor/github.com/fsnotify/fsnotify/backend_kqueue.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/github.com/fsnotify/fsnotify/backend_kqueue.go | Apache-2.0 |
func (w *Watcher) sendError(err error) bool {
select {
case w.Errors <- err:
return true
case <-w.done:
}
return false
} | Returns true if the error was sent, or false if watcher is closed. | sendError | go | k8snetworkplumbingwg/multus-cni | vendor/github.com/fsnotify/fsnotify/backend_kqueue.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/github.com/fsnotify/fsnotify/backend_kqueue.go | Apache-2.0 |
func (w *Watcher) Close() error {
w.mu.Lock()
if w.isClosed {
w.mu.Unlock()
return nil
}
w.isClosed = true
// copy paths to remove while locked
pathsToRemove := make([]string, 0, len(w.watches))
for name := range w.watches {
pathsToRemove = append(pathsToRemove, name)
}
w.mu.Unlock() // Unlock before calling Remove, which also locks
for _, name := range pathsToRemove {
w.Remove(name)
}
// Send "quit" message to the reader goroutine.
unix.Close(w.closepipe[1])
close(w.done)
return nil
} | Close removes all watches and closes the events channel. | Close | go | k8snetworkplumbingwg/multus-cni | vendor/github.com/fsnotify/fsnotify/backend_kqueue.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/github.com/fsnotify/fsnotify/backend_kqueue.go | Apache-2.0 |
func (w *Watcher) Add(name string) error {
w.mu.Lock()
w.userWatches[name] = struct{}{}
w.mu.Unlock()
_, err := w.addWatch(name, noteAllEvents)
return err
} | Add starts monitoring the path for changes.
A path can only be watched once; attempting to watch it more than once will
return an error. Paths that do not yet exist on the filesystem cannot be
added. A watch will be automatically removed if the path is deleted.
A path will remain watched if it gets renamed to somewhere else on the same
filesystem, but the monitor will get removed if the path gets deleted and
re-created, or if it's moved to a different filesystem.
Notifications on network filesystems (NFS, SMB, FUSE, etc.) or special
filesystems (/proc, /sys, etc.) generally don't work.
# Watching directories
All files in a directory are monitored, including new files that are created
after the watcher is started. Subdirectories are not watched (i.e. it's
non-recursive).
# Watching files
Watching individual files (rather than directories) is generally not
recommended as many tools update files atomically. Instead of "just" writing
to the file a temporary file will be written to first, and if successful the
temporary file is moved to to destination removing the original, or some
variant thereof. The watcher on the original file is now lost, as it no
longer exists.
Instead, watch the parent directory and use Event.Name to filter out files
you're not interested in. There is an example of this in [cmd/fsnotify/file.go]. | Add | go | k8snetworkplumbingwg/multus-cni | vendor/github.com/fsnotify/fsnotify/backend_kqueue.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/github.com/fsnotify/fsnotify/backend_kqueue.go | Apache-2.0 |
func (w *Watcher) Remove(name string) error {
name = filepath.Clean(name)
w.mu.Lock()
watchfd, ok := w.watches[name]
w.mu.Unlock()
if !ok {
return fmt.Errorf("%w: %s", ErrNonExistentWatch, name)
}
err := w.register([]int{watchfd}, unix.EV_DELETE, 0)
if err != nil {
return err
}
unix.Close(watchfd)
w.mu.Lock()
isDir := w.paths[watchfd].isDir
delete(w.watches, name)
delete(w.userWatches, name)
parentName := filepath.Dir(name)
delete(w.watchesByDir[parentName], watchfd)
if len(w.watchesByDir[parentName]) == 0 {
delete(w.watchesByDir, parentName)
}
delete(w.paths, watchfd)
delete(w.dirFlags, name)
delete(w.fileExists, name)
w.mu.Unlock()
// Find all watched paths that are in this directory that are not external.
if isDir {
var pathsToRemove []string
w.mu.Lock()
for fd := range w.watchesByDir[name] {
path := w.paths[fd]
if _, ok := w.userWatches[path.name]; !ok {
pathsToRemove = append(pathsToRemove, path.name)
}
}
w.mu.Unlock()
for _, name := range pathsToRemove {
// Since these are internal, not much sense in propagating error
// to the user, as that will just confuse them with an error about
// a path they did not explicitly watch themselves.
w.Remove(name)
}
}
return nil
} | Remove stops monitoring the path for changes.
Directories are always removed non-recursively. For example, if you added
/tmp/dir and /tmp/dir/subdir then you will need to remove both.
Removing a path that has not yet been added returns [ErrNonExistentWatch]. | Remove | go | k8snetworkplumbingwg/multus-cni | vendor/github.com/fsnotify/fsnotify/backend_kqueue.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/github.com/fsnotify/fsnotify/backend_kqueue.go | Apache-2.0 |
func (w *Watcher) WatchList() []string {
w.mu.Lock()
defer w.mu.Unlock()
entries := make([]string, 0, len(w.userWatches))
for pathname := range w.userWatches {
entries = append(entries, pathname)
}
return entries
} | WatchList returns all paths added with [Add] (and are not yet removed). | WatchList | go | k8snetworkplumbingwg/multus-cni | vendor/github.com/fsnotify/fsnotify/backend_kqueue.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/github.com/fsnotify/fsnotify/backend_kqueue.go | Apache-2.0 |
func (w *Watcher) addWatch(name string, flags uint32) (string, error) {
var isDir bool
// Make ./name and name equivalent
name = filepath.Clean(name)
w.mu.Lock()
if w.isClosed {
w.mu.Unlock()
return "", errors.New("kevent instance already closed")
}
watchfd, alreadyWatching := w.watches[name]
// We already have a watch, but we can still override flags.
if alreadyWatching {
isDir = w.paths[watchfd].isDir
}
w.mu.Unlock()
if !alreadyWatching {
fi, err := os.Lstat(name)
if err != nil {
return "", err
}
// Don't watch sockets or named pipes
if (fi.Mode()&os.ModeSocket == os.ModeSocket) || (fi.Mode()&os.ModeNamedPipe == os.ModeNamedPipe) {
return "", nil
}
// Follow Symlinks
//
// Linux can add unresolvable symlinks to the watch list without issue,
// and Windows can't do symlinks period. To maintain consistency, we
// will act like everything is fine if the link can't be resolved.
// There will simply be no file events for broken symlinks. Hence the
// returns of nil on errors.
if fi.Mode()&os.ModeSymlink == os.ModeSymlink {
name, err = filepath.EvalSymlinks(name)
if err != nil {
return "", nil
}
w.mu.Lock()
_, alreadyWatching = w.watches[name]
w.mu.Unlock()
if alreadyWatching {
return name, nil
}
fi, err = os.Lstat(name)
if err != nil {
return "", nil
}
}
// Retry on EINTR; open() can return EINTR in practice on macOS.
// See #354, and go issues 11180 and 39237.
for {
watchfd, err = unix.Open(name, openMode, 0)
if err == nil {
break
}
if errors.Is(err, unix.EINTR) {
continue
}
return "", err
}
isDir = fi.IsDir()
}
err := w.register([]int{watchfd}, unix.EV_ADD|unix.EV_CLEAR|unix.EV_ENABLE, flags)
if err != nil {
unix.Close(watchfd)
return "", err
}
if !alreadyWatching {
w.mu.Lock()
parentName := filepath.Dir(name)
w.watches[name] = watchfd
watchesByDir, ok := w.watchesByDir[parentName]
if !ok {
watchesByDir = make(map[int]struct{}, 1)
w.watchesByDir[parentName] = watchesByDir
}
watchesByDir[watchfd] = struct{}{}
w.paths[watchfd] = pathInfo{name: name, isDir: isDir}
w.mu.Unlock()
}
if isDir {
// Watch the directory if it has not been watched before,
// or if it was watched before, but perhaps only a NOTE_DELETE (watchDirectoryFiles)
w.mu.Lock()
watchDir := (flags&unix.NOTE_WRITE) == unix.NOTE_WRITE &&
(!alreadyWatching || (w.dirFlags[name]&unix.NOTE_WRITE) != unix.NOTE_WRITE)
// Store flags so this watch can be updated later
w.dirFlags[name] = flags
w.mu.Unlock()
if watchDir {
if err := w.watchDirectoryFiles(name); err != nil {
return "", err
}
}
}
return name, nil
} | addWatch adds name to the watched file set.
The flags are interpreted as described in kevent(2).
Returns the real path to the file which was added, if any, which may be different from the one passed in the case of symlinks. | addWatch | go | k8snetworkplumbingwg/multus-cni | vendor/github.com/fsnotify/fsnotify/backend_kqueue.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/github.com/fsnotify/fsnotify/backend_kqueue.go | Apache-2.0 |
func (w *Watcher) readEvents() {
defer func() {
err := unix.Close(w.kq)
if err != nil {
w.Errors <- err
}
unix.Close(w.closepipe[0])
close(w.Events)
close(w.Errors)
}()
eventBuffer := make([]unix.Kevent_t, 10)
for closed := false; !closed; {
kevents, err := w.read(eventBuffer)
// EINTR is okay, the syscall was interrupted before timeout expired.
if err != nil && err != unix.EINTR {
if !w.sendError(fmt.Errorf("fsnotify.readEvents: %w", err)) {
closed = true
}
continue
}
// Flush the events we received to the Events channel
for _, kevent := range kevents {
var (
watchfd = int(kevent.Ident)
mask = uint32(kevent.Fflags)
)
// Shut down the loop when the pipe is closed, but only after all
// other events have been processed.
if watchfd == w.closepipe[0] {
closed = true
continue
}
w.mu.Lock()
path := w.paths[watchfd]
w.mu.Unlock()
event := w.newEvent(path.name, mask)
if path.isDir && !event.Has(Remove) {
// Double check to make sure the directory exists. This can
// happen when we do a rm -fr on a recursively watched folders
// and we receive a modification event first but the folder has
// been deleted and later receive the delete event.
if _, err := os.Lstat(event.Name); os.IsNotExist(err) {
event.Op |= Remove
}
}
if event.Has(Rename) || event.Has(Remove) {
w.Remove(event.Name)
w.mu.Lock()
delete(w.fileExists, event.Name)
w.mu.Unlock()
}
if path.isDir && event.Has(Write) && !event.Has(Remove) {
w.sendDirectoryChangeEvents(event.Name)
} else {
if !w.sendEvent(event) {
closed = true
continue
}
}
if event.Has(Remove) {
// Look for a file that may have overwritten this.
// For example, mv f1 f2 will delete f2, then create f2.
if path.isDir {
fileDir := filepath.Clean(event.Name)
w.mu.Lock()
_, found := w.watches[fileDir]
w.mu.Unlock()
if found {
// make sure the directory exists before we watch for changes. When we
// do a recursive watch and perform rm -fr, the parent directory might
// have gone missing, ignore the missing directory and let the
// upcoming delete event remove the watch from the parent directory.
if _, err := os.Lstat(fileDir); err == nil {
w.sendDirectoryChangeEvents(fileDir)
}
}
} else {
filePath := filepath.Clean(event.Name)
if fileInfo, err := os.Lstat(filePath); err == nil {
w.sendFileCreatedEventIfNew(filePath, fileInfo)
}
}
}
}
}
} | readEvents reads from kqueue and converts the received kevents into
Event values that it sends down the Events channel. | readEvents | go | k8snetworkplumbingwg/multus-cni | vendor/github.com/fsnotify/fsnotify/backend_kqueue.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/github.com/fsnotify/fsnotify/backend_kqueue.go | Apache-2.0 |
func (w *Watcher) newEvent(name string, mask uint32) Event {
e := Event{Name: name}
if mask&unix.NOTE_DELETE == unix.NOTE_DELETE {
e.Op |= Remove
}
if mask&unix.NOTE_WRITE == unix.NOTE_WRITE {
e.Op |= Write
}
if mask&unix.NOTE_RENAME == unix.NOTE_RENAME {
e.Op |= Rename
}
if mask&unix.NOTE_ATTRIB == unix.NOTE_ATTRIB {
e.Op |= Chmod
}
return e
} | newEvent returns an platform-independent Event based on kqueue Fflags. | newEvent | go | k8snetworkplumbingwg/multus-cni | vendor/github.com/fsnotify/fsnotify/backend_kqueue.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/github.com/fsnotify/fsnotify/backend_kqueue.go | Apache-2.0 |
func (w *Watcher) watchDirectoryFiles(dirPath string) error {
// Get all files
files, err := ioutil.ReadDir(dirPath)
if err != nil {
return err
}
for _, fileInfo := range files {
path := filepath.Join(dirPath, fileInfo.Name())
cleanPath, err := w.internalWatch(path, fileInfo)
if err != nil {
// No permission to read the file; that's not a problem: just skip.
// But do add it to w.fileExists to prevent it from being picked up
// as a "new" file later (it still shows up in the directory
// listing).
switch {
case errors.Is(err, unix.EACCES) || errors.Is(err, unix.EPERM):
cleanPath = filepath.Clean(path)
default:
return fmt.Errorf("%q: %w", filepath.Join(dirPath, fileInfo.Name()), err)
}
}
w.mu.Lock()
w.fileExists[cleanPath] = struct{}{}
w.mu.Unlock()
}
return nil
} | watchDirectoryFiles to mimic inotify when adding a watch on a directory | watchDirectoryFiles | go | k8snetworkplumbingwg/multus-cni | vendor/github.com/fsnotify/fsnotify/backend_kqueue.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/github.com/fsnotify/fsnotify/backend_kqueue.go | Apache-2.0 |
func (w *Watcher) sendDirectoryChangeEvents(dir string) {
// Get all files
files, err := ioutil.ReadDir(dir)
if err != nil {
if !w.sendError(fmt.Errorf("fsnotify.sendDirectoryChangeEvents: %w", err)) {
return
}
}
// Search for new files
for _, fi := range files {
err := w.sendFileCreatedEventIfNew(filepath.Join(dir, fi.Name()), fi)
if err != nil {
return
}
}
} | Search the directory for new files and send an event for them.
This functionality is to have the BSD watcher match the inotify, which sends
a create event for files created in a watched directory. | sendDirectoryChangeEvents | go | k8snetworkplumbingwg/multus-cni | vendor/github.com/fsnotify/fsnotify/backend_kqueue.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/github.com/fsnotify/fsnotify/backend_kqueue.go | Apache-2.0 |
func (w *Watcher) sendFileCreatedEventIfNew(filePath string, fileInfo os.FileInfo) (err error) {
w.mu.Lock()
_, doesExist := w.fileExists[filePath]
w.mu.Unlock()
if !doesExist {
if !w.sendEvent(Event{Name: filePath, Op: Create}) {
return
}
}
// like watchDirectoryFiles (but without doing another ReadDir)
filePath, err = w.internalWatch(filePath, fileInfo)
if err != nil {
return err
}
w.mu.Lock()
w.fileExists[filePath] = struct{}{}
w.mu.Unlock()
return nil
} | sendFileCreatedEvent sends a create event if the file isn't already being tracked. | sendFileCreatedEventIfNew | go | k8snetworkplumbingwg/multus-cni | vendor/github.com/fsnotify/fsnotify/backend_kqueue.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/github.com/fsnotify/fsnotify/backend_kqueue.go | Apache-2.0 |
func (w *Watcher) register(fds []int, flags int, fflags uint32) error {
changes := make([]unix.Kevent_t, len(fds))
for i, fd := range fds {
// SetKevent converts int to the platform-specific types.
unix.SetKevent(&changes[i], fd, unix.EVFILT_VNODE, flags)
changes[i].Fflags = fflags
}
// Register the events.
success, err := unix.Kevent(w.kq, changes, nil, nil)
if success == -1 {
return err
}
return nil
} | Register events with the queue. | register | go | k8snetworkplumbingwg/multus-cni | vendor/github.com/fsnotify/fsnotify/backend_kqueue.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/github.com/fsnotify/fsnotify/backend_kqueue.go | Apache-2.0 |
func (w *Watcher) read(events []unix.Kevent_t) ([]unix.Kevent_t, error) {
n, err := unix.Kevent(w.kq, nil, events, nil)
if err != nil {
return nil, err
}
return events[0:n], nil
} | read retrieves pending events, or waits until an event occurs. | read | go | k8snetworkplumbingwg/multus-cni | vendor/github.com/fsnotify/fsnotify/backend_kqueue.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/github.com/fsnotify/fsnotify/backend_kqueue.go | Apache-2.0 |
func (o Op) Has(h Op) bool { return o&h == h } | Has reports if this operation has the given operation. | Has | go | k8snetworkplumbingwg/multus-cni | vendor/github.com/fsnotify/fsnotify/fsnotify.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/github.com/fsnotify/fsnotify/fsnotify.go | Apache-2.0 |
func (e Event) Has(op Op) bool { return e.Op.Has(op) } | Has reports if this event has the given operation. | Has | go | k8snetworkplumbingwg/multus-cni | vendor/github.com/fsnotify/fsnotify/fsnotify.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/github.com/fsnotify/fsnotify/fsnotify.go | Apache-2.0 |
func (e Event) String() string {
return fmt.Sprintf("%-13s %q", e.Op.String(), e.Name)
} | String returns a string representation of the event with their path. | String | go | k8snetworkplumbingwg/multus-cni | vendor/github.com/fsnotify/fsnotify/fsnotify.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/github.com/fsnotify/fsnotify/fsnotify.go | Apache-2.0 |
func NewWatcher() (*Watcher, error) {
return nil, errors.New("FEN based watcher not yet supported for fsnotify\n")
} | NewWatcher creates a new Watcher. | NewWatcher | go | k8snetworkplumbingwg/multus-cni | vendor/github.com/fsnotify/fsnotify/backend_fen.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/github.com/fsnotify/fsnotify/backend_fen.go | Apache-2.0 |
func (w *Watcher) Close() error {
return nil
} | Close removes all watches and closes the events channel. | Close | go | k8snetworkplumbingwg/multus-cni | vendor/github.com/fsnotify/fsnotify/backend_fen.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/github.com/fsnotify/fsnotify/backend_fen.go | Apache-2.0 |
func (w *Watcher) Add(name string) error {
return nil
} | Add starts monitoring the path for changes.
A path can only be watched once; attempting to watch it more than once will
return an error. Paths that do not yet exist on the filesystem cannot be
added. A watch will be automatically removed if the path is deleted.
A path will remain watched if it gets renamed to somewhere else on the same
filesystem, but the monitor will get removed if the path gets deleted and
re-created, or if it's moved to a different filesystem.
Notifications on network filesystems (NFS, SMB, FUSE, etc.) or special
filesystems (/proc, /sys, etc.) generally don't work.
# Watching directories
All files in a directory are monitored, including new files that are created
after the watcher is started. Subdirectories are not watched (i.e. it's
non-recursive).
# Watching files
Watching individual files (rather than directories) is generally not
recommended as many tools update files atomically. Instead of "just" writing
to the file a temporary file will be written to first, and if successful the
temporary file is moved to to destination removing the original, or some
variant thereof. The watcher on the original file is now lost, as it no
longer exists.
Instead, watch the parent directory and use Event.Name to filter out files
you're not interested in. There is an example of this in [cmd/fsnotify/file.go]. | Add | go | k8snetworkplumbingwg/multus-cni | vendor/github.com/fsnotify/fsnotify/backend_fen.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/github.com/fsnotify/fsnotify/backend_fen.go | Apache-2.0 |
func (w *Watcher) Remove(name string) error {
return nil
} | Remove stops monitoring the path for changes.
Directories are always removed non-recursively. For example, if you added
/tmp/dir and /tmp/dir/subdir then you will need to remove both.
Removing a path that has not yet been added returns [ErrNonExistentWatch]. | Remove | go | k8snetworkplumbingwg/multus-cni | vendor/github.com/fsnotify/fsnotify/backend_fen.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/github.com/fsnotify/fsnotify/backend_fen.go | Apache-2.0 |
func NewWatcher() (*Watcher, error) {
return nil, fmt.Errorf("fsnotify not supported on %s", runtime.GOOS)
} | NewWatcher creates a new Watcher. | NewWatcher | go | k8snetworkplumbingwg/multus-cni | vendor/github.com/fsnotify/fsnotify/backend_other.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/github.com/fsnotify/fsnotify/backend_other.go | Apache-2.0 |
func (w *Watcher) Close() error {
return nil
} | Close removes all watches and closes the events channel. | Close | go | k8snetworkplumbingwg/multus-cni | vendor/github.com/fsnotify/fsnotify/backend_other.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/github.com/fsnotify/fsnotify/backend_other.go | Apache-2.0 |
func (w *Watcher) Add(name string) error {
return nil
} | Add starts monitoring the path for changes.
A path can only be watched once; attempting to watch it more than once will
return an error. Paths that do not yet exist on the filesystem cannot be
added. A watch will be automatically removed if the path is deleted.
A path will remain watched if it gets renamed to somewhere else on the same
filesystem, but the monitor will get removed if the path gets deleted and
re-created, or if it's moved to a different filesystem.
Notifications on network filesystems (NFS, SMB, FUSE, etc.) or special
filesystems (/proc, /sys, etc.) generally don't work.
# Watching directories
All files in a directory are monitored, including new files that are created
after the watcher is started. Subdirectories are not watched (i.e. it's
non-recursive).
# Watching files
Watching individual files (rather than directories) is generally not
recommended as many tools update files atomically. Instead of "just" writing
to the file a temporary file will be written to first, and if successful the
temporary file is moved to to destination removing the original, or some
variant thereof. The watcher on the original file is now lost, as it no
longer exists.
Instead, watch the parent directory and use Event.Name to filter out files
you're not interested in. There is an example of this in [cmd/fsnotify/file.go]. | Add | go | k8snetworkplumbingwg/multus-cni | vendor/github.com/fsnotify/fsnotify/backend_other.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/github.com/fsnotify/fsnotify/backend_other.go | Apache-2.0 |
func (w *Watcher) Remove(name string) error {
return nil
} | Remove stops monitoring the path for changes.
Directories are always removed non-recursively. For example, if you added
/tmp/dir and /tmp/dir/subdir then you will need to remove both.
Removing a path that has not yet been added returns [ErrNonExistentWatch]. | Remove | go | k8snetworkplumbingwg/multus-cni | vendor/github.com/fsnotify/fsnotify/backend_other.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/github.com/fsnotify/fsnotify/backend_other.go | Apache-2.0 |
func String(s string) string {
m := pool.Get().(map[string]string)
c, ok := m[s]
if ok {
pool.Put(m)
return c
}
m[s] = s
pool.Put(m)
return s
} | String returns s, interned. | String | go | k8snetworkplumbingwg/multus-cni | vendor/github.com/josharian/intern/intern.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/github.com/josharian/intern/intern.go | Apache-2.0 |
func Bytes(b []byte) string {
m := pool.Get().(map[string]string)
c, ok := m[string(b)]
if ok {
pool.Put(m)
return c
}
s := string(b)
m[s] = s
pool.Put(m)
return s
} | Bytes returns b converted to a string, interned. | Bytes | go | k8snetworkplumbingwg/multus-cni | vendor/github.com/josharian/intern/intern.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/github.com/josharian/intern/intern.go | Apache-2.0 |
func Parse(r io.Reader) (*Profile, error) {
data, err := io.ReadAll(r)
if err != nil {
return nil, err
}
return ParseData(data)
} | Parse parses a profile and checks for its validity. The input
may be a gzip-compressed encoded protobuf or one of many legacy
profile formats which may be unsupported in the future. | Parse | go | k8snetworkplumbingwg/multus-cni | vendor/github.com/google/pprof/profile/profile.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/github.com/google/pprof/profile/profile.go | Apache-2.0 |
func ParseData(data []byte) (*Profile, error) {
var p *Profile
var err error
if len(data) >= 2 && data[0] == 0x1f && data[1] == 0x8b {
gz, err := gzip.NewReader(bytes.NewBuffer(data))
if err == nil {
data, err = io.ReadAll(gz)
}
if err != nil {
return nil, fmt.Errorf("decompressing profile: %v", err)
}
}
if p, err = ParseUncompressed(data); err != nil && err != errNoData && err != errConcatProfile {
p, err = parseLegacy(data)
}
if err != nil {
return nil, fmt.Errorf("parsing profile: %v", err)
}
if err := p.CheckValid(); err != nil {
return nil, fmt.Errorf("malformed profile: %v", err)
}
return p, nil
} | ParseData parses a profile from a buffer and checks for its
validity. | ParseData | go | k8snetworkplumbingwg/multus-cni | vendor/github.com/google/pprof/profile/profile.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/github.com/google/pprof/profile/profile.go | Apache-2.0 |
func ParseUncompressed(data []byte) (*Profile, error) {
if len(data) == 0 {
return nil, errNoData
}
p := &Profile{}
if err := unmarshal(data, p); err != nil {
return nil, err
}
if err := p.postDecode(); err != nil {
return nil, err
}
return p, nil
} | ParseUncompressed parses an uncompressed protobuf into a profile. | ParseUncompressed | go | k8snetworkplumbingwg/multus-cni | vendor/github.com/google/pprof/profile/profile.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/github.com/google/pprof/profile/profile.go | Apache-2.0 |
func (p *Profile) massageMappings() {
// Merge adjacent regions with matching names, checking that the offsets match
if len(p.Mapping) > 1 {
mappings := []*Mapping{p.Mapping[0]}
for _, m := range p.Mapping[1:] {
lm := mappings[len(mappings)-1]
if adjacent(lm, m) {
lm.Limit = m.Limit
if m.File != "" {
lm.File = m.File
}
if m.BuildID != "" {
lm.BuildID = m.BuildID
}
p.updateLocationMapping(m, lm)
continue
}
mappings = append(mappings, m)
}
p.Mapping = mappings
}
// Use heuristics to identify main binary and move it to the top of the list of mappings
for i, m := range p.Mapping {
file := strings.TrimSpace(strings.Replace(m.File, "(deleted)", "", -1))
if len(file) == 0 {
continue
}
if len(libRx.FindStringSubmatch(file)) > 0 {
continue
}
if file[0] == '[' {
continue
}
// Swap what we guess is main to position 0.
p.Mapping[0], p.Mapping[i] = p.Mapping[i], p.Mapping[0]
break
}
// Keep the mapping IDs neatly sorted
for i, m := range p.Mapping {
m.ID = uint64(i + 1)
}
} | massageMappings applies heuristic-based changes to the profile
mappings to account for quirks of some environments. | massageMappings | go | k8snetworkplumbingwg/multus-cni | vendor/github.com/google/pprof/profile/profile.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/github.com/google/pprof/profile/profile.go | Apache-2.0 |
func adjacent(m1, m2 *Mapping) bool {
if m1.File != "" && m2.File != "" {
if m1.File != m2.File {
return false
}
}
if m1.BuildID != "" && m2.BuildID != "" {
if m1.BuildID != m2.BuildID {
return false
}
}
if m1.Limit != m2.Start {
return false
}
if m1.Offset != 0 && m2.Offset != 0 {
offset := m1.Offset + (m1.Limit - m1.Start)
if offset != m2.Offset {
return false
}
}
return true
} | adjacent returns whether two mapping entries represent the same
mapping that has been split into two. Check that their addresses are adjacent,
and if the offsets match, if they are available. | adjacent | go | k8snetworkplumbingwg/multus-cni | vendor/github.com/google/pprof/profile/profile.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/github.com/google/pprof/profile/profile.go | Apache-2.0 |
func (p *Profile) Write(w io.Writer) error {
zw := gzip.NewWriter(w)
defer zw.Close()
_, err := zw.Write(serialize(p))
return err
} | Write writes the profile as a gzip-compressed marshaled protobuf. | Write | go | k8snetworkplumbingwg/multus-cni | vendor/github.com/google/pprof/profile/profile.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/github.com/google/pprof/profile/profile.go | Apache-2.0 |
func (p *Profile) WriteUncompressed(w io.Writer) error {
_, err := w.Write(serialize(p))
return err
} | WriteUncompressed writes the profile as a marshaled protobuf. | WriteUncompressed | go | k8snetworkplumbingwg/multus-cni | vendor/github.com/google/pprof/profile/profile.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/github.com/google/pprof/profile/profile.go | Apache-2.0 |
func (p *Profile) CheckValid() error {
// Check that sample values are consistent
sampleLen := len(p.SampleType)
if sampleLen == 0 && len(p.Sample) != 0 {
return fmt.Errorf("missing sample type information")
}
for _, s := range p.Sample {
if s == nil {
return fmt.Errorf("profile has nil sample")
}
if len(s.Value) != sampleLen {
return fmt.Errorf("mismatch: sample has %d values vs. %d types", len(s.Value), len(p.SampleType))
}
for _, l := range s.Location {
if l == nil {
return fmt.Errorf("sample has nil location")
}
}
}
// Check that all mappings/locations/functions are in the tables
// Check that there are no duplicate ids
mappings := make(map[uint64]*Mapping, len(p.Mapping))
for _, m := range p.Mapping {
if m == nil {
return fmt.Errorf("profile has nil mapping")
}
if m.ID == 0 {
return fmt.Errorf("found mapping with reserved ID=0")
}
if mappings[m.ID] != nil {
return fmt.Errorf("multiple mappings with same id: %d", m.ID)
}
mappings[m.ID] = m
}
functions := make(map[uint64]*Function, len(p.Function))
for _, f := range p.Function {
if f == nil {
return fmt.Errorf("profile has nil function")
}
if f.ID == 0 {
return fmt.Errorf("found function with reserved ID=0")
}
if functions[f.ID] != nil {
return fmt.Errorf("multiple functions with same id: %d", f.ID)
}
functions[f.ID] = f
}
locations := make(map[uint64]*Location, len(p.Location))
for _, l := range p.Location {
if l == nil {
return fmt.Errorf("profile has nil location")
}
if l.ID == 0 {
return fmt.Errorf("found location with reserved id=0")
}
if locations[l.ID] != nil {
return fmt.Errorf("multiple locations with same id: %d", l.ID)
}
locations[l.ID] = l
if m := l.Mapping; m != nil {
if m.ID == 0 || mappings[m.ID] != m {
return fmt.Errorf("inconsistent mapping %p: %d", m, m.ID)
}
}
for _, ln := range l.Line {
f := ln.Function
if f == nil {
return fmt.Errorf("location id: %d has a line with nil function", l.ID)
}
if f.ID == 0 || functions[f.ID] != f {
return fmt.Errorf("inconsistent function %p: %d", f, f.ID)
}
}
}
return nil
} | CheckValid tests whether the profile is valid. Checks include, but are
not limited to:
- len(Profile.Sample[n].value) == len(Profile.value_unit)
- Sample.id has a corresponding Profile.Location | CheckValid | go | k8snetworkplumbingwg/multus-cni | vendor/github.com/google/pprof/profile/profile.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/github.com/google/pprof/profile/profile.go | Apache-2.0 |
func (p *Profile) Aggregate(inlineFrame, function, filename, linenumber, columnnumber, address bool) error {
for _, m := range p.Mapping {
m.HasInlineFrames = m.HasInlineFrames && inlineFrame
m.HasFunctions = m.HasFunctions && function
m.HasFilenames = m.HasFilenames && filename
m.HasLineNumbers = m.HasLineNumbers && linenumber
}
// Aggregate functions
if !function || !filename {
for _, f := range p.Function {
if !function {
f.Name = ""
f.SystemName = ""
}
if !filename {
f.Filename = ""
}
}
}
// Aggregate locations
if !inlineFrame || !address || !linenumber || !columnnumber {
for _, l := range p.Location {
if !inlineFrame && len(l.Line) > 1 {
l.Line = l.Line[len(l.Line)-1:]
}
if !linenumber {
for i := range l.Line {
l.Line[i].Line = 0
l.Line[i].Column = 0
}
}
if !columnnumber {
for i := range l.Line {
l.Line[i].Column = 0
}
}
if !address {
l.Address = 0
}
}
}
return p.CheckValid()
} | Aggregate merges the locations in the profile into equivalence
classes preserving the request attributes. It also updates the
samples to point to the merged locations. | Aggregate | go | k8snetworkplumbingwg/multus-cni | vendor/github.com/google/pprof/profile/profile.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/github.com/google/pprof/profile/profile.go | Apache-2.0 |
func (p *Profile) NumLabelUnits() (map[string]string, map[string][]string) {
numLabelUnits := map[string]string{}
ignoredUnits := map[string]map[string]bool{}
encounteredKeys := map[string]bool{}
// Determine units based on numeric tags for each sample.
for _, s := range p.Sample {
for k := range s.NumLabel {
encounteredKeys[k] = true
for _, unit := range s.NumUnit[k] {
if unit == "" {
continue
}
if wantUnit, ok := numLabelUnits[k]; !ok {
numLabelUnits[k] = unit
} else if wantUnit != unit {
if v, ok := ignoredUnits[k]; ok {
v[unit] = true
} else {
ignoredUnits[k] = map[string]bool{unit: true}
}
}
}
}
}
// Infer units for keys without any units associated with
// numeric tag values.
for key := range encounteredKeys {
unit := numLabelUnits[key]
if unit == "" {
switch key {
case "alignment", "request":
numLabelUnits[key] = "bytes"
default:
numLabelUnits[key] = key
}
}
}
// Copy ignored units into more readable format
unitsIgnored := make(map[string][]string, len(ignoredUnits))
for key, values := range ignoredUnits {
units := make([]string, len(values))
i := 0
for unit := range values {
units[i] = unit
i++
}
sort.Strings(units)
unitsIgnored[key] = units
}
return numLabelUnits, unitsIgnored
} | NumLabelUnits returns a map of numeric label keys to the units
associated with those keys and a map of those keys to any units
that were encountered but not used.
Unit for a given key is the first encountered unit for that key. If multiple
units are encountered for values paired with a particular key, then the first
unit encountered is used and all other units are returned in sorted order
in map of ignored units.
If no units are encountered for a particular key, the unit is then inferred
based on the key. | NumLabelUnits | go | k8snetworkplumbingwg/multus-cni | vendor/github.com/google/pprof/profile/profile.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/github.com/google/pprof/profile/profile.go | Apache-2.0 |
func (p *Profile) String() string {
ss := make([]string, 0, len(p.Comments)+len(p.Sample)+len(p.Mapping)+len(p.Location))
for _, c := range p.Comments {
ss = append(ss, "Comment: "+c)
}
if pt := p.PeriodType; pt != nil {
ss = append(ss, fmt.Sprintf("PeriodType: %s %s", pt.Type, pt.Unit))
}
ss = append(ss, fmt.Sprintf("Period: %d", p.Period))
if p.TimeNanos != 0 {
ss = append(ss, fmt.Sprintf("Time: %v", time.Unix(0, p.TimeNanos)))
}
if p.DurationNanos != 0 {
ss = append(ss, fmt.Sprintf("Duration: %.4v", time.Duration(p.DurationNanos)))
}
ss = append(ss, "Samples:")
var sh1 string
for _, s := range p.SampleType {
dflt := ""
if s.Type == p.DefaultSampleType {
dflt = "[dflt]"
}
sh1 = sh1 + fmt.Sprintf("%s/%s%s ", s.Type, s.Unit, dflt)
}
ss = append(ss, strings.TrimSpace(sh1))
for _, s := range p.Sample {
ss = append(ss, s.string())
}
ss = append(ss, "Locations")
for _, l := range p.Location {
ss = append(ss, l.string())
}
ss = append(ss, "Mappings")
for _, m := range p.Mapping {
ss = append(ss, m.string())
}
return strings.Join(ss, "\n") + "\n"
} | String dumps a text representation of a profile. Intended mainly
for debugging purposes. | String | go | k8snetworkplumbingwg/multus-cni | vendor/github.com/google/pprof/profile/profile.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/github.com/google/pprof/profile/profile.go | Apache-2.0 |
func (m *Mapping) string() string {
bits := ""
if m.HasFunctions {
bits = bits + "[FN]"
}
if m.HasFilenames {
bits = bits + "[FL]"
}
if m.HasLineNumbers {
bits = bits + "[LN]"
}
if m.HasInlineFrames {
bits = bits + "[IN]"
}
return fmt.Sprintf("%d: %#x/%#x/%#x %s %s %s",
m.ID,
m.Start, m.Limit, m.Offset,
m.File,
m.BuildID,
bits)
} | string dumps a text representation of a mapping. Intended mainly
for debugging purposes. | string | go | k8snetworkplumbingwg/multus-cni | vendor/github.com/google/pprof/profile/profile.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/github.com/google/pprof/profile/profile.go | Apache-2.0 |
func (l *Location) string() string {
ss := []string{}
locStr := fmt.Sprintf("%6d: %#x ", l.ID, l.Address)
if m := l.Mapping; m != nil {
locStr = locStr + fmt.Sprintf("M=%d ", m.ID)
}
if l.IsFolded {
locStr = locStr + "[F] "
}
if len(l.Line) == 0 {
ss = append(ss, locStr)
}
for li := range l.Line {
lnStr := "??"
if fn := l.Line[li].Function; fn != nil {
lnStr = fmt.Sprintf("%s %s:%d:%d s=%d",
fn.Name,
fn.Filename,
l.Line[li].Line,
l.Line[li].Column,
fn.StartLine)
if fn.Name != fn.SystemName {
lnStr = lnStr + "(" + fn.SystemName + ")"
}
}
ss = append(ss, locStr+lnStr)
// Do not print location details past the first line
locStr = " "
}
return strings.Join(ss, "\n")
} | string dumps a text representation of a location. Intended mainly
for debugging purposes. | string | go | k8snetworkplumbingwg/multus-cni | vendor/github.com/google/pprof/profile/profile.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/github.com/google/pprof/profile/profile.go | Apache-2.0 |
func (s *Sample) string() string {
ss := []string{}
var sv string
for _, v := range s.Value {
sv = fmt.Sprintf("%s %10d", sv, v)
}
sv = sv + ": "
for _, l := range s.Location {
sv = sv + fmt.Sprintf("%d ", l.ID)
}
ss = append(ss, sv)
const labelHeader = " "
if len(s.Label) > 0 {
ss = append(ss, labelHeader+labelsToString(s.Label))
}
if len(s.NumLabel) > 0 {
ss = append(ss, labelHeader+numLabelsToString(s.NumLabel, s.NumUnit))
}
return strings.Join(ss, "\n")
} | string dumps a text representation of a sample. Intended mainly
for debugging purposes. | string | go | k8snetworkplumbingwg/multus-cni | vendor/github.com/google/pprof/profile/profile.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/github.com/google/pprof/profile/profile.go | Apache-2.0 |
func labelsToString(labels map[string][]string) string {
ls := []string{}
for k, v := range labels {
ls = append(ls, fmt.Sprintf("%s:%v", k, v))
}
sort.Strings(ls)
return strings.Join(ls, " ")
} | labelsToString returns a string representation of a
map representing labels. | labelsToString | go | k8snetworkplumbingwg/multus-cni | vendor/github.com/google/pprof/profile/profile.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/github.com/google/pprof/profile/profile.go | Apache-2.0 |
func numLabelsToString(numLabels map[string][]int64, numUnits map[string][]string) string {
ls := []string{}
for k, v := range numLabels {
units := numUnits[k]
var labelString string
if len(units) == len(v) {
values := make([]string, len(v))
for i, vv := range v {
values[i] = fmt.Sprintf("%d %s", vv, units[i])
}
labelString = fmt.Sprintf("%s:%v", k, values)
} else {
labelString = fmt.Sprintf("%s:%v", k, v)
}
ls = append(ls, labelString)
}
sort.Strings(ls)
return strings.Join(ls, " ")
} | numLabelsToString returns a string representation of a map
representing numeric labels. | numLabelsToString | go | k8snetworkplumbingwg/multus-cni | vendor/github.com/google/pprof/profile/profile.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/github.com/google/pprof/profile/profile.go | Apache-2.0 |
func (p *Profile) SetLabel(key string, value []string) {
for _, sample := range p.Sample {
if sample.Label == nil {
sample.Label = map[string][]string{key: value}
} else {
sample.Label[key] = value
}
}
} | SetLabel sets the specified key to the specified value for all samples in the
profile. | SetLabel | go | k8snetworkplumbingwg/multus-cni | vendor/github.com/google/pprof/profile/profile.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/github.com/google/pprof/profile/profile.go | Apache-2.0 |
func (p *Profile) RemoveLabel(key string) {
for _, sample := range p.Sample {
delete(sample.Label, key)
}
} | RemoveLabel removes all labels associated with the specified key for all
samples in the profile. | RemoveLabel | go | k8snetworkplumbingwg/multus-cni | vendor/github.com/google/pprof/profile/profile.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/github.com/google/pprof/profile/profile.go | Apache-2.0 |
func (s *Sample) HasLabel(key, value string) bool {
for _, v := range s.Label[key] {
if v == value {
return true
}
}
return false
} | HasLabel returns true if a sample has a label with indicated key and value. | HasLabel | go | k8snetworkplumbingwg/multus-cni | vendor/github.com/google/pprof/profile/profile.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/github.com/google/pprof/profile/profile.go | Apache-2.0 |
func (p *Profile) SetNumLabel(key string, value []int64, unit []string) {
for _, sample := range p.Sample {
if sample.NumLabel == nil {
sample.NumLabel = map[string][]int64{key: value}
} else {
sample.NumLabel[key] = value
}
if sample.NumUnit == nil {
sample.NumUnit = map[string][]string{key: unit}
} else {
sample.NumUnit[key] = unit
}
}
} | SetNumLabel sets the specified key to the specified value for all samples in the
profile. "unit" is a slice that describes the units that each corresponding member
of "values" is measured in (e.g. bytes or seconds). If there is no relevant
unit for a given value, that member of "unit" should be the empty string.
"unit" must either have the same length as "value", or be nil. | SetNumLabel | go | k8snetworkplumbingwg/multus-cni | vendor/github.com/google/pprof/profile/profile.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/github.com/google/pprof/profile/profile.go | Apache-2.0 |
func (p *Profile) RemoveNumLabel(key string) {
for _, sample := range p.Sample {
delete(sample.NumLabel, key)
delete(sample.NumUnit, key)
}
} | RemoveNumLabel removes all numerical labels associated with the specified key for all
samples in the profile. | RemoveNumLabel | go | k8snetworkplumbingwg/multus-cni | vendor/github.com/google/pprof/profile/profile.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/github.com/google/pprof/profile/profile.go | Apache-2.0 |
func (s *Sample) DiffBaseSample() bool {
return s.HasLabel("pprof::base", "true")
} | DiffBaseSample returns true if a sample belongs to the diff base and false
otherwise. | DiffBaseSample | go | k8snetworkplumbingwg/multus-cni | vendor/github.com/google/pprof/profile/profile.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/github.com/google/pprof/profile/profile.go | Apache-2.0 |
func (p *Profile) Scale(ratio float64) {
if ratio == 1 {
return
}
ratios := make([]float64, len(p.SampleType))
for i := range p.SampleType {
ratios[i] = ratio
}
p.ScaleN(ratios)
} | Scale multiplies all sample values in a profile by a constant and keeps
only samples that have at least one non-zero value. | Scale | go | k8snetworkplumbingwg/multus-cni | vendor/github.com/google/pprof/profile/profile.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/github.com/google/pprof/profile/profile.go | Apache-2.0 |
func (p *Profile) ScaleN(ratios []float64) error {
if len(p.SampleType) != len(ratios) {
return fmt.Errorf("mismatched scale ratios, got %d, want %d", len(ratios), len(p.SampleType))
}
allOnes := true
for _, r := range ratios {
if r != 1 {
allOnes = false
break
}
}
if allOnes {
return nil
}
fillIdx := 0
for _, s := range p.Sample {
keepSample := false
for i, v := range s.Value {
if ratios[i] != 1 {
val := int64(math.Round(float64(v) * ratios[i]))
s.Value[i] = val
keepSample = keepSample || val != 0
}
}
if keepSample {
p.Sample[fillIdx] = s
fillIdx++
}
}
p.Sample = p.Sample[:fillIdx]
return nil
} | ScaleN multiplies each sample values in a sample by a different amount
and keeps only samples that have at least one non-zero value. | ScaleN | go | k8snetworkplumbingwg/multus-cni | vendor/github.com/google/pprof/profile/profile.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/github.com/google/pprof/profile/profile.go | Apache-2.0 |
func (p *Profile) HasFunctions() bool {
for _, l := range p.Location {
if l.Mapping != nil && !l.Mapping.HasFunctions {
return false
}
}
return true
} | HasFunctions determines if all locations in this profile have
symbolized function information. | HasFunctions | go | k8snetworkplumbingwg/multus-cni | vendor/github.com/google/pprof/profile/profile.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/github.com/google/pprof/profile/profile.go | Apache-2.0 |
func (p *Profile) HasFileLines() bool {
for _, l := range p.Location {
if l.Mapping != nil && (!l.Mapping.HasFilenames || !l.Mapping.HasLineNumbers) {
return false
}
}
return true
} | HasFileLines determines if all locations in this profile have
symbolized file and line number information. | HasFileLines | go | k8snetworkplumbingwg/multus-cni | vendor/github.com/google/pprof/profile/profile.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/github.com/google/pprof/profile/profile.go | Apache-2.0 |
func (m *Mapping) Unsymbolizable() bool {
name := filepath.Base(m.File)
return strings.HasPrefix(name, "[") || strings.HasPrefix(name, "linux-vdso") || strings.HasPrefix(m.File, "/dev/dri/") || m.File == "//anon"
} | Unsymbolizable returns true if a mapping points to a binary for which
locations can't be symbolized in principle, at least now. Examples are
"[vdso]", [vsyscall]" and some others, see the code. | Unsymbolizable | go | k8snetworkplumbingwg/multus-cni | vendor/github.com/google/pprof/profile/profile.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/github.com/google/pprof/profile/profile.go | Apache-2.0 |
func (p *Profile) Copy() *Profile {
pp := &Profile{}
if err := unmarshal(serialize(p), pp); err != nil {
panic(err)
}
if err := pp.postDecode(); err != nil {
panic(err)
}
return pp
} | Copy makes a fully independent copy of a profile. | Copy | go | k8snetworkplumbingwg/multus-cni | vendor/github.com/google/pprof/profile/profile.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/github.com/google/pprof/profile/profile.go | Apache-2.0 |
func javaCPUProfile(b []byte, period int64, parse func(b []byte) (uint64, []byte)) (*Profile, error) {
p := &Profile{
Period: period * 1000,
PeriodType: &ValueType{Type: "cpu", Unit: "nanoseconds"},
SampleType: []*ValueType{{Type: "samples", Unit: "count"}, {Type: "cpu", Unit: "nanoseconds"}},
}
var err error
var locs map[uint64]*Location
if b, locs, err = parseCPUSamples(b, parse, false, p); err != nil {
return nil, err
}
if err = parseJavaLocations(b, locs, p); err != nil {
return nil, err
}
// Strip out addresses for better merge.
if err = p.Aggregate(true, true, true, true, false, false); err != nil {
return nil, err
}
return p, nil
} | javaCPUProfile returns a new Profile from profilez data.
b is the profile bytes after the header, period is the profiling
period, and parse is a function to parse 8-byte chunks from the
profile in its native endianness. | javaCPUProfile | go | k8snetworkplumbingwg/multus-cni | vendor/github.com/google/pprof/profile/legacy_java_profile.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/github.com/google/pprof/profile/legacy_java_profile.go | Apache-2.0 |
func parseJavaProfile(b []byte) (*Profile, error) {
h := bytes.SplitAfterN(b, []byte("\n"), 2)
if len(h) < 2 {
return nil, errUnrecognized
}
p := &Profile{
PeriodType: &ValueType{},
}
header := string(bytes.TrimSpace(h[0]))
var err error
var pType string
switch header {
case "--- heapz 1 ---":
pType = "heap"
case "--- contentionz 1 ---":
pType = "contention"
default:
return nil, errUnrecognized
}
if b, err = parseJavaHeader(pType, h[1], p); err != nil {
return nil, err
}
var locs map[uint64]*Location
if b, locs, err = parseJavaSamples(pType, b, p); err != nil {
return nil, err
}
if err = parseJavaLocations(b, locs, p); err != nil {
return nil, err
}
// Strip out addresses for better merge.
if err = p.Aggregate(true, true, true, true, false, false); err != nil {
return nil, err
}
return p, nil
} | parseJavaProfile returns a new profile from heapz or contentionz
data. b is the profile bytes after the header. | parseJavaProfile | go | k8snetworkplumbingwg/multus-cni | vendor/github.com/google/pprof/profile/legacy_java_profile.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/github.com/google/pprof/profile/legacy_java_profile.go | Apache-2.0 |
func parseJavaHeader(pType string, b []byte, p *Profile) ([]byte, error) {
nextNewLine := bytes.IndexByte(b, byte('\n'))
for nextNewLine != -1 {
line := string(bytes.TrimSpace(b[0:nextNewLine]))
if line != "" {
h := attributeRx.FindStringSubmatch(line)
if h == nil {
// Not a valid attribute, exit.
return b, nil
}
attribute, value := strings.TrimSpace(h[1]), strings.TrimSpace(h[2])
var err error
switch pType + "/" + attribute {
case "heap/format", "cpu/format", "contention/format":
if value != "java" {
return nil, errUnrecognized
}
case "heap/resolution":
p.SampleType = []*ValueType{
{Type: "inuse_objects", Unit: "count"},
{Type: "inuse_space", Unit: value},
}
case "contention/resolution":
p.SampleType = []*ValueType{
{Type: "contentions", Unit: "count"},
{Type: "delay", Unit: value},
}
case "contention/sampling period":
p.PeriodType = &ValueType{
Type: "contentions", Unit: "count",
}
if p.Period, err = strconv.ParseInt(value, 0, 64); err != nil {
return nil, fmt.Errorf("failed to parse attribute %s: %v", line, err)
}
case "contention/ms since reset":
millis, err := strconv.ParseInt(value, 0, 64)
if err != nil {
return nil, fmt.Errorf("failed to parse attribute %s: %v", line, err)
}
p.DurationNanos = millis * 1000 * 1000
default:
return nil, errUnrecognized
}
}
// Grab next line.
b = b[nextNewLine+1:]
nextNewLine = bytes.IndexByte(b, byte('\n'))
}
return b, nil
} | parseJavaHeader parses the attribute section on a java profile and
populates a profile. Returns the remainder of the buffer after all
attributes. | parseJavaHeader | go | k8snetworkplumbingwg/multus-cni | vendor/github.com/google/pprof/profile/legacy_java_profile.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/github.com/google/pprof/profile/legacy_java_profile.go | Apache-2.0 |
func parseJavaSamples(pType string, b []byte, p *Profile) ([]byte, map[uint64]*Location, error) {
nextNewLine := bytes.IndexByte(b, byte('\n'))
locs := make(map[uint64]*Location)
for nextNewLine != -1 {
line := string(bytes.TrimSpace(b[0:nextNewLine]))
if line != "" {
sample := javaSampleRx.FindStringSubmatch(line)
if sample == nil {
// Not a valid sample, exit.
return b, locs, nil
}
// Java profiles have data/fields inverted compared to other
// profile types.
var err error
value1, value2, value3 := sample[2], sample[1], sample[3]
addrs, err := parseHexAddresses(value3)
if err != nil {
return nil, nil, fmt.Errorf("malformed sample: %s: %v", line, err)
}
var sloc []*Location
for _, addr := range addrs {
loc := locs[addr]
if locs[addr] == nil {
loc = &Location{
Address: addr,
}
p.Location = append(p.Location, loc)
locs[addr] = loc
}
sloc = append(sloc, loc)
}
s := &Sample{
Value: make([]int64, 2),
Location: sloc,
}
if s.Value[0], err = strconv.ParseInt(value1, 0, 64); err != nil {
return nil, nil, fmt.Errorf("parsing sample %s: %v", line, err)
}
if s.Value[1], err = strconv.ParseInt(value2, 0, 64); err != nil {
return nil, nil, fmt.Errorf("parsing sample %s: %v", line, err)
}
switch pType {
case "heap":
const javaHeapzSamplingRate = 524288 // 512K
if s.Value[0] == 0 {
return nil, nil, fmt.Errorf("parsing sample %s: second value must be non-zero", line)
}
s.NumLabel = map[string][]int64{"bytes": {s.Value[1] / s.Value[0]}}
s.Value[0], s.Value[1] = scaleHeapSample(s.Value[0], s.Value[1], javaHeapzSamplingRate)
case "contention":
if period := p.Period; period != 0 {
s.Value[0] = s.Value[0] * p.Period
s.Value[1] = s.Value[1] * p.Period
}
}
p.Sample = append(p.Sample, s)
}
// Grab next line.
b = b[nextNewLine+1:]
nextNewLine = bytes.IndexByte(b, byte('\n'))
}
return b, locs, nil
} | parseJavaSamples parses the samples from a java profile and
populates the Samples in a profile. Returns the remainder of the
buffer after the samples. | parseJavaSamples | go | k8snetworkplumbingwg/multus-cni | vendor/github.com/google/pprof/profile/legacy_java_profile.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/github.com/google/pprof/profile/legacy_java_profile.go | Apache-2.0 |
func parseJavaLocations(b []byte, locs map[uint64]*Location, p *Profile) error {
r := bytes.NewBuffer(b)
fns := make(map[string]*Function)
for {
line, err := r.ReadString('\n')
if err != nil {
if err != io.EOF {
return err
}
if line == "" {
break
}
}
if line = strings.TrimSpace(line); line == "" {
continue
}
jloc := javaLocationRx.FindStringSubmatch(line)
if len(jloc) != 3 {
continue
}
addr, err := strconv.ParseUint(jloc[1], 16, 64)
if err != nil {
return fmt.Errorf("parsing sample %s: %v", line, err)
}
loc := locs[addr]
if loc == nil {
// Unused/unseen
continue
}
var lineFunc, lineFile string
var lineNo int64
if fileLine := javaLocationFileLineRx.FindStringSubmatch(jloc[2]); len(fileLine) == 4 {
// Found a line of the form: "function (file:line)"
lineFunc, lineFile = fileLine[1], fileLine[2]
if n, err := strconv.ParseInt(fileLine[3], 10, 64); err == nil && n > 0 {
lineNo = n
}
} else if filePath := javaLocationPathRx.FindStringSubmatch(jloc[2]); len(filePath) == 3 {
// If there's not a file:line, it's a shared library path.
// The path isn't interesting, so just give the .so.
lineFunc, lineFile = filePath[1], filepath.Base(filePath[2])
} else if strings.Contains(jloc[2], "generated stub/JIT") {
lineFunc = "STUB"
} else {
// Treat whole line as the function name. This is used by the
// java agent for internal states such as "GC" or "VM".
lineFunc = jloc[2]
}
fn := fns[lineFunc]
if fn == nil {
fn = &Function{
Name: lineFunc,
SystemName: lineFunc,
Filename: lineFile,
}
fns[lineFunc] = fn
p.Function = append(p.Function, fn)
}
loc.Line = []Line{
{
Function: fn,
Line: lineNo,
},
}
loc.Address = 0
}
p.remapLocationIDs()
p.remapFunctionIDs()
p.remapMappingIDs()
return nil
} | parseJavaLocations parses the location information in a java
profile and populates the Locations in a profile. It uses the
location addresses from the profile as both the ID of each
location. | parseJavaLocations | go | k8snetworkplumbingwg/multus-cni | vendor/github.com/google/pprof/profile/legacy_java_profile.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/github.com/google/pprof/profile/legacy_java_profile.go | Apache-2.0 |
func (p *Profile) SampleIndexByName(sampleIndex string) (int, error) {
if sampleIndex == "" {
if dst := p.DefaultSampleType; dst != "" {
for i, t := range sampleTypes(p) {
if t == dst {
return i, nil
}
}
}
// By default select the last sample value
return len(p.SampleType) - 1, nil
}
if i, err := strconv.Atoi(sampleIndex); err == nil {
if i < 0 || i >= len(p.SampleType) {
return 0, fmt.Errorf("sample_index %s is outside the range [0..%d]", sampleIndex, len(p.SampleType)-1)
}
return i, nil
}
// Remove the inuse_ prefix to support legacy pprof options
// "inuse_space" and "inuse_objects" for profiles containing types
// "space" and "objects".
noInuse := strings.TrimPrefix(sampleIndex, "inuse_")
for i, t := range p.SampleType {
if t.Type == sampleIndex || t.Type == noInuse {
return i, nil
}
}
return 0, fmt.Errorf("sample_index %q must be one of: %v", sampleIndex, sampleTypes(p))
} | SampleIndexByName returns the appropriate index for a value of sample index.
If numeric, it returns the number, otherwise it looks up the text in the
profile sample types. | SampleIndexByName | go | k8snetworkplumbingwg/multus-cni | vendor/github.com/google/pprof/profile/index.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/github.com/google/pprof/profile/index.go | Apache-2.0 |
func parseGoCount(b []byte) (*Profile, error) {
s := bufio.NewScanner(bytes.NewBuffer(b))
// Skip comments at the beginning of the file.
for s.Scan() && isSpaceOrComment(s.Text()) {
}
if err := s.Err(); err != nil {
return nil, err
}
m := countStartRE.FindStringSubmatch(s.Text())
if m == nil {
return nil, errUnrecognized
}
profileType := m[1]
p := &Profile{
PeriodType: &ValueType{Type: profileType, Unit: "count"},
Period: 1,
SampleType: []*ValueType{{Type: profileType, Unit: "count"}},
}
locations := make(map[uint64]*Location)
for s.Scan() {
line := s.Text()
if isSpaceOrComment(line) {
continue
}
if strings.HasPrefix(line, "---") {
break
}
m := countRE.FindStringSubmatch(line)
if m == nil {
return nil, errMalformed
}
n, err := strconv.ParseInt(m[1], 0, 64)
if err != nil {
return nil, errMalformed
}
fields := strings.Fields(m[2])
locs := make([]*Location, 0, len(fields))
for _, stk := range fields {
addr, err := strconv.ParseUint(stk, 0, 64)
if err != nil {
return nil, errMalformed
}
// Adjust all frames by -1 to land on top of the call instruction.
addr--
loc := locations[addr]
if loc == nil {
loc = &Location{
Address: addr,
}
locations[addr] = loc
p.Location = append(p.Location, loc)
}
locs = append(locs, loc)
}
p.Sample = append(p.Sample, &Sample{
Location: locs,
Value: []int64{n},
})
}
if err := s.Err(); err != nil {
return nil, err
}
if err := parseAdditionalSections(s, p); err != nil {
return nil, err
}
return p, nil
} | parseGoCount parses a Go count profile (e.g., threadcreate or
goroutine) and returns a new Profile. | parseGoCount | go | k8snetworkplumbingwg/multus-cni | vendor/github.com/google/pprof/profile/legacy_profile.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/github.com/google/pprof/profile/legacy_profile.go | Apache-2.0 |
func (p *Profile) remapLocationIDs() {
seen := make(map[*Location]bool, len(p.Location))
var locs []*Location
for _, s := range p.Sample {
for _, l := range s.Location {
if seen[l] {
continue
}
l.ID = uint64(len(locs) + 1)
locs = append(locs, l)
seen[l] = true
}
}
p.Location = locs
} | remapLocationIDs ensures there is a location for each address
referenced by a sample, and remaps the samples to point to the new
location ids. | remapLocationIDs | go | k8snetworkplumbingwg/multus-cni | vendor/github.com/google/pprof/profile/legacy_profile.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/github.com/google/pprof/profile/legacy_profile.go | Apache-2.0 |
func (p *Profile) remapMappingIDs() {
// Some profile handlers will incorrectly set regions for the main
// executable if its section is remapped. Fix them through heuristics.
if len(p.Mapping) > 0 {
// Remove the initial mapping if named '/anon_hugepage' and has a
// consecutive adjacent mapping.
if m := p.Mapping[0]; strings.HasPrefix(m.File, "/anon_hugepage") {
if len(p.Mapping) > 1 && m.Limit == p.Mapping[1].Start {
p.Mapping = p.Mapping[1:]
}
}
}
// Subtract the offset from the start of the main mapping if it
// ends up at a recognizable start address.
if len(p.Mapping) > 0 {
const expectedStart = 0x400000
if m := p.Mapping[0]; m.Start-m.Offset == expectedStart {
m.Start = expectedStart
m.Offset = 0
}
}
// Associate each location with an address to the corresponding
// mapping. Create fake mapping if a suitable one isn't found.
var fake *Mapping
nextLocation:
for _, l := range p.Location {
a := l.Address
if l.Mapping != nil || a == 0 {
continue
}
for _, m := range p.Mapping {
if m.Start <= a && a < m.Limit {
l.Mapping = m
continue nextLocation
}
}
// Work around legacy handlers failing to encode the first
// part of mappings split into adjacent ranges.
for _, m := range p.Mapping {
if m.Offset != 0 && m.Start-m.Offset <= a && a < m.Start {
m.Start -= m.Offset
m.Offset = 0
l.Mapping = m
continue nextLocation
}
}
// If there is still no mapping, create a fake one.
// This is important for the Go legacy handler, which produced
// no mappings.
if fake == nil {
fake = &Mapping{
ID: 1,
Limit: ^uint64(0),
}
p.Mapping = append(p.Mapping, fake)
}
l.Mapping = fake
}
// Reset all mapping IDs.
for i, m := range p.Mapping {
m.ID = uint64(i + 1)
}
} | remapMappingIDs matches location addresses with existing mappings
and updates them appropriately. This is O(N*M), if this ever shows
up as a bottleneck, evaluate sorting the mappings and doing a
binary search, which would make it O(N*log(M)). | remapMappingIDs | go | k8snetworkplumbingwg/multus-cni | vendor/github.com/google/pprof/profile/legacy_profile.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/github.com/google/pprof/profile/legacy_profile.go | Apache-2.0 |
func parseCPU(b []byte) (*Profile, error) {
var parse func([]byte) (uint64, []byte)
var n1, n2, n3, n4, n5 uint64
for _, parse = range cpuInts {
var tmp []byte
n1, tmp = parse(b)
n2, tmp = parse(tmp)
n3, tmp = parse(tmp)
n4, tmp = parse(tmp)
n5, tmp = parse(tmp)
if tmp != nil && n1 == 0 && n2 == 3 && n3 == 0 && n4 > 0 && n5 == 0 {
b = tmp
return cpuProfile(b, int64(n4), parse)
}
if tmp != nil && n1 == 0 && n2 == 3 && n3 == 1 && n4 > 0 && n5 == 0 {
b = tmp
return javaCPUProfile(b, int64(n4), parse)
}
}
return nil, errUnrecognized
} | parseCPU parses a profilez legacy profile and returns a newly
populated Profile.
The general format for profilez samples is a sequence of words in
binary format. The first words are a header with the following data:
1st word -- 0
2nd word -- 3
3rd word -- 0 if a c++ application, 1 if a java application.
4th word -- Sampling period (in microseconds).
5th word -- Padding. | parseCPU | go | k8snetworkplumbingwg/multus-cni | vendor/github.com/google/pprof/profile/legacy_profile.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/github.com/google/pprof/profile/legacy_profile.go | Apache-2.0 |
func cpuProfile(b []byte, period int64, parse func(b []byte) (uint64, []byte)) (*Profile, error) {
p := &Profile{
Period: period * 1000,
PeriodType: &ValueType{Type: "cpu", Unit: "nanoseconds"},
SampleType: []*ValueType{
{Type: "samples", Unit: "count"},
{Type: "cpu", Unit: "nanoseconds"},
},
}
var err error
if b, _, err = parseCPUSamples(b, parse, true, p); err != nil {
return nil, err
}
// If *most* samples have the same second-to-the-bottom frame, it
// strongly suggests that it is an uninteresting artifact of
// measurement -- a stack frame pushed by the signal handler. The
// bottom frame is always correct as it is picked up from the signal
// structure, not the stack. Check if this is the case and if so,
// remove.
// Remove up to two frames.
maxiter := 2
// Allow one different sample for this many samples with the same
// second-to-last frame.
similarSamples := 32
margin := len(p.Sample) / similarSamples
for iter := 0; iter < maxiter; iter++ {
addr1 := make(map[uint64]int)
for _, s := range p.Sample {
if len(s.Location) > 1 {
a := s.Location[1].Address
addr1[a] = addr1[a] + 1
}
}
for id1, count := range addr1 {
if count >= len(p.Sample)-margin {
// Found uninteresting frame, strip it out from all samples
for _, s := range p.Sample {
if len(s.Location) > 1 && s.Location[1].Address == id1 {
s.Location = append(s.Location[:1], s.Location[2:]...)
}
}
break
}
}
}
if err := p.ParseMemoryMap(bytes.NewBuffer(b)); err != nil {
return nil, err
}
cleanupDuplicateLocations(p)
return p, nil
} | cpuProfile returns a new Profile from C++ profilez data.
b is the profile bytes after the header, period is the profiling
period, and parse is a function to parse 8-byte chunks from the
profile in its native endianness. | cpuProfile | go | k8snetworkplumbingwg/multus-cni | vendor/github.com/google/pprof/profile/legacy_profile.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/github.com/google/pprof/profile/legacy_profile.go | Apache-2.0 |
func parseCPUSamples(b []byte, parse func(b []byte) (uint64, []byte), adjust bool, p *Profile) ([]byte, map[uint64]*Location, error) {
locs := make(map[uint64]*Location)
for len(b) > 0 {
var count, nstk uint64
count, b = parse(b)
nstk, b = parse(b)
if b == nil || nstk > uint64(len(b)/4) {
return nil, nil, errUnrecognized
}
var sloc []*Location
addrs := make([]uint64, nstk)
for i := 0; i < int(nstk); i++ {
addrs[i], b = parse(b)
}
if count == 0 && nstk == 1 && addrs[0] == 0 {
// End of data marker
break
}
for i, addr := range addrs {
if adjust && i > 0 {
addr--
}
loc := locs[addr]
if loc == nil {
loc = &Location{
Address: addr,
}
locs[addr] = loc
p.Location = append(p.Location, loc)
}
sloc = append(sloc, loc)
}
p.Sample = append(p.Sample,
&Sample{
Value: []int64{int64(count), int64(count) * p.Period},
Location: sloc,
})
}
// Reached the end without finding the EOD marker.
return b, locs, nil
} | parseCPUSamples parses a collection of profilez samples from a
profile.
profilez samples are a repeated sequence of stack frames of the
form:
1st word -- The number of times this stack was encountered.
2nd word -- The size of the stack (StackSize).
3rd word -- The first address on the stack.
...
StackSize + 2 -- The last address on the stack
The last stack trace is of the form:
1st word -- 0
2nd word -- 1
3rd word -- 0
Addresses from stack traces may point to the next instruction after
each call. Optionally adjust by -1 to land somewhere on the actual
call (except for the leaf, which is not a call). | parseCPUSamples | go | k8snetworkplumbingwg/multus-cni | vendor/github.com/google/pprof/profile/legacy_profile.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/github.com/google/pprof/profile/legacy_profile.go | Apache-2.0 |
func parseHeap(b []byte) (p *Profile, err error) {
s := bufio.NewScanner(bytes.NewBuffer(b))
if !s.Scan() {
if err := s.Err(); err != nil {
return nil, err
}
return nil, errUnrecognized
}
p = &Profile{}
sampling := ""
hasAlloc := false
line := s.Text()
p.PeriodType = &ValueType{Type: "space", Unit: "bytes"}
if header := heapHeaderRE.FindStringSubmatch(line); header != nil {
sampling, p.Period, hasAlloc, err = parseHeapHeader(line)
if err != nil {
return nil, err
}
} else if header = growthHeaderRE.FindStringSubmatch(line); header != nil {
p.Period = 1
} else if header = fragmentationHeaderRE.FindStringSubmatch(line); header != nil {
p.Period = 1
} else {
return nil, errUnrecognized
}
if hasAlloc {
// Put alloc before inuse so that default pprof selection
// will prefer inuse_space.
p.SampleType = []*ValueType{
{Type: "alloc_objects", Unit: "count"},
{Type: "alloc_space", Unit: "bytes"},
{Type: "inuse_objects", Unit: "count"},
{Type: "inuse_space", Unit: "bytes"},
}
} else {
p.SampleType = []*ValueType{
{Type: "objects", Unit: "count"},
{Type: "space", Unit: "bytes"},
}
}
locs := make(map[uint64]*Location)
for s.Scan() {
line := strings.TrimSpace(s.Text())
if isSpaceOrComment(line) {
continue
}
if isMemoryMapSentinel(line) {
break
}
value, blocksize, addrs, err := parseHeapSample(line, p.Period, sampling, hasAlloc)
if err != nil {
return nil, err
}
var sloc []*Location
for _, addr := range addrs {
// Addresses from stack traces point to the next instruction after
// each call. Adjust by -1 to land somewhere on the actual call.
addr--
loc := locs[addr]
if locs[addr] == nil {
loc = &Location{
Address: addr,
}
p.Location = append(p.Location, loc)
locs[addr] = loc
}
sloc = append(sloc, loc)
}
p.Sample = append(p.Sample, &Sample{
Value: value,
Location: sloc,
NumLabel: map[string][]int64{"bytes": {blocksize}},
})
}
if err := s.Err(); err != nil {
return nil, err
}
if err := parseAdditionalSections(s, p); err != nil {
return nil, err
}
return p, nil
} | parseHeap parses a heapz legacy or a growthz profile and
returns a newly populated Profile. | parseHeap | go | k8snetworkplumbingwg/multus-cni | vendor/github.com/google/pprof/profile/legacy_profile.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/github.com/google/pprof/profile/legacy_profile.go | Apache-2.0 |
func parseHeapSample(line string, rate int64, sampling string, includeAlloc bool) (value []int64, blocksize int64, addrs []uint64, err error) {
sampleData := heapSampleRE.FindStringSubmatch(line)
if len(sampleData) != 6 {
return nil, 0, nil, fmt.Errorf("unexpected number of sample values: got %d, want 6", len(sampleData))
}
// This is a local-scoped helper function to avoid needing to pass
// around rate, sampling and many return parameters.
addValues := func(countString, sizeString string, label string) error {
count, err := strconv.ParseInt(countString, 10, 64)
if err != nil {
return fmt.Errorf("malformed sample: %s: %v", line, err)
}
size, err := strconv.ParseInt(sizeString, 10, 64)
if err != nil {
return fmt.Errorf("malformed sample: %s: %v", line, err)
}
if count == 0 && size != 0 {
return fmt.Errorf("%s count was 0 but %s bytes was %d", label, label, size)
}
if count != 0 {
blocksize = size / count
if sampling == "v2" {
count, size = scaleHeapSample(count, size, rate)
}
}
value = append(value, count, size)
return nil
}
if includeAlloc {
if err := addValues(sampleData[3], sampleData[4], "allocation"); err != nil {
return nil, 0, nil, err
}
}
if err := addValues(sampleData[1], sampleData[2], "inuse"); err != nil {
return nil, 0, nil, err
}
addrs, err = parseHexAddresses(sampleData[5])
if err != nil {
return nil, 0, nil, fmt.Errorf("malformed sample: %s: %v", line, err)
}
return value, blocksize, addrs, nil
} | parseHeapSample parses a single row from a heap profile into a new Sample. | parseHeapSample | go | k8snetworkplumbingwg/multus-cni | vendor/github.com/google/pprof/profile/legacy_profile.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/github.com/google/pprof/profile/legacy_profile.go | Apache-2.0 |
func parseHexAddresses(s string) ([]uint64, error) {
hexStrings := hexNumberRE.FindAllString(s, -1)
var addrs []uint64
for _, s := range hexStrings {
if addr, err := strconv.ParseUint(s, 0, 64); err == nil {
addrs = append(addrs, addr)
} else {
return nil, fmt.Errorf("failed to parse as hex 64-bit number: %s", s)
}
}
return addrs, nil
} | parseHexAddresses extracts hex numbers from a string, attempts to convert
each to an unsigned 64-bit number and returns the resulting numbers as a
slice, or an error if the string contains hex numbers which are too large to
handle (which means a malformed profile). | parseHexAddresses | go | k8snetworkplumbingwg/multus-cni | vendor/github.com/google/pprof/profile/legacy_profile.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/github.com/google/pprof/profile/legacy_profile.go | Apache-2.0 |
func scaleHeapSample(count, size, rate int64) (int64, int64) {
if count == 0 || size == 0 {
return 0, 0
}
if rate <= 1 {
// if rate==1 all samples were collected so no adjustment is needed.
// if rate<1 treat as unknown and skip scaling.
return count, size
}
avgSize := float64(size) / float64(count)
scale := 1 / (1 - math.Exp(-avgSize/float64(rate)))
return int64(float64(count) * scale), int64(float64(size) * scale)
} | scaleHeapSample adjusts the data from a heapz Sample to
account for its probability of appearing in the collected
data. heapz profiles are a sampling of the memory allocations
requests in a program. We estimate the unsampled value by dividing
each collected sample by its probability of appearing in the
profile. heapz v2 profiles rely on a poisson process to determine
which samples to collect, based on the desired average collection
rate R. The probability of a sample of size S to appear in that
profile is 1-exp(-S/R). | scaleHeapSample | go | k8snetworkplumbingwg/multus-cni | vendor/github.com/google/pprof/profile/legacy_profile.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/github.com/google/pprof/profile/legacy_profile.go | Apache-2.0 |
func parseContention(b []byte) (*Profile, error) {
s := bufio.NewScanner(bytes.NewBuffer(b))
if !s.Scan() {
if err := s.Err(); err != nil {
return nil, err
}
return nil, errUnrecognized
}
switch l := s.Text(); {
case strings.HasPrefix(l, "--- contentionz "):
case strings.HasPrefix(l, "--- mutex:"):
case strings.HasPrefix(l, "--- contention:"):
default:
return nil, errUnrecognized
}
p := &Profile{
PeriodType: &ValueType{Type: "contentions", Unit: "count"},
Period: 1,
SampleType: []*ValueType{
{Type: "contentions", Unit: "count"},
{Type: "delay", Unit: "nanoseconds"},
},
}
var cpuHz int64
// Parse text of the form "attribute = value" before the samples.
const delimiter = "="
for s.Scan() {
line := s.Text()
if line = strings.TrimSpace(line); isSpaceOrComment(line) {
continue
}
if strings.HasPrefix(line, "---") {
break
}
attr := strings.SplitN(line, delimiter, 2)
if len(attr) != 2 {
break
}
key, val := strings.TrimSpace(attr[0]), strings.TrimSpace(attr[1])
var err error
switch key {
case "cycles/second":
if cpuHz, err = strconv.ParseInt(val, 0, 64); err != nil {
return nil, errUnrecognized
}
case "sampling period":
if p.Period, err = strconv.ParseInt(val, 0, 64); err != nil {
return nil, errUnrecognized
}
case "ms since reset":
ms, err := strconv.ParseInt(val, 0, 64)
if err != nil {
return nil, errUnrecognized
}
p.DurationNanos = ms * 1000 * 1000
case "format":
// CPP contentionz profiles don't have format.
return nil, errUnrecognized
case "resolution":
// CPP contentionz profiles don't have resolution.
return nil, errUnrecognized
case "discarded samples":
default:
return nil, errUnrecognized
}
}
if err := s.Err(); err != nil {
return nil, err
}
locs := make(map[uint64]*Location)
for {
line := strings.TrimSpace(s.Text())
if strings.HasPrefix(line, "---") {
break
}
if !isSpaceOrComment(line) {
value, addrs, err := parseContentionSample(line, p.Period, cpuHz)
if err != nil {
return nil, err
}
var sloc []*Location
for _, addr := range addrs {
// Addresses from stack traces point to the next instruction after
// each call. Adjust by -1 to land somewhere on the actual call.
addr--
loc := locs[addr]
if locs[addr] == nil {
loc = &Location{
Address: addr,
}
p.Location = append(p.Location, loc)
locs[addr] = loc
}
sloc = append(sloc, loc)
}
p.Sample = append(p.Sample, &Sample{
Value: value,
Location: sloc,
})
}
if !s.Scan() {
break
}
}
if err := s.Err(); err != nil {
return nil, err
}
if err := parseAdditionalSections(s, p); err != nil {
return nil, err
}
return p, nil
} | parseContention parses a mutex or contention profile. There are 2 cases:
"--- contentionz " for legacy C++ profiles (and backwards compatibility)
"--- mutex:" or "--- contention:" for profiles generated by the Go runtime. | parseContention | go | k8snetworkplumbingwg/multus-cni | vendor/github.com/google/pprof/profile/legacy_profile.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/github.com/google/pprof/profile/legacy_profile.go | Apache-2.0 |
func parseContentionSample(line string, period, cpuHz int64) (value []int64, addrs []uint64, err error) {
sampleData := contentionSampleRE.FindStringSubmatch(line)
if sampleData == nil {
return nil, nil, errUnrecognized
}
v1, err := strconv.ParseInt(sampleData[1], 10, 64)
if err != nil {
return nil, nil, fmt.Errorf("malformed sample: %s: %v", line, err)
}
v2, err := strconv.ParseInt(sampleData[2], 10, 64)
if err != nil {
return nil, nil, fmt.Errorf("malformed sample: %s: %v", line, err)
}
// Unsample values if period and cpuHz are available.
// - Delays are scaled to cycles and then to nanoseconds.
// - Contentions are scaled to cycles.
if period > 0 {
if cpuHz > 0 {
cpuGHz := float64(cpuHz) / 1e9
v1 = int64(float64(v1) * float64(period) / cpuGHz)
}
v2 = v2 * period
}
value = []int64{v2, v1}
addrs, err = parseHexAddresses(sampleData[3])
if err != nil {
return nil, nil, fmt.Errorf("malformed sample: %s: %v", line, err)
}
return value, addrs, nil
} | parseContentionSample parses a single row from a contention profile
into a new Sample. | parseContentionSample | go | k8snetworkplumbingwg/multus-cni | vendor/github.com/google/pprof/profile/legacy_profile.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/github.com/google/pprof/profile/legacy_profile.go | Apache-2.0 |
func parseThread(b []byte) (*Profile, error) {
s := bufio.NewScanner(bytes.NewBuffer(b))
// Skip past comments and empty lines seeking a real header.
for s.Scan() && isSpaceOrComment(s.Text()) {
}
line := s.Text()
if m := threadzStartRE.FindStringSubmatch(line); m != nil {
// Advance over initial comments until first stack trace.
for s.Scan() {
if line = s.Text(); isMemoryMapSentinel(line) || strings.HasPrefix(line, "-") {
break
}
}
} else if t := threadStartRE.FindStringSubmatch(line); len(t) != 4 {
return nil, errUnrecognized
}
p := &Profile{
SampleType: []*ValueType{{Type: "thread", Unit: "count"}},
PeriodType: &ValueType{Type: "thread", Unit: "count"},
Period: 1,
}
locs := make(map[uint64]*Location)
// Recognize each thread and populate profile samples.
for !isMemoryMapSentinel(line) {
if strings.HasPrefix(line, "---- no stack trace for") {
break
}
if t := threadStartRE.FindStringSubmatch(line); len(t) != 4 {
return nil, errUnrecognized
}
var addrs []uint64
var err error
line, addrs, err = parseThreadSample(s)
if err != nil {
return nil, err
}
if len(addrs) == 0 {
// We got a --same as previous threads--. Bump counters.
if len(p.Sample) > 0 {
s := p.Sample[len(p.Sample)-1]
s.Value[0]++
}
continue
}
var sloc []*Location
for i, addr := range addrs {
// Addresses from stack traces point to the next instruction after
// each call. Adjust by -1 to land somewhere on the actual call
// (except for the leaf, which is not a call).
if i > 0 {
addr--
}
loc := locs[addr]
if locs[addr] == nil {
loc = &Location{
Address: addr,
}
p.Location = append(p.Location, loc)
locs[addr] = loc
}
sloc = append(sloc, loc)
}
p.Sample = append(p.Sample, &Sample{
Value: []int64{1},
Location: sloc,
})
}
if err := parseAdditionalSections(s, p); err != nil {
return nil, err
}
cleanupDuplicateLocations(p)
return p, nil
} | parseThread parses a Threadz profile and returns a new Profile. | parseThread | go | k8snetworkplumbingwg/multus-cni | vendor/github.com/google/pprof/profile/legacy_profile.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/github.com/google/pprof/profile/legacy_profile.go | Apache-2.0 |
func parseThreadSample(s *bufio.Scanner) (nextl string, addrs []uint64, err error) {
var line string
sameAsPrevious := false
for s.Scan() {
line = strings.TrimSpace(s.Text())
if line == "" {
continue
}
if strings.HasPrefix(line, "---") {
break
}
if strings.Contains(line, "same as previous thread") {
sameAsPrevious = true
continue
}
curAddrs, err := parseHexAddresses(line)
if err != nil {
return "", nil, fmt.Errorf("malformed sample: %s: %v", line, err)
}
addrs = append(addrs, curAddrs...)
}
if err := s.Err(); err != nil {
return "", nil, err
}
if sameAsPrevious {
return line, nil, nil
}
return line, addrs, nil
} | parseThreadSample parses a symbolized or unsymbolized stack trace.
Returns the first line after the traceback, the sample (or nil if
it hits a 'same-as-previous' marker) and an error. | parseThreadSample | go | k8snetworkplumbingwg/multus-cni | vendor/github.com/google/pprof/profile/legacy_profile.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/github.com/google/pprof/profile/legacy_profile.go | Apache-2.0 |
func parseAdditionalSections(s *bufio.Scanner, p *Profile) error {
for !isMemoryMapSentinel(s.Text()) && s.Scan() {
}
if err := s.Err(); err != nil {
return err
}
return p.ParseMemoryMapFromScanner(s)
} | parseAdditionalSections parses any additional sections in the
profile, ignoring any unrecognized sections. | parseAdditionalSections | go | k8snetworkplumbingwg/multus-cni | vendor/github.com/google/pprof/profile/legacy_profile.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/github.com/google/pprof/profile/legacy_profile.go | Apache-2.0 |
func ParseProcMaps(rd io.Reader) ([]*Mapping, error) {
s := bufio.NewScanner(rd)
return parseProcMapsFromScanner(s)
} | ParseProcMaps parses a memory map in the format of /proc/self/maps.
ParseMemoryMap should be called after setting on a profile to
associate locations to the corresponding mapping based on their
address. | ParseProcMaps | go | k8snetworkplumbingwg/multus-cni | vendor/github.com/google/pprof/profile/legacy_profile.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/github.com/google/pprof/profile/legacy_profile.go | Apache-2.0 |
func removeLoggingInfo(line string) string {
if match := logInfoRE.FindStringIndex(line); match != nil {
return line[match[1]:]
}
return line
} | removeLoggingInfo detects and removes log prefix entries generated
by the glog package. If no logging prefix is detected, the string
is returned unmodified. | removeLoggingInfo | go | k8snetworkplumbingwg/multus-cni | vendor/github.com/google/pprof/profile/legacy_profile.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/github.com/google/pprof/profile/legacy_profile.go | Apache-2.0 |
func (p *Profile) ParseMemoryMap(rd io.Reader) error {
return p.ParseMemoryMapFromScanner(bufio.NewScanner(rd))
} | ParseMemoryMap parses a memory map in the format of
/proc/self/maps, and overrides the mappings in the current profile.
It renumbers the samples and locations in the profile correspondingly. | ParseMemoryMap | go | k8snetworkplumbingwg/multus-cni | vendor/github.com/google/pprof/profile/legacy_profile.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/github.com/google/pprof/profile/legacy_profile.go | Apache-2.0 |
func (p *Profile) ParseMemoryMapFromScanner(s *bufio.Scanner) error {
mapping, err := parseProcMapsFromScanner(s)
if err != nil {
return err
}
p.Mapping = append(p.Mapping, mapping...)
p.massageMappings()
p.remapLocationIDs()
p.remapFunctionIDs()
p.remapMappingIDs()
return nil
} | ParseMemoryMapFromScanner parses a memory map in the format of
/proc/self/maps or a variety of legacy format, and overrides the
mappings in the current profile. It renumbers the samples and
locations in the profile correspondingly. | ParseMemoryMapFromScanner | go | k8snetworkplumbingwg/multus-cni | vendor/github.com/google/pprof/profile/legacy_profile.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/github.com/google/pprof/profile/legacy_profile.go | Apache-2.0 |
func isMemoryMapSentinel(line string) bool {
for _, s := range memoryMapSentinels {
if strings.Contains(line, s) {
return true
}
}
return false
} | isMemoryMapSentinel returns true if the string contains one of the
known sentinels for memory map information. | isMemoryMapSentinel | go | k8snetworkplumbingwg/multus-cni | vendor/github.com/google/pprof/profile/legacy_profile.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/github.com/google/pprof/profile/legacy_profile.go | Apache-2.0 |
func (p *Profile) preEncode() {
strings := make(map[string]int)
addString(strings, "")
for _, st := range p.SampleType {
st.typeX = addString(strings, st.Type)
st.unitX = addString(strings, st.Unit)
}
for _, s := range p.Sample {
s.labelX = nil
var keys []string
for k := range s.Label {
keys = append(keys, k)
}
sort.Strings(keys)
for _, k := range keys {
vs := s.Label[k]
for _, v := range vs {
s.labelX = append(s.labelX,
label{
keyX: addString(strings, k),
strX: addString(strings, v),
},
)
}
}
var numKeys []string
for k := range s.NumLabel {
numKeys = append(numKeys, k)
}
sort.Strings(numKeys)
for _, k := range numKeys {
keyX := addString(strings, k)
vs := s.NumLabel[k]
units := s.NumUnit[k]
for i, v := range vs {
var unitX int64
if len(units) != 0 {
unitX = addString(strings, units[i])
}
s.labelX = append(s.labelX,
label{
keyX: keyX,
numX: v,
unitX: unitX,
},
)
}
}
s.locationIDX = make([]uint64, len(s.Location))
for i, loc := range s.Location {
s.locationIDX[i] = loc.ID
}
}
for _, m := range p.Mapping {
m.fileX = addString(strings, m.File)
m.buildIDX = addString(strings, m.BuildID)
}
for _, l := range p.Location {
for i, ln := range l.Line {
if ln.Function != nil {
l.Line[i].functionIDX = ln.Function.ID
} else {
l.Line[i].functionIDX = 0
}
}
if l.Mapping != nil {
l.mappingIDX = l.Mapping.ID
} else {
l.mappingIDX = 0
}
}
for _, f := range p.Function {
f.nameX = addString(strings, f.Name)
f.systemNameX = addString(strings, f.SystemName)
f.filenameX = addString(strings, f.Filename)
}
p.dropFramesX = addString(strings, p.DropFrames)
p.keepFramesX = addString(strings, p.KeepFrames)
if pt := p.PeriodType; pt != nil {
pt.typeX = addString(strings, pt.Type)
pt.unitX = addString(strings, pt.Unit)
}
p.commentX = nil
for _, c := range p.Comments {
p.commentX = append(p.commentX, addString(strings, c))
}
p.defaultSampleTypeX = addString(strings, p.DefaultSampleType)
p.stringTable = make([]string, len(strings))
for s, i := range strings {
p.stringTable[i] = s
}
} | preEncode populates the unexported fields to be used by encode
(with suffix X) from the corresponding exported fields. The
exported fields are cleared up to facilitate testing. | preEncode | go | k8snetworkplumbingwg/multus-cni | vendor/github.com/google/pprof/profile/encode.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/github.com/google/pprof/profile/encode.go | Apache-2.0 |
func padStringArray(arr []string, l int) []string {
if l <= len(arr) {
return arr
}
return append(arr, make([]string, l-len(arr))...)
} | padStringArray pads arr with enough empty strings to make arr
length l when arr's length is less than l. | padStringArray | go | k8snetworkplumbingwg/multus-cni | vendor/github.com/google/pprof/profile/encode.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/github.com/google/pprof/profile/encode.go | Apache-2.0 |
func simplifyFunc(f string) string {
// Account for leading '.' on the PPC ELF v1 ABI.
funcName := strings.TrimPrefix(f, ".")
// Account for unsimplified names -- try to remove the argument list by trimming
// starting from the first '(', but skipping reserved names that have '('.
for _, ind := range bracketRx.FindAllStringSubmatchIndex(funcName, -1) {
foundReserved := false
for _, res := range reservedNames {
if funcName[ind[0]:ind[1]] == res {
foundReserved = true
break
}
}
if !foundReserved {
funcName = funcName[:ind[0]]
break
}
}
return funcName
} | simplifyFunc does some primitive simplification of function names. | simplifyFunc | go | k8snetworkplumbingwg/multus-cni | vendor/github.com/google/pprof/profile/prune.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/github.com/google/pprof/profile/prune.go | Apache-2.0 |
func (p *Profile) Compact() *Profile {
p, _ = Merge([]*Profile{p})
return p
} | Compact performs garbage collection on a profile to remove any
unreferenced fields. This is useful to reduce the size of a profile
after samples or locations have been removed. | Compact | go | k8snetworkplumbingwg/multus-cni | vendor/github.com/google/pprof/profile/merge.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/github.com/google/pprof/profile/merge.go | Apache-2.0 |
func Merge(srcs []*Profile) (*Profile, error) {
if len(srcs) == 0 {
return nil, fmt.Errorf("no profiles to merge")
}
p, err := combineHeaders(srcs)
if err != nil {
return nil, err
}
pm := &profileMerger{
p: p,
samples: make(map[sampleKey]*Sample, len(srcs[0].Sample)),
locations: make(map[locationKey]*Location, len(srcs[0].Location)),
functions: make(map[functionKey]*Function, len(srcs[0].Function)),
mappings: make(map[mappingKey]*Mapping, len(srcs[0].Mapping)),
}
for _, src := range srcs {
// Clear the profile-specific hash tables
pm.locationsByID = makeLocationIDMap(len(src.Location))
pm.functionsByID = make(map[uint64]*Function, len(src.Function))
pm.mappingsByID = make(map[uint64]mapInfo, len(src.Mapping))
if len(pm.mappings) == 0 && len(src.Mapping) > 0 {
// The Mapping list has the property that the first mapping
// represents the main binary. Take the first Mapping we see,
// otherwise the operations below will add mappings in an
// arbitrary order.
pm.mapMapping(src.Mapping[0])
}
for _, s := range src.Sample {
if !isZeroSample(s) {
pm.mapSample(s)
}
}
}
for _, s := range p.Sample {
if isZeroSample(s) {
// If there are any zero samples, re-merge the profile to GC
// them.
return Merge([]*Profile{p})
}
}
return p, nil
} | Merge merges all the profiles in profs into a single Profile.
Returns a new profile independent of the input profiles. The merged
profile is compacted to eliminate unused samples, locations,
functions and mappings. Profiles must have identical profile sample
and period types or the merge will fail. profile.Period of the
resulting profile will be the maximum of all profiles, and
profile.TimeNanos will be the earliest nonzero one. Merges are
associative with the caveat of the first profile having some
specialization in how headers are combined. There may be other
subtleties now or in the future regarding associativity. | Merge | go | k8snetworkplumbingwg/multus-cni | vendor/github.com/google/pprof/profile/merge.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/github.com/google/pprof/profile/merge.go | Apache-2.0 |
func (p *Profile) Normalize(pb *Profile) error {
if err := p.compatible(pb); err != nil {
return err
}
baseVals := make([]int64, len(p.SampleType))
for _, s := range pb.Sample {
for i, v := range s.Value {
baseVals[i] += v
}
}
srcVals := make([]int64, len(p.SampleType))
for _, s := range p.Sample {
for i, v := range s.Value {
srcVals[i] += v
}
}
normScale := make([]float64, len(baseVals))
for i := range baseVals {
if srcVals[i] == 0 {
normScale[i] = 0.0
} else {
normScale[i] = float64(baseVals[i]) / float64(srcVals[i])
}
}
p.ScaleN(normScale)
return nil
} | Normalize normalizes the source profile by multiplying each value in profile by the
ratio of the sum of the base profile's values of that sample type to the sum of the
source profile's value of that sample type. | Normalize | go | k8snetworkplumbingwg/multus-cni | vendor/github.com/google/pprof/profile/merge.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/github.com/google/pprof/profile/merge.go | Apache-2.0 |
func sortedKeys1(m map[string][]string) []string {
if len(m) == 0 {
return nil
}
keys := make([]string, 0, len(m))
for k := range m {
keys = append(keys, k)
}
sort.Strings(keys)
return keys
} | sortedKeys1 returns the sorted keys found in a string->[]string map.
Note: this is currently non-generic since github pprof runs golint,
which does not support generics. When that issue is fixed, it can
be merged with sortedKeys2 and made into a generic function. | sortedKeys1 | go | k8snetworkplumbingwg/multus-cni | vendor/github.com/google/pprof/profile/merge.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/github.com/google/pprof/profile/merge.go | Apache-2.0 |
func sortedKeys2(m map[string][]int64) []string {
if len(m) == 0 {
return nil
}
keys := make([]string, 0, len(m))
for k := range m {
keys = append(keys, k)
}
sort.Strings(keys)
return keys
} | sortedKeys2 returns the sorted keys found in a string->[]int64 map.
Note: this is currently non-generic since github pprof runs golint,
which does not support generics. When that issue is fixed, it can
be merged with sortedKeys1 and made into a generic function. | sortedKeys2 | go | k8snetworkplumbingwg/multus-cni | vendor/github.com/google/pprof/profile/merge.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/github.com/google/pprof/profile/merge.go | Apache-2.0 |
func (l *Location) key() locationKey {
key := locationKey{
addr: l.Address,
isFolded: l.IsFolded,
}
if l.Mapping != nil {
// Normalizes address to handle address space randomization.
key.addr -= l.Mapping.Start
key.mappingID = l.Mapping.ID
}
lines := make([]string, len(l.Line)*3)
for i, line := range l.Line {
if line.Function != nil {
lines[i*2] = strconv.FormatUint(line.Function.ID, 16)
}
lines[i*2+1] = strconv.FormatInt(line.Line, 16)
lines[i*2+2] = strconv.FormatInt(line.Column, 16)
}
key.lines = strings.Join(lines, "|")
return key
} | key generates locationKey to be used as a key for maps. | key | go | k8snetworkplumbingwg/multus-cni | vendor/github.com/google/pprof/profile/merge.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/github.com/google/pprof/profile/merge.go | Apache-2.0 |
func (m *Mapping) key() mappingKey {
// Normalize addresses to handle address space randomization.
// Round up to next 4K boundary to avoid minor discrepancies.
const mapsizeRounding = 0x1000
size := m.Limit - m.Start
size = size + mapsizeRounding - 1
size = size - (size % mapsizeRounding)
key := mappingKey{
size: size,
offset: m.Offset,
}
switch {
case m.BuildID != "":
key.buildIDOrFile = m.BuildID
case m.File != "":
key.buildIDOrFile = m.File
default:
// A mapping containing neither build ID nor file name is a fake mapping. A
// key with empty buildIDOrFile is used for fake mappings so that they are
// treated as the same mapping during merging.
}
return key
} | key generates encoded strings of Mapping to be used as a key for
maps. | key | go | k8snetworkplumbingwg/multus-cni | vendor/github.com/google/pprof/profile/merge.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/github.com/google/pprof/profile/merge.go | Apache-2.0 |
func (f *Function) key() functionKey {
return functionKey{
f.StartLine,
f.Name,
f.SystemName,
f.Filename,
}
} | key generates a struct to be used as a key for maps. | key | go | k8snetworkplumbingwg/multus-cni | vendor/github.com/google/pprof/profile/merge.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/github.com/google/pprof/profile/merge.go | Apache-2.0 |
func combineHeaders(srcs []*Profile) (*Profile, error) {
for _, s := range srcs[1:] {
if err := srcs[0].compatible(s); err != nil {
return nil, err
}
}
var timeNanos, durationNanos, period int64
var comments []string
seenComments := map[string]bool{}
var defaultSampleType string
for _, s := range srcs {
if timeNanos == 0 || s.TimeNanos < timeNanos {
timeNanos = s.TimeNanos
}
durationNanos += s.DurationNanos
if period == 0 || period < s.Period {
period = s.Period
}
for _, c := range s.Comments {
if seen := seenComments[c]; !seen {
comments = append(comments, c)
seenComments[c] = true
}
}
if defaultSampleType == "" {
defaultSampleType = s.DefaultSampleType
}
}
p := &Profile{
SampleType: make([]*ValueType, len(srcs[0].SampleType)),
DropFrames: srcs[0].DropFrames,
KeepFrames: srcs[0].KeepFrames,
TimeNanos: timeNanos,
DurationNanos: durationNanos,
PeriodType: srcs[0].PeriodType,
Period: period,
Comments: comments,
DefaultSampleType: defaultSampleType,
}
copy(p.SampleType, srcs[0].SampleType)
return p, nil
} | combineHeaders checks that all profiles can be merged and returns
their combined profile. | combineHeaders | go | k8snetworkplumbingwg/multus-cni | vendor/github.com/google/pprof/profile/merge.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/github.com/google/pprof/profile/merge.go | Apache-2.0 |
func (p *Profile) compatible(pb *Profile) error {
if !equalValueType(p.PeriodType, pb.PeriodType) {
return fmt.Errorf("incompatible period types %v and %v", p.PeriodType, pb.PeriodType)
}
if len(p.SampleType) != len(pb.SampleType) {
return fmt.Errorf("incompatible sample types %v and %v", p.SampleType, pb.SampleType)
}
for i := range p.SampleType {
if !equalValueType(p.SampleType[i], pb.SampleType[i]) {
return fmt.Errorf("incompatible sample types %v and %v", p.SampleType, pb.SampleType)
}
}
return nil
} | compatible determines if two profiles can be compared/merged.
returns nil if the profiles are compatible; otherwise an error with
details on the incompatibility. | compatible | go | k8snetworkplumbingwg/multus-cni | vendor/github.com/google/pprof/profile/merge.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/github.com/google/pprof/profile/merge.go | Apache-2.0 |
func equalValueType(st1, st2 *ValueType) bool {
return st1.Type == st2.Type && st1.Unit == st2.Unit
} | equalValueType returns true if the two value types are semantically
equal. It ignores the internal fields used during encode/decode. | equalValueType | go | k8snetworkplumbingwg/multus-cni | vendor/github.com/google/pprof/profile/merge.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/github.com/google/pprof/profile/merge.go | Apache-2.0 |
func CompatibilizeSampleTypes(ps []*Profile) error {
sTypes := commonSampleTypes(ps)
if len(sTypes) == 0 {
return fmt.Errorf("profiles have empty common sample type list")
}
for _, p := range ps {
if err := compatibilizeSampleTypes(p, sTypes); err != nil {
return err
}
}
return nil
} | CompatibilizeSampleTypes makes profiles compatible to be compared/merged. It
keeps sample types that appear in all profiles only and drops/reorders the
sample types as necessary.
In the case of sample types order is not the same for given profiles the
order is derived from the first profile.
Profiles are modified in-place.
It returns an error if the sample type's intersection is empty. | CompatibilizeSampleTypes | go | k8snetworkplumbingwg/multus-cni | vendor/github.com/google/pprof/profile/merge.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/github.com/google/pprof/profile/merge.go | Apache-2.0 |
func commonSampleTypes(ps []*Profile) []string {
if len(ps) == 0 {
return nil
}
sTypes := map[string]int{}
for _, p := range ps {
for _, st := range p.SampleType {
sTypes[st.Type]++
}
}
var res []string
for _, st := range ps[0].SampleType {
if sTypes[st.Type] == len(ps) {
res = append(res, st.Type)
}
}
return res
} | commonSampleTypes returns sample types that appear in all profiles in the
order how they ordered in the first profile. | commonSampleTypes | go | k8snetworkplumbingwg/multus-cni | vendor/github.com/google/pprof/profile/merge.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/github.com/google/pprof/profile/merge.go | Apache-2.0 |
func compatibilizeSampleTypes(p *Profile, sTypes []string) error {
if len(sTypes) == 0 {
return fmt.Errorf("sample type list is empty")
}
defaultSampleType := sTypes[0]
reMap, needToModify := make([]int, len(sTypes)), false
for i, st := range sTypes {
if st == p.DefaultSampleType {
defaultSampleType = p.DefaultSampleType
}
idx := searchValueType(p.SampleType, st)
if idx < 0 {
return fmt.Errorf("%q sample type is not found in profile", st)
}
reMap[i] = idx
if idx != i {
needToModify = true
}
}
if !needToModify && len(sTypes) == len(p.SampleType) {
return nil
}
p.DefaultSampleType = defaultSampleType
oldSampleTypes := p.SampleType
p.SampleType = make([]*ValueType, len(sTypes))
for i, idx := range reMap {
p.SampleType[i] = oldSampleTypes[idx]
}
values := make([]int64, len(sTypes))
for _, s := range p.Sample {
for i, idx := range reMap {
values[i] = s.Value[idx]
}
s.Value = s.Value[:len(values)]
copy(s.Value, values)
}
return nil
} | compatibilizeSampleTypes drops sample types that are not present in sTypes
list and reorder them if needed.
It sets DefaultSampleType to sType[0] if it is not in sType list.
It assumes that all sample types from the sTypes list are present in the
given profile otherwise it returns an error. | compatibilizeSampleTypes | go | k8snetworkplumbingwg/multus-cni | vendor/github.com/google/pprof/profile/merge.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/github.com/google/pprof/profile/merge.go | Apache-2.0 |
func (p *Profile) FilterSamplesByName(focus, ignore, hide, show *regexp.Regexp) (fm, im, hm, hnm bool) {
if focus == nil && ignore == nil && hide == nil && show == nil {
fm = true // Missing focus implies a match
return
}
focusOrIgnore := make(map[uint64]bool)
hidden := make(map[uint64]bool)
for _, l := range p.Location {
if ignore != nil && l.matchesName(ignore) {
im = true
focusOrIgnore[l.ID] = false
} else if focus == nil || l.matchesName(focus) {
fm = true
focusOrIgnore[l.ID] = true
}
if hide != nil && l.matchesName(hide) {
hm = true
l.Line = l.unmatchedLines(hide)
if len(l.Line) == 0 {
hidden[l.ID] = true
}
}
if show != nil {
l.Line = l.matchedLines(show)
if len(l.Line) == 0 {
hidden[l.ID] = true
} else {
hnm = true
}
}
}
s := make([]*Sample, 0, len(p.Sample))
for _, sample := range p.Sample {
if focusedAndNotIgnored(sample.Location, focusOrIgnore) {
if len(hidden) > 0 {
var locs []*Location
for _, loc := range sample.Location {
if !hidden[loc.ID] {
locs = append(locs, loc)
}
}
if len(locs) == 0 {
// Remove sample with no locations (by not adding it to s).
continue
}
sample.Location = locs
}
s = append(s, sample)
}
}
p.Sample = s
return
} | FilterSamplesByName filters the samples in a profile and only keeps
samples where at least one frame matches focus but none match ignore.
Returns true is the corresponding regexp matched at least one sample. | FilterSamplesByName | go | k8snetworkplumbingwg/multus-cni | vendor/github.com/google/pprof/profile/filter.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/github.com/google/pprof/profile/filter.go | Apache-2.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.