manager.go 10 KB

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