manager_linux.go 9.7 KB

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