manager.go 10 KB

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