manager.go 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347
  1. package plugin
  2. import (
  3. "encoding/json"
  4. "io"
  5. "io/ioutil"
  6. "os"
  7. "path/filepath"
  8. "reflect"
  9. "regexp"
  10. "strings"
  11. "sync"
  12. "github.com/Sirupsen/logrus"
  13. "github.com/docker/distribution/reference"
  14. "github.com/docker/docker/api/types"
  15. "github.com/docker/docker/image"
  16. "github.com/docker/docker/layer"
  17. "github.com/docker/docker/libcontainerd"
  18. "github.com/docker/docker/pkg/ioutils"
  19. "github.com/docker/docker/pkg/mount"
  20. "github.com/docker/docker/plugin/v2"
  21. "github.com/docker/docker/registry"
  22. "github.com/opencontainers/go-digest"
  23. "github.com/pkg/errors"
  24. )
  25. const configFileName = "config.json"
  26. const rootFSFileName = "rootfs"
  27. var validFullID = regexp.MustCompile(`^([a-f0-9]{64})$`)
  28. func (pm *Manager) restorePlugin(p *v2.Plugin) error {
  29. if p.IsEnabled() {
  30. return pm.restore(p)
  31. }
  32. return nil
  33. }
  34. type eventLogger func(id, name, action string)
  35. // ManagerConfig defines configuration needed to start new manager.
  36. type ManagerConfig struct {
  37. Store *Store // remove
  38. Executor libcontainerd.Remote
  39. RegistryService registry.Service
  40. LiveRestoreEnabled bool // TODO: remove
  41. LogPluginEvent eventLogger
  42. Root string
  43. ExecRoot string
  44. }
  45. // Manager controls the plugin subsystem.
  46. type Manager struct {
  47. config ManagerConfig
  48. mu sync.RWMutex // protects cMap
  49. muGC sync.RWMutex // protects blobstore deletions
  50. cMap map[*v2.Plugin]*controller
  51. containerdClient libcontainerd.Client
  52. blobStore *basicBlobStore
  53. }
  54. // controller represents the manager's control on a plugin.
  55. type controller struct {
  56. restart bool
  57. exitChan chan bool
  58. timeoutInSecs int
  59. }
  60. // pluginRegistryService ensures that all resolved repositories
  61. // are of the plugin class.
  62. type pluginRegistryService struct {
  63. registry.Service
  64. }
  65. func (s pluginRegistryService) ResolveRepository(name reference.Named) (repoInfo *registry.RepositoryInfo, err error) {
  66. repoInfo, err = s.Service.ResolveRepository(name)
  67. if repoInfo != nil {
  68. repoInfo.Class = "plugin"
  69. }
  70. return
  71. }
  72. // NewManager returns a new plugin manager.
  73. func NewManager(config ManagerConfig) (*Manager, error) {
  74. if config.RegistryService != nil {
  75. config.RegistryService = pluginRegistryService{config.RegistryService}
  76. }
  77. manager := &Manager{
  78. config: config,
  79. }
  80. if err := os.MkdirAll(manager.config.Root, 0700); err != nil {
  81. return nil, errors.Wrapf(err, "failed to mkdir %v", manager.config.Root)
  82. }
  83. if err := os.MkdirAll(manager.config.ExecRoot, 0700); err != nil {
  84. return nil, errors.Wrapf(err, "failed to mkdir %v", manager.config.ExecRoot)
  85. }
  86. if err := os.MkdirAll(manager.tmpDir(), 0700); err != nil {
  87. return nil, errors.Wrapf(err, "failed to mkdir %v", manager.tmpDir())
  88. }
  89. var err error
  90. manager.containerdClient, err = config.Executor.Client(manager) // todo: move to another struct
  91. if err != nil {
  92. return nil, errors.Wrap(err, "failed to create containerd client")
  93. }
  94. manager.blobStore, err = newBasicBlobStore(filepath.Join(manager.config.Root, "storage/blobs"))
  95. if err != nil {
  96. return nil, err
  97. }
  98. manager.cMap = make(map[*v2.Plugin]*controller)
  99. if err := manager.reload(); err != nil {
  100. return nil, errors.Wrap(err, "failed to restore plugins")
  101. }
  102. return manager, nil
  103. }
  104. func (pm *Manager) tmpDir() string {
  105. return filepath.Join(pm.config.Root, "tmp")
  106. }
  107. // StateChanged updates plugin internals using libcontainerd events.
  108. func (pm *Manager) StateChanged(id string, e libcontainerd.StateInfo) error {
  109. logrus.Debugf("plugin state changed %s %#v", id, e)
  110. switch e.State {
  111. case libcontainerd.StateExit:
  112. p, err := pm.config.Store.GetV2Plugin(id)
  113. if err != nil {
  114. return err
  115. }
  116. pm.mu.RLock()
  117. c := pm.cMap[p]
  118. if c.exitChan != nil {
  119. close(c.exitChan)
  120. }
  121. restart := c.restart
  122. pm.mu.RUnlock()
  123. os.RemoveAll(filepath.Join(pm.config.ExecRoot, id))
  124. if p.PropagatedMount != "" {
  125. if err := mount.Unmount(p.PropagatedMount); err != nil {
  126. logrus.Warnf("Could not unmount %s: %v", p.PropagatedMount, err)
  127. }
  128. propRoot := filepath.Join(filepath.Dir(p.Rootfs), "propagated-mount")
  129. if err := mount.Unmount(propRoot); err != nil {
  130. logrus.Warn("Could not unmount %s: %v", propRoot, err)
  131. }
  132. }
  133. if restart {
  134. pm.enable(p, c, true)
  135. }
  136. }
  137. return nil
  138. }
  139. func (pm *Manager) reload() error { // todo: restore
  140. dir, err := ioutil.ReadDir(pm.config.Root)
  141. if err != nil {
  142. return errors.Wrapf(err, "failed to read %v", pm.config.Root)
  143. }
  144. plugins := make(map[string]*v2.Plugin)
  145. for _, v := range dir {
  146. if validFullID.MatchString(v.Name()) {
  147. p, err := pm.loadPlugin(v.Name())
  148. if err != nil {
  149. return err
  150. }
  151. plugins[p.GetID()] = p
  152. }
  153. }
  154. pm.config.Store.SetAll(plugins)
  155. var wg sync.WaitGroup
  156. wg.Add(len(plugins))
  157. for _, p := range plugins {
  158. c := &controller{} // todo: remove this
  159. pm.cMap[p] = c
  160. go func(p *v2.Plugin) {
  161. defer wg.Done()
  162. if err := pm.restorePlugin(p); err != nil {
  163. logrus.Errorf("failed to restore plugin '%s': %s", p.Name(), err)
  164. return
  165. }
  166. if p.Rootfs != "" {
  167. p.Rootfs = filepath.Join(pm.config.Root, p.PluginObj.ID, "rootfs")
  168. }
  169. // We should only enable rootfs propagation for certain plugin types that need it.
  170. for _, typ := range p.PluginObj.Config.Interface.Types {
  171. if (typ.Capability == "volumedriver" || typ.Capability == "graphdriver") && typ.Prefix == "docker" && strings.HasPrefix(typ.Version, "1.") {
  172. if p.PluginObj.Config.PropagatedMount != "" {
  173. propRoot := filepath.Join(filepath.Dir(p.Rootfs), "propagated-mount")
  174. // check if we need to migrate an older propagated mount from before
  175. // these mounts were stored outside the plugin rootfs
  176. if _, err := os.Stat(propRoot); os.IsNotExist(err) {
  177. if _, err := os.Stat(p.PropagatedMount); err == nil {
  178. // make sure nothing is mounted here
  179. // don't care about errors
  180. mount.Unmount(p.PropagatedMount)
  181. if err := os.Rename(p.PropagatedMount, propRoot); err != nil {
  182. logrus.WithError(err).WithField("dir", propRoot).Error("error migrating propagated mount storage")
  183. }
  184. if err := os.MkdirAll(p.PropagatedMount, 0755); err != nil {
  185. logrus.WithError(err).WithField("dir", p.PropagatedMount).Error("error migrating propagated mount storage")
  186. }
  187. }
  188. }
  189. if err := os.MkdirAll(propRoot, 0755); err != nil {
  190. logrus.Errorf("failed to create PropagatedMount directory at %s: %v", propRoot, err)
  191. }
  192. // TODO: sanitize PropagatedMount and prevent breakout
  193. p.PropagatedMount = filepath.Join(p.Rootfs, p.PluginObj.Config.PropagatedMount)
  194. if err := os.MkdirAll(p.PropagatedMount, 0755); err != nil {
  195. logrus.Errorf("failed to create PropagatedMount directory at %s: %v", p.PropagatedMount, err)
  196. return
  197. }
  198. }
  199. }
  200. }
  201. pm.save(p)
  202. requiresManualRestore := !pm.config.LiveRestoreEnabled && p.IsEnabled()
  203. if requiresManualRestore {
  204. // if liveRestore is not enabled, the plugin will be stopped now so we should enable it
  205. if err := pm.enable(p, c, true); err != nil {
  206. logrus.Errorf("failed to enable plugin '%s': %s", p.Name(), err)
  207. }
  208. }
  209. }(p)
  210. }
  211. wg.Wait()
  212. return nil
  213. }
  214. func (pm *Manager) loadPlugin(id string) (*v2.Plugin, error) {
  215. p := filepath.Join(pm.config.Root, id, configFileName)
  216. dt, err := ioutil.ReadFile(p)
  217. if err != nil {
  218. return nil, errors.Wrapf(err, "error reading %v", p)
  219. }
  220. var plugin v2.Plugin
  221. if err := json.Unmarshal(dt, &plugin); err != nil {
  222. return nil, errors.Wrapf(err, "error decoding %v", p)
  223. }
  224. return &plugin, nil
  225. }
  226. func (pm *Manager) save(p *v2.Plugin) error {
  227. pluginJSON, err := json.Marshal(p)
  228. if err != nil {
  229. return errors.Wrap(err, "failed to marshal plugin json")
  230. }
  231. if err := ioutils.AtomicWriteFile(filepath.Join(pm.config.Root, p.GetID(), configFileName), pluginJSON, 0600); err != nil {
  232. return errors.Wrap(err, "failed to write atomically plugin json")
  233. }
  234. return nil
  235. }
  236. // GC cleans up unrefrenced blobs. This is recommended to run in a goroutine
  237. func (pm *Manager) GC() {
  238. pm.muGC.Lock()
  239. defer pm.muGC.Unlock()
  240. whitelist := make(map[digest.Digest]struct{})
  241. for _, p := range pm.config.Store.GetAll() {
  242. whitelist[p.Config] = struct{}{}
  243. for _, b := range p.Blobsums {
  244. whitelist[b] = struct{}{}
  245. }
  246. }
  247. pm.blobStore.gc(whitelist)
  248. }
  249. type logHook struct{ id string }
  250. func (logHook) Levels() []logrus.Level {
  251. return logrus.AllLevels
  252. }
  253. func (l logHook) Fire(entry *logrus.Entry) error {
  254. entry.Data = logrus.Fields{"plugin": l.id}
  255. return nil
  256. }
  257. func attachToLog(id string) func(libcontainerd.IOPipe) error {
  258. return func(iop libcontainerd.IOPipe) error {
  259. iop.Stdin.Close()
  260. logger := logrus.New()
  261. logger.Hooks.Add(logHook{id})
  262. // TODO: cache writer per id
  263. w := logger.Writer()
  264. go func() {
  265. io.Copy(w, iop.Stdout)
  266. }()
  267. go func() {
  268. // TODO: update logrus and use logger.WriterLevel
  269. io.Copy(w, iop.Stderr)
  270. }()
  271. return nil
  272. }
  273. }
  274. func validatePrivileges(requiredPrivileges, privileges types.PluginPrivileges) error {
  275. // todo: make a better function that doesn't check order
  276. if !reflect.DeepEqual(privileges, requiredPrivileges) {
  277. return errors.New("incorrect privileges")
  278. }
  279. return nil
  280. }
  281. func configToRootFS(c []byte) (*image.RootFS, error) {
  282. var pluginConfig types.PluginConfig
  283. if err := json.Unmarshal(c, &pluginConfig); err != nil {
  284. return nil, err
  285. }
  286. // validation for empty rootfs is in distribution code
  287. if pluginConfig.Rootfs == nil {
  288. return nil, nil
  289. }
  290. return rootFSFromPlugin(pluginConfig.Rootfs), nil
  291. }
  292. func rootFSFromPlugin(pluginfs *types.PluginConfigRootfs) *image.RootFS {
  293. rootFS := image.RootFS{
  294. Type: pluginfs.Type,
  295. DiffIDs: make([]layer.DiffID, len(pluginfs.DiffIds)),
  296. }
  297. for i := range pluginfs.DiffIds {
  298. rootFS.DiffIDs[i] = layer.DiffID(pluginfs.DiffIds[i])
  299. }
  300. return &rootFS
  301. }