manager.go 10.0 KB

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