manager_linux.go 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349
  1. package plugin // import "github.com/docker/docker/plugin"
  2. import (
  3. "context"
  4. "encoding/json"
  5. "net"
  6. "os"
  7. "path/filepath"
  8. "time"
  9. "github.com/containerd/containerd/content"
  10. "github.com/containerd/log"
  11. "github.com/docker/docker/api/types"
  12. "github.com/docker/docker/daemon/initlayer"
  13. "github.com/docker/docker/errdefs"
  14. "github.com/docker/docker/pkg/idtools"
  15. "github.com/docker/docker/pkg/plugins"
  16. "github.com/docker/docker/pkg/stringid"
  17. v2 "github.com/docker/docker/plugin/v2"
  18. "github.com/moby/sys/mount"
  19. "github.com/opencontainers/go-digest"
  20. ocispec "github.com/opencontainers/image-spec/specs-go/v1"
  21. "github.com/pkg/errors"
  22. "golang.org/x/sys/unix"
  23. )
  24. func (pm *Manager) enable(p *v2.Plugin, c *controller, force bool) error {
  25. p.Rootfs = filepath.Join(pm.config.Root, p.PluginObj.ID, "rootfs")
  26. if p.IsEnabled() && !force {
  27. return errors.Wrap(enabledError(p.Name()), "plugin already enabled")
  28. }
  29. spec, err := p.InitSpec(pm.config.ExecRoot)
  30. if err != nil {
  31. return err
  32. }
  33. c.restart = true
  34. c.exitChan = make(chan bool)
  35. pm.mu.Lock()
  36. pm.cMap[p] = c
  37. pm.mu.Unlock()
  38. var propRoot string
  39. if p.PluginObj.Config.PropagatedMount != "" {
  40. propRoot = filepath.Join(filepath.Dir(p.Rootfs), "propagated-mount")
  41. if err := os.MkdirAll(propRoot, 0o755); err != nil {
  42. log.G(context.TODO()).Errorf("failed to create PropagatedMount directory at %s: %v", propRoot, err)
  43. }
  44. if err := mount.MakeRShared(propRoot); err != nil {
  45. return errors.Wrap(err, "error setting up propagated mount dir")
  46. }
  47. }
  48. rootFS := filepath.Join(pm.config.Root, p.PluginObj.ID, rootFSFileName)
  49. if err := initlayer.Setup(rootFS, idtools.Identity{UID: 0, GID: 0}); err != nil {
  50. return errors.WithStack(err)
  51. }
  52. stdout, stderr := makeLoggerStreams(p.GetID())
  53. if err := pm.executor.Create(p.GetID(), *spec, stdout, stderr); err != nil {
  54. if p.PluginObj.Config.PropagatedMount != "" {
  55. if err := mount.Unmount(propRoot); err != nil {
  56. log.G(context.TODO()).WithField("plugin", p.Name()).WithError(err).Warn("Failed to unmount vplugin propagated mount root")
  57. }
  58. }
  59. return errors.WithStack(err)
  60. }
  61. return pm.pluginPostStart(p, c)
  62. }
  63. func (pm *Manager) pluginPostStart(p *v2.Plugin, c *controller) error {
  64. sockAddr := filepath.Join(pm.config.ExecRoot, p.GetID(), p.GetSocket())
  65. p.SetTimeout(time.Duration(c.timeoutInSecs) * time.Second)
  66. addr := &net.UnixAddr{Net: "unix", Name: sockAddr}
  67. p.SetAddr(addr)
  68. if p.Protocol() == plugins.ProtocolSchemeHTTPV1 {
  69. client, err := plugins.NewClientWithTimeout(addr.Network()+"://"+addr.String(), nil, p.Timeout())
  70. if err != nil {
  71. c.restart = false
  72. shutdownPlugin(p, c.exitChan, pm.executor)
  73. return errors.WithStack(err)
  74. }
  75. p.SetPClient(client)
  76. }
  77. // Initial sleep before net Dial to allow plugin to listen on socket.
  78. time.Sleep(500 * time.Millisecond)
  79. maxRetries := 3
  80. var retries int
  81. for {
  82. // net dial into the unix socket to see if someone's listening.
  83. conn, err := net.Dial("unix", sockAddr)
  84. if err == nil {
  85. conn.Close()
  86. break
  87. }
  88. time.Sleep(3 * time.Second)
  89. retries++
  90. if retries > maxRetries {
  91. log.G(context.TODO()).Debugf("error net dialing plugin: %v", err)
  92. c.restart = false
  93. // While restoring plugins, we need to explicitly set the state to disabled
  94. pm.config.Store.SetState(p, false)
  95. shutdownPlugin(p, c.exitChan, pm.executor)
  96. return err
  97. }
  98. }
  99. pm.config.Store.SetState(p, true)
  100. pm.config.Store.CallHandler(p)
  101. return pm.save(p)
  102. }
  103. func (pm *Manager) restore(p *v2.Plugin, c *controller) error {
  104. stdout, stderr := makeLoggerStreams(p.GetID())
  105. alive, err := pm.executor.Restore(p.GetID(), stdout, stderr)
  106. if err != nil {
  107. return err
  108. }
  109. if pm.config.LiveRestoreEnabled {
  110. if !alive {
  111. return pm.enable(p, c, true)
  112. }
  113. c.exitChan = make(chan bool)
  114. c.restart = true
  115. pm.mu.Lock()
  116. pm.cMap[p] = c
  117. pm.mu.Unlock()
  118. return pm.pluginPostStart(p, c)
  119. }
  120. if alive {
  121. // TODO(@cpuguy83): Should we always just re-attach to the running plugin instead of doing this?
  122. c.restart = false
  123. shutdownPlugin(p, c.exitChan, pm.executor)
  124. }
  125. return nil
  126. }
  127. const shutdownTimeout = 10 * time.Second
  128. func shutdownPlugin(p *v2.Plugin, ec chan bool, executor Executor) {
  129. pluginID := p.GetID()
  130. if err := executor.Signal(pluginID, unix.SIGTERM); err != nil {
  131. log.G(context.TODO()).Errorf("Sending SIGTERM to plugin failed with error: %v", err)
  132. return
  133. }
  134. timeout := time.NewTimer(shutdownTimeout)
  135. defer timeout.Stop()
  136. select {
  137. case <-ec:
  138. log.G(context.TODO()).Debug("Clean shutdown of plugin")
  139. case <-timeout.C:
  140. log.G(context.TODO()).Debug("Force shutdown plugin")
  141. if err := executor.Signal(pluginID, unix.SIGKILL); err != nil {
  142. log.G(context.TODO()).Errorf("Sending SIGKILL to plugin failed with error: %v", err)
  143. }
  144. timeout.Reset(shutdownTimeout)
  145. select {
  146. case <-ec:
  147. log.G(context.TODO()).Debug("SIGKILL plugin shutdown")
  148. case <-timeout.C:
  149. log.G(context.TODO()).WithField("plugin", p.Name).Warn("Force shutdown plugin FAILED")
  150. }
  151. }
  152. }
  153. func (pm *Manager) disable(p *v2.Plugin, c *controller) error {
  154. if !p.IsEnabled() {
  155. return errors.Wrap(errDisabled(p.Name()), "plugin is already disabled")
  156. }
  157. c.restart = false
  158. shutdownPlugin(p, c.exitChan, pm.executor)
  159. pm.config.Store.SetState(p, false)
  160. return pm.save(p)
  161. }
  162. // Shutdown stops all plugins and called during daemon shutdown.
  163. func (pm *Manager) Shutdown() {
  164. plugins := pm.config.Store.GetAll()
  165. for _, p := range plugins {
  166. pm.mu.RLock()
  167. c := pm.cMap[p]
  168. pm.mu.RUnlock()
  169. if pm.config.LiveRestoreEnabled && p.IsEnabled() {
  170. log.G(context.TODO()).Debug("Plugin active when liveRestore is set, skipping shutdown")
  171. continue
  172. }
  173. if pm.executor != nil && p.IsEnabled() {
  174. c.restart = false
  175. shutdownPlugin(p, c.exitChan, pm.executor)
  176. }
  177. }
  178. if err := mount.RecursiveUnmount(pm.config.Root); err != nil {
  179. log.G(context.TODO()).WithError(err).Warn("error cleaning up plugin mounts")
  180. }
  181. }
  182. func (pm *Manager) upgradePlugin(p *v2.Plugin, configDigest, manifestDigest digest.Digest, blobsums []digest.Digest, tmpRootFSDir string, privileges *types.PluginPrivileges) (err error) {
  183. config, err := pm.setupNewPlugin(configDigest, privileges)
  184. if err != nil {
  185. return err
  186. }
  187. pdir := filepath.Join(pm.config.Root, p.PluginObj.ID)
  188. orig := filepath.Join(pdir, "rootfs")
  189. // Make sure nothing is mounted
  190. // This could happen if the plugin was disabled with `-f` with active mounts.
  191. // If there is anything in `orig` is still mounted, this should error out.
  192. if err := mount.RecursiveUnmount(orig); err != nil {
  193. return errdefs.System(err)
  194. }
  195. backup := orig + "-old"
  196. if err := os.Rename(orig, backup); err != nil {
  197. return errors.Wrap(errdefs.System(err), "error backing up plugin data before upgrade")
  198. }
  199. defer func() {
  200. if err != nil {
  201. if rmErr := os.RemoveAll(orig); rmErr != nil {
  202. log.G(context.TODO()).WithError(rmErr).WithField("dir", backup).Error("error cleaning up after failed upgrade")
  203. return
  204. }
  205. if mvErr := os.Rename(backup, orig); mvErr != nil {
  206. err = errors.Wrap(mvErr, "error restoring old plugin root on upgrade failure")
  207. }
  208. if rmErr := os.RemoveAll(tmpRootFSDir); rmErr != nil && !os.IsNotExist(rmErr) {
  209. log.G(context.TODO()).WithError(rmErr).WithField("plugin", p.Name()).Errorf("error cleaning up plugin upgrade dir: %s", tmpRootFSDir)
  210. }
  211. } else {
  212. if rmErr := os.RemoveAll(backup); rmErr != nil {
  213. log.G(context.TODO()).WithError(rmErr).WithField("dir", backup).Error("error cleaning up old plugin root after successful upgrade")
  214. }
  215. p.Config = configDigest
  216. p.Blobsums = blobsums
  217. }
  218. }()
  219. if err := os.Rename(tmpRootFSDir, orig); err != nil {
  220. return errors.Wrap(errdefs.System(err), "error upgrading")
  221. }
  222. p.PluginObj.Config = config
  223. p.Manifest = manifestDigest
  224. err = pm.save(p)
  225. return errors.Wrap(err, "error saving upgraded plugin config")
  226. }
  227. func (pm *Manager) setupNewPlugin(configDigest digest.Digest, privileges *types.PluginPrivileges) (types.PluginConfig, error) {
  228. configRA, err := pm.blobStore.ReaderAt(context.TODO(), ocispec.Descriptor{Digest: configDigest})
  229. if err != nil {
  230. return types.PluginConfig{}, err
  231. }
  232. defer configRA.Close()
  233. configR := content.NewReader(configRA)
  234. var config types.PluginConfig
  235. dec := json.NewDecoder(configR)
  236. if err := dec.Decode(&config); err != nil {
  237. return types.PluginConfig{}, errors.Wrapf(err, "failed to parse config")
  238. }
  239. if dec.More() {
  240. return types.PluginConfig{}, errors.New("invalid config json")
  241. }
  242. requiredPrivileges := computePrivileges(config)
  243. if privileges != nil {
  244. if err := validatePrivileges(requiredPrivileges, *privileges); err != nil {
  245. return types.PluginConfig{}, err
  246. }
  247. }
  248. return config, nil
  249. }
  250. // createPlugin creates a new plugin. take lock before calling.
  251. func (pm *Manager) createPlugin(name string, configDigest, manifestDigest digest.Digest, blobsums []digest.Digest, rootFSDir string, privileges *types.PluginPrivileges, opts ...CreateOpt) (p *v2.Plugin, err error) {
  252. if err := pm.config.Store.validateName(name); err != nil { // todo: this check is wrong. remove store
  253. return nil, errdefs.InvalidParameter(err)
  254. }
  255. config, err := pm.setupNewPlugin(configDigest, privileges)
  256. if err != nil {
  257. return nil, err
  258. }
  259. p = &v2.Plugin{
  260. PluginObj: types.Plugin{
  261. Name: name,
  262. ID: stringid.GenerateRandomID(),
  263. Config: config,
  264. },
  265. Config: configDigest,
  266. Blobsums: blobsums,
  267. Manifest: manifestDigest,
  268. }
  269. p.InitEmptySettings()
  270. for _, o := range opts {
  271. o(p)
  272. }
  273. pdir := filepath.Join(pm.config.Root, p.PluginObj.ID)
  274. if err := os.MkdirAll(pdir, 0o700); err != nil {
  275. return nil, errors.Wrapf(err, "failed to mkdir %v", pdir)
  276. }
  277. defer func() {
  278. if err != nil {
  279. os.RemoveAll(pdir)
  280. }
  281. }()
  282. if err := os.Rename(rootFSDir, filepath.Join(pdir, rootFSFileName)); err != nil {
  283. return nil, errors.Wrap(err, "failed to rename rootfs")
  284. }
  285. if err := pm.save(p); err != nil {
  286. return nil, err
  287. }
  288. pm.config.Store.Add(p) // todo: remove
  289. return p, nil
  290. }
  291. func recursiveUnmount(target string) error {
  292. return mount.RecursiveUnmount(target)
  293. }