1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282
|
// -*- Mode: Go; indent-tabs-mode: t -*-
/*
* Copyright (C) 2022 Canonical Ltd
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 3 as
* published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
package cgroup
import (
"context"
"fmt"
"path/filepath"
"sync"
"github.com/snapcore/snapd/logger"
"github.com/snapcore/snapd/osutil"
"github.com/snapcore/snapd/osutil/inotify"
)
// inotifyWatcher manages the inotify watcher, allowing to have a single watch descriptor open
type inotifyWatcher struct {
// The watch object
wd *inotify.Watcher
wdErr error
// This is used to ensure that the watcher goroutine is launched only once
doOnce sync.Once
// Context
ctx context.Context
// This channel is used to add a new CGroup that has to be checked
addWatchChan chan *groupToWatch
// Contains the list of groups to monitor, to detect when they have been deleted
groupList []*groupToWatch
// Contains the list of paths being monitored by the inotify watcher.
// The paths monitored are both the actual leaf path and the parent
// directory. See discussion in addWatch for details on why the parent
// needs to be tracked as well.
pathList map[string]uint
done context.CancelFunc
doneChan chan struct{}
// observer callback to facilitate testing, called when a watch is
// added, or a folder from a watched group is removed, or the whole
// group is empty and thus notified about
observeMonitorCb func(w *inotifyWatcher, name string)
}
// Contains the data corresponding to a CGroup that must be watched to detect
// when it is destroyed
type groupToWatch struct {
// This is the CGroup identifier
name string
// This contains a hash map of folders to monitor. When all of them have been
// deleted, the CGroup has been destroyed and there are no processes running
folders map[string]struct{}
// This channel is used to notify to the requester that this CGroup has been
// destroyed. The watcher writes the CGroup identifier on it; this way, the
// same channel can be shared to monitor several CGroups.
channel chan<- string
}
var currentWatcher *inotifyWatcher = newInotifyWatcher(context.Background())
func newInotifyWatcher(ctx context.Context) *inotifyWatcher {
ctx, cancel := context.WithCancel(ctx)
return &inotifyWatcher{
ctx: ctx,
pathList: make(map[string]uint),
addWatchChan: make(chan *groupToWatch),
doneChan: make(chan struct{}),
done: cancel,
}
}
func (gtw *groupToWatch) sendClosedNotification() {
// Use a goroutine to avoid getting blocked on the channel
go func() {
defer func() {
if err := recover(); err != nil {
logger.Noticef("cannot send closed notification for %s", gtw.name)
}
}()
gtw.channel <- gtw.name
}()
}
// Close stops the watcher and waits for it to finish.
func (iw *inotifyWatcher) Close() {
iw.done()
<-iw.doneChan
for p := range iw.pathList {
iw.removePath(p)
}
iw.wd.Close()
}
func (iw *inotifyWatcher) addWatch(newWatch *groupToWatch) {
for fullPath := range newWatch.folders {
// It's not possible to use inotify.InDeleteSelf in /sys/fs because it
// isn't triggered, so we must monitor the parent folder and use InDelete
basePath := filepath.Dir(fullPath)
if _, exists := iw.pathList[basePath]; !exists {
iw.pathList[basePath] = 0
if err := iw.wd.AddWatch(basePath, inotify.InDelete); err != nil {
// TODO propagate the error back to the caller
logger.Noticef("cannot add watch %v", err)
delete(iw.pathList, basePath)
continue
}
}
// bump for the base path, since we're relying on a watch being added there
iw.pathList[basePath]++
// bump on the actual path
iw.pathList[fullPath]++
if !osutil.FileExists(fullPath) {
// the path is gone by now
delete(newWatch.folders, fullPath)
iw.removePath(fullPath)
}
}
if len(newWatch.folders) == 0 {
newWatch.sendClosedNotification()
} else {
iw.groupList = append(iw.groupList, newWatch)
}
iw.notifyObserver(newWatch)
logger.Debugf("watches after add: %v", iw.pathList)
}
func (iw *inotifyWatcher) removePath(fullPath string) {
cnt, ok := iw.pathList[fullPath]
if !ok {
// path we are not watching
return
}
parent := filepath.Dir(fullPath)
cnt--
// we are also keeping references to the parent, see
// addWatch about the details
iw.pathList[parent]--
if cnt > 0 {
// still references to this path
iw.pathList[fullPath] = cnt
return
}
logger.Debugf("removing watch for %s", fullPath)
delete(iw.pathList, fullPath)
// deal with parent now
if iw.pathList[parent] == 0 {
if err := iw.wd.RemoveWatch(parent); err != nil {
logger.Noticef("cannot remove watch: %v", err)
}
delete(iw.pathList, parent)
}
logger.Debugf("watches after remove: %v", iw.pathList)
}
// processDeletedPath checks if the received path corresponds to the passed
// CGroup, removing it from the list of folders being watched in that CGroup if
// needed. It returns true if there remain folders to be monitored in that CGroup,
// or false if all the folders of that CGroup have been deleted.
func (iw *inotifyWatcher) processDeletedPath(watch *groupToWatch, deletedPath string) (keepWatching bool) {
if _, ok := watch.folders[deletedPath]; ok {
// if the folder name is in the list of folders to monitor, decrement the
// parent's usage counter, and remove it from the list of folders to watch
// in this CGroup (by not adding it to tmpFolders)
iw.removePath(deletedPath)
delete(watch.folders, deletedPath)
iw.notifyObserver(watch)
}
if len(watch.folders) == 0 {
// if all the files/folders of this CGroup have been deleted, notify the
// client that it is done.
watch.sendClosedNotification()
iw.notifyObserver(watch)
return false
}
return true
}
func (iw *inotifyWatcher) notifyObserver(w *groupToWatch) {
if iw.observeMonitorCb != nil {
iw.observeMonitorCb(iw, w.name)
}
}
func (iw *inotifyWatcher) watcherMainLoop() {
for {
select {
case event := <-iw.wd.Event:
if event.Mask&inotify.InDelete == 0 {
continue
}
var newGroupList []*groupToWatch
for _, watch := range iw.groupList {
if iw.processDeletedPath(watch, event.Name) {
newGroupList = append(newGroupList, watch)
}
}
iw.groupList = newGroupList
case newWatch := <-iw.addWatchChan:
iw.addWatch(newWatch)
case <-iw.ctx.Done():
close(iw.doneChan)
return
}
}
}
// MonitorDelete monitors the specified paths for deletion.
// Once all of them have been deleted, it pushes the specified name through the channel.
func (iw *inotifyWatcher) monitorDelete(folders []string, name string, channel chan<- string) (err error) {
iw.doOnce.Do(func() {
iw.wd, err = inotify.NewWatcher()
if err != nil {
iw.wdErr = err
return
}
go iw.watcherMainLoop()
})
if iw.wdErr != nil {
return fmt.Errorf("cannot initialize inotify: %w", iw.wdErr)
}
foldersMap := make(map[string]struct{}, len(folders))
for _, f := range folders {
foldersMap[f] = struct{}{}
}
iw.addWatchChan <- &groupToWatch{
name: name,
folders: foldersMap,
channel: channel,
}
return nil
}
// MonitorSnapEnded monitors the running instances of a snap. Once all
// instances of the snap have stopped, its name is pushed through the supplied
// channel. This allows the caller to use the same channel to monitor several snaps.
func MonitorSnapEnded(snapName string, channel chan<- string) error {
options := InstancePathsOptions{
ReturnCGroupPath: true,
}
paths, err := InstancePathsOfSnap(snapName, options)
if err != nil {
return err
}
logger.Debugf("snap %s has %d processes: %v", snapName, len(paths), paths)
return currentWatcher.monitorDelete(paths, snapName, channel)
}
|