manager.go 10 KB

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