manager_linux.go 8.9 KB

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