github.com/jfrazelle/docker@v1.1.2-0.20210712172922-bf78e25fe508/plugin/manager.go (about) 1 package plugin // import "github.com/docker/docker/plugin" 2 3 import ( 4 "context" 5 "encoding/json" 6 "io" 7 "io/ioutil" 8 "os" 9 "path/filepath" 10 "reflect" 11 "regexp" 12 "sort" 13 "strings" 14 "sync" 15 16 "github.com/containerd/containerd/content" 17 "github.com/containerd/containerd/content/local" 18 "github.com/docker/distribution/reference" 19 "github.com/docker/docker/api/types" 20 "github.com/docker/docker/pkg/authorization" 21 "github.com/docker/docker/pkg/ioutils" 22 "github.com/docker/docker/pkg/pubsub" 23 "github.com/docker/docker/pkg/system" 24 v2 "github.com/docker/docker/plugin/v2" 25 "github.com/docker/docker/registry" 26 digest "github.com/opencontainers/go-digest" 27 specs "github.com/opencontainers/runtime-spec/specs-go" 28 "github.com/pkg/errors" 29 "github.com/sirupsen/logrus" 30 ) 31 32 const configFileName = "config.json" 33 const rootFSFileName = "rootfs" 34 35 var validFullID = regexp.MustCompile(`^([a-f0-9]{64})$`) 36 37 // Executor is the interface that the plugin manager uses to interact with for starting/stopping plugins 38 type Executor interface { 39 Create(id string, spec specs.Spec, stdout, stderr io.WriteCloser) error 40 IsRunning(id string) (bool, error) 41 Restore(id string, stdout, stderr io.WriteCloser) (alive bool, err error) 42 Signal(id string, signal int) error 43 } 44 45 func (pm *Manager) restorePlugin(p *v2.Plugin, c *controller) error { 46 if p.IsEnabled() { 47 return pm.restore(p, c) 48 } 49 return nil 50 } 51 52 type eventLogger func(id, name, action string) 53 54 // ManagerConfig defines configuration needed to start new manager. 55 type ManagerConfig struct { 56 Store *Store // remove 57 RegistryService registry.Service 58 LiveRestoreEnabled bool // TODO: remove 59 LogPluginEvent eventLogger 60 Root string 61 ExecRoot string 62 CreateExecutor ExecutorCreator 63 AuthzMiddleware *authorization.Middleware 64 } 65 66 // ExecutorCreator is used in the manager config to pass in an `Executor` 67 type ExecutorCreator func(*Manager) (Executor, error) 68 69 // Manager controls the plugin subsystem. 70 type Manager struct { 71 config ManagerConfig 72 mu sync.RWMutex // protects cMap 73 muGC sync.RWMutex // protects blobstore deletions 74 cMap map[*v2.Plugin]*controller 75 blobStore content.Store 76 publisher *pubsub.Publisher 77 executor Executor 78 } 79 80 // controller represents the manager's control on a plugin. 81 type controller struct { 82 restart bool 83 exitChan chan bool 84 timeoutInSecs int 85 } 86 87 // pluginRegistryService ensures that all resolved repositories 88 // are of the plugin class. 89 type pluginRegistryService struct { 90 registry.Service 91 } 92 93 func (s pluginRegistryService) ResolveRepository(name reference.Named) (repoInfo *registry.RepositoryInfo, err error) { 94 repoInfo, err = s.Service.ResolveRepository(name) 95 if repoInfo != nil { 96 repoInfo.Class = "plugin" 97 } 98 return 99 } 100 101 // NewManager returns a new plugin manager. 102 func NewManager(config ManagerConfig) (*Manager, error) { 103 if config.RegistryService != nil { 104 config.RegistryService = pluginRegistryService{config.RegistryService} 105 } 106 manager := &Manager{ 107 config: config, 108 } 109 for _, dirName := range []string{manager.config.Root, manager.config.ExecRoot, manager.tmpDir()} { 110 if err := os.MkdirAll(dirName, 0700); err != nil { 111 return nil, errors.Wrapf(err, "failed to mkdir %v", dirName) 112 } 113 } 114 var err error 115 manager.executor, err = config.CreateExecutor(manager) 116 if err != nil { 117 return nil, err 118 } 119 120 manager.blobStore, err = local.NewStore(filepath.Join(manager.config.Root, "storage")) 121 if err != nil { 122 return nil, errors.Wrap(err, "error creating plugin blob store") 123 } 124 125 manager.cMap = make(map[*v2.Plugin]*controller) 126 if err := manager.reload(); err != nil { 127 return nil, errors.Wrap(err, "failed to restore plugins") 128 } 129 130 manager.publisher = pubsub.NewPublisher(0, 0) 131 return manager, nil 132 } 133 134 func (pm *Manager) tmpDir() string { 135 return filepath.Join(pm.config.Root, "tmp") 136 } 137 138 // HandleExitEvent is called when the executor receives the exit event 139 // In the future we may change this, but for now all we care about is the exit event. 140 func (pm *Manager) HandleExitEvent(id string) error { 141 p, err := pm.config.Store.GetV2Plugin(id) 142 if err != nil { 143 return err 144 } 145 146 if err := os.RemoveAll(filepath.Join(pm.config.ExecRoot, id)); err != nil { 147 logrus.WithError(err).WithField("id", id).Error("Could not remove plugin bundle dir") 148 } 149 150 pm.mu.RLock() 151 c := pm.cMap[p] 152 if c.exitChan != nil { 153 close(c.exitChan) 154 c.exitChan = nil // ignore duplicate events (containerd issue #2299) 155 } 156 restart := c.restart 157 pm.mu.RUnlock() 158 159 if restart { 160 pm.enable(p, c, true) 161 } else if err := recursiveUnmount(filepath.Join(pm.config.Root, id)); err != nil { 162 return errors.Wrap(err, "error cleaning up plugin mounts") 163 } 164 return nil 165 } 166 167 func handleLoadError(err error, id string) { 168 if err == nil { 169 return 170 } 171 logger := logrus.WithError(err).WithField("id", id) 172 if errors.Is(err, os.ErrNotExist) { 173 // Likely some error while removing on an older version of docker 174 logger.Warn("missing plugin config, skipping: this may be caused due to a failed remove and requires manual cleanup.") 175 return 176 } 177 logger.Error("error loading plugin, skipping") 178 } 179 180 func (pm *Manager) reload() error { // todo: restore 181 dir, err := ioutil.ReadDir(pm.config.Root) 182 if err != nil { 183 return errors.Wrapf(err, "failed to read %v", pm.config.Root) 184 } 185 plugins := make(map[string]*v2.Plugin) 186 for _, v := range dir { 187 if validFullID.MatchString(v.Name()) { 188 p, err := pm.loadPlugin(v.Name()) 189 if err != nil { 190 handleLoadError(err, v.Name()) 191 continue 192 } 193 plugins[p.GetID()] = p 194 } else { 195 if validFullID.MatchString(strings.TrimSuffix(v.Name(), "-removing")) { 196 // There was likely some error while removing this plugin, let's try to remove again here 197 if err := system.EnsureRemoveAll(v.Name()); err != nil { 198 logrus.WithError(err).WithField("id", v.Name()).Warn("error while attempting to clean up previously removed plugin") 199 } 200 } 201 } 202 } 203 204 pm.config.Store.SetAll(plugins) 205 206 var wg sync.WaitGroup 207 wg.Add(len(plugins)) 208 for _, p := range plugins { 209 c := &controller{exitChan: make(chan bool)} 210 pm.mu.Lock() 211 pm.cMap[p] = c 212 pm.mu.Unlock() 213 214 go func(p *v2.Plugin) { 215 defer wg.Done() 216 if err := pm.restorePlugin(p, c); err != nil { 217 logrus.WithError(err).WithField("id", p.GetID()).Error("Failed to restore plugin") 218 return 219 } 220 221 if p.Rootfs != "" { 222 p.Rootfs = filepath.Join(pm.config.Root, p.PluginObj.ID, "rootfs") 223 } 224 225 // We should only enable rootfs propagation for certain plugin types that need it. 226 for _, typ := range p.PluginObj.Config.Interface.Types { 227 if (typ.Capability == "volumedriver" || typ.Capability == "graphdriver") && typ.Prefix == "docker" && strings.HasPrefix(typ.Version, "1.") { 228 if p.PluginObj.Config.PropagatedMount != "" { 229 propRoot := filepath.Join(filepath.Dir(p.Rootfs), "propagated-mount") 230 231 // check if we need to migrate an older propagated mount from before 232 // these mounts were stored outside the plugin rootfs 233 if _, err := os.Stat(propRoot); os.IsNotExist(err) { 234 rootfsProp := filepath.Join(p.Rootfs, p.PluginObj.Config.PropagatedMount) 235 if _, err := os.Stat(rootfsProp); err == nil { 236 if err := os.Rename(rootfsProp, propRoot); err != nil { 237 logrus.WithError(err).WithField("dir", propRoot).Error("error migrating propagated mount storage") 238 } 239 } 240 } 241 242 if err := os.MkdirAll(propRoot, 0755); err != nil { 243 logrus.Errorf("failed to create PropagatedMount directory at %s: %v", propRoot, err) 244 } 245 } 246 } 247 } 248 249 pm.save(p) 250 requiresManualRestore := !pm.config.LiveRestoreEnabled && p.IsEnabled() 251 252 if requiresManualRestore { 253 // if liveRestore is not enabled, the plugin will be stopped now so we should enable it 254 if err := pm.enable(p, c, true); err != nil { 255 logrus.WithError(err).WithField("id", p.GetID()).Error("failed to enable plugin") 256 } 257 } 258 }(p) 259 } 260 wg.Wait() 261 return nil 262 } 263 264 // Get looks up the requested plugin in the store. 265 func (pm *Manager) Get(idOrName string) (*v2.Plugin, error) { 266 return pm.config.Store.GetV2Plugin(idOrName) 267 } 268 269 func (pm *Manager) loadPlugin(id string) (*v2.Plugin, error) { 270 p := filepath.Join(pm.config.Root, id, configFileName) 271 dt, err := ioutil.ReadFile(p) 272 if err != nil { 273 return nil, errors.Wrapf(err, "error reading %v", p) 274 } 275 var plugin v2.Plugin 276 if err := json.Unmarshal(dt, &plugin); err != nil { 277 return nil, errors.Wrapf(err, "error decoding %v", p) 278 } 279 return &plugin, nil 280 } 281 282 func (pm *Manager) save(p *v2.Plugin) error { 283 pluginJSON, err := json.Marshal(p) 284 if err != nil { 285 return errors.Wrap(err, "failed to marshal plugin json") 286 } 287 if err := ioutils.AtomicWriteFile(filepath.Join(pm.config.Root, p.GetID(), configFileName), pluginJSON, 0600); err != nil { 288 return errors.Wrap(err, "failed to write atomically plugin json") 289 } 290 return nil 291 } 292 293 // GC cleans up unreferenced blobs. This is recommended to run in a goroutine 294 func (pm *Manager) GC() { 295 pm.muGC.Lock() 296 defer pm.muGC.Unlock() 297 298 used := make(map[digest.Digest]struct{}) 299 for _, p := range pm.config.Store.GetAll() { 300 used[p.Config] = struct{}{} 301 for _, b := range p.Blobsums { 302 used[b] = struct{}{} 303 } 304 } 305 306 ctx := context.TODO() 307 pm.blobStore.Walk(ctx, func(info content.Info) error { 308 _, ok := used[info.Digest] 309 if ok { 310 return nil 311 } 312 313 return pm.blobStore.Delete(ctx, info.Digest) 314 }) 315 } 316 317 type logHook struct{ id string } 318 319 func (logHook) Levels() []logrus.Level { 320 return logrus.AllLevels 321 } 322 323 func (l logHook) Fire(entry *logrus.Entry) error { 324 entry.Data = logrus.Fields{"plugin": l.id} 325 return nil 326 } 327 328 func makeLoggerStreams(id string) (stdout, stderr io.WriteCloser) { 329 logger := logrus.New() 330 logger.Hooks.Add(logHook{id}) 331 return logger.WriterLevel(logrus.InfoLevel), logger.WriterLevel(logrus.ErrorLevel) 332 } 333 334 func validatePrivileges(requiredPrivileges, privileges types.PluginPrivileges) error { 335 if !isEqual(requiredPrivileges, privileges, isEqualPrivilege) { 336 return errors.New("incorrect privileges") 337 } 338 339 return nil 340 } 341 342 func isEqual(arrOne, arrOther types.PluginPrivileges, compare func(x, y types.PluginPrivilege) bool) bool { 343 if len(arrOne) != len(arrOther) { 344 return false 345 } 346 347 sort.Sort(arrOne) 348 sort.Sort(arrOther) 349 350 for i := 1; i < arrOne.Len(); i++ { 351 if !compare(arrOne[i], arrOther[i]) { 352 return false 353 } 354 } 355 356 return true 357 } 358 359 func isEqualPrivilege(a, b types.PluginPrivilege) bool { 360 if a.Name != b.Name { 361 return false 362 } 363 364 return reflect.DeepEqual(a.Value, b.Value) 365 }