github.com/rumpl/bof@v23.0.0-rc.2+incompatible/plugin/manager.go (about)

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