manager_linux.go 9.2 KB

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