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