backend_linux.go 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863
  1. // +build linux
  2. package plugin
  3. import (
  4. "archive/tar"
  5. "compress/gzip"
  6. "encoding/json"
  7. "fmt"
  8. "io"
  9. "io/ioutil"
  10. "net/http"
  11. "os"
  12. "path"
  13. "path/filepath"
  14. "sort"
  15. "strings"
  16. "github.com/Sirupsen/logrus"
  17. "github.com/docker/distribution/manifest/schema2"
  18. "github.com/docker/distribution/reference"
  19. "github.com/docker/docker/api/types"
  20. "github.com/docker/docker/api/types/filters"
  21. "github.com/docker/docker/distribution"
  22. progressutils "github.com/docker/docker/distribution/utils"
  23. "github.com/docker/docker/distribution/xfer"
  24. "github.com/docker/docker/dockerversion"
  25. "github.com/docker/docker/image"
  26. "github.com/docker/docker/layer"
  27. "github.com/docker/docker/pkg/authorization"
  28. "github.com/docker/docker/pkg/chrootarchive"
  29. "github.com/docker/docker/pkg/mount"
  30. "github.com/docker/docker/pkg/pools"
  31. "github.com/docker/docker/pkg/progress"
  32. "github.com/docker/docker/plugin/v2"
  33. refstore "github.com/docker/docker/reference"
  34. "github.com/opencontainers/go-digest"
  35. "github.com/pkg/errors"
  36. "golang.org/x/net/context"
  37. )
  38. var acceptedPluginFilterTags = map[string]bool{
  39. "enabled": true,
  40. "capability": true,
  41. }
  42. // Disable deactivates a plugin. This means resources (volumes, networks) cant use them.
  43. func (pm *Manager) Disable(refOrID string, config *types.PluginDisableConfig) error {
  44. p, err := pm.config.Store.GetV2Plugin(refOrID)
  45. if err != nil {
  46. return err
  47. }
  48. pm.mu.RLock()
  49. c := pm.cMap[p]
  50. pm.mu.RUnlock()
  51. if !config.ForceDisable && p.GetRefCount() > 0 {
  52. return fmt.Errorf("plugin %s is in use", p.Name())
  53. }
  54. for _, typ := range p.GetTypes() {
  55. if typ.Capability == authorization.AuthZApiImplements {
  56. authzList := pm.config.AuthzMiddleware.GetAuthzPlugins()
  57. for i, authPlugin := range authzList {
  58. if authPlugin.Name() == p.Name() {
  59. // Remove plugin from authzmiddleware chain
  60. authzList = append(authzList[:i], authzList[i+1:]...)
  61. pm.config.AuthzMiddleware.SetAuthzPlugins(authzList)
  62. }
  63. }
  64. }
  65. }
  66. if err := pm.disable(p, c); err != nil {
  67. return err
  68. }
  69. pm.config.LogPluginEvent(p.GetID(), refOrID, "disable")
  70. return nil
  71. }
  72. // Enable activates a plugin, which implies that they are ready to be used by containers.
  73. func (pm *Manager) Enable(refOrID string, config *types.PluginEnableConfig) error {
  74. p, err := pm.config.Store.GetV2Plugin(refOrID)
  75. if err != nil {
  76. return err
  77. }
  78. c := &controller{timeoutInSecs: config.Timeout}
  79. if err := pm.enable(p, c, false); err != nil {
  80. return err
  81. }
  82. pm.config.LogPluginEvent(p.GetID(), refOrID, "enable")
  83. return nil
  84. }
  85. // Inspect examines a plugin config
  86. func (pm *Manager) Inspect(refOrID string) (tp *types.Plugin, err error) {
  87. p, err := pm.config.Store.GetV2Plugin(refOrID)
  88. if err != nil {
  89. return nil, err
  90. }
  91. return &p.PluginObj, nil
  92. }
  93. func (pm *Manager) pull(ctx context.Context, ref reference.Named, config *distribution.ImagePullConfig, outStream io.Writer) error {
  94. if outStream != nil {
  95. // Include a buffer so that slow client connections don't affect
  96. // transfer performance.
  97. progressChan := make(chan progress.Progress, 100)
  98. writesDone := make(chan struct{})
  99. defer func() {
  100. close(progressChan)
  101. <-writesDone
  102. }()
  103. var cancelFunc context.CancelFunc
  104. ctx, cancelFunc = context.WithCancel(ctx)
  105. go func() {
  106. progressutils.WriteDistributionProgress(cancelFunc, outStream, progressChan)
  107. close(writesDone)
  108. }()
  109. config.ProgressOutput = progress.ChanOutput(progressChan)
  110. } else {
  111. config.ProgressOutput = progress.DiscardOutput()
  112. }
  113. return distribution.Pull(ctx, ref, config)
  114. }
  115. type tempConfigStore struct {
  116. config []byte
  117. configDigest digest.Digest
  118. }
  119. func (s *tempConfigStore) Put(c []byte) (digest.Digest, error) {
  120. dgst := digest.FromBytes(c)
  121. s.config = c
  122. s.configDigest = dgst
  123. return dgst, nil
  124. }
  125. func (s *tempConfigStore) Get(d digest.Digest) ([]byte, error) {
  126. if d != s.configDigest {
  127. return nil, fmt.Errorf("digest not found")
  128. }
  129. return s.config, nil
  130. }
  131. func (s *tempConfigStore) RootFSFromConfig(c []byte) (*image.RootFS, error) {
  132. return configToRootFS(c)
  133. }
  134. func computePrivileges(c types.PluginConfig) (types.PluginPrivileges, error) {
  135. var privileges types.PluginPrivileges
  136. if c.Network.Type != "null" && c.Network.Type != "bridge" && c.Network.Type != "" {
  137. privileges = append(privileges, types.PluginPrivilege{
  138. Name: "network",
  139. Description: "permissions to access a network",
  140. Value: []string{c.Network.Type},
  141. })
  142. }
  143. if c.IpcHost {
  144. privileges = append(privileges, types.PluginPrivilege{
  145. Name: "host ipc namespace",
  146. Description: "allow access to host ipc namespace",
  147. Value: []string{"true"},
  148. })
  149. }
  150. if c.PidHost {
  151. privileges = append(privileges, types.PluginPrivilege{
  152. Name: "host pid namespace",
  153. Description: "allow access to host pid namespace",
  154. Value: []string{"true"},
  155. })
  156. }
  157. for _, mount := range c.Mounts {
  158. if mount.Source != nil {
  159. privileges = append(privileges, types.PluginPrivilege{
  160. Name: "mount",
  161. Description: "host path to mount",
  162. Value: []string{*mount.Source},
  163. })
  164. }
  165. }
  166. for _, device := range c.Linux.Devices {
  167. if device.Path != nil {
  168. privileges = append(privileges, types.PluginPrivilege{
  169. Name: "device",
  170. Description: "host device to access",
  171. Value: []string{*device.Path},
  172. })
  173. }
  174. }
  175. if c.Linux.AllowAllDevices {
  176. privileges = append(privileges, types.PluginPrivilege{
  177. Name: "allow-all-devices",
  178. Description: "allow 'rwm' access to all devices",
  179. Value: []string{"true"},
  180. })
  181. }
  182. if len(c.Linux.Capabilities) > 0 {
  183. privileges = append(privileges, types.PluginPrivilege{
  184. Name: "capabilities",
  185. Description: "list of additional capabilities required",
  186. Value: c.Linux.Capabilities,
  187. })
  188. }
  189. return privileges, nil
  190. }
  191. // Privileges pulls a plugin config and computes the privileges required to install it.
  192. func (pm *Manager) Privileges(ctx context.Context, ref reference.Named, metaHeader http.Header, authConfig *types.AuthConfig) (types.PluginPrivileges, error) {
  193. // create image store instance
  194. cs := &tempConfigStore{}
  195. // DownloadManager not defined because only pulling configuration.
  196. pluginPullConfig := &distribution.ImagePullConfig{
  197. Config: distribution.Config{
  198. MetaHeaders: metaHeader,
  199. AuthConfig: authConfig,
  200. RegistryService: pm.config.RegistryService,
  201. ImageEventLogger: func(string, string, string) {},
  202. ImageStore: cs,
  203. },
  204. Schema2Types: distribution.PluginTypes,
  205. }
  206. if err := pm.pull(ctx, ref, pluginPullConfig, nil); err != nil {
  207. return nil, err
  208. }
  209. if cs.config == nil {
  210. return nil, errors.New("no configuration pulled")
  211. }
  212. var config types.PluginConfig
  213. if err := json.Unmarshal(cs.config, &config); err != nil {
  214. return nil, err
  215. }
  216. return computePrivileges(config)
  217. }
  218. // Upgrade upgrades a plugin
  219. func (pm *Manager) Upgrade(ctx context.Context, ref reference.Named, name string, metaHeader http.Header, authConfig *types.AuthConfig, privileges types.PluginPrivileges, outStream io.Writer) (err error) {
  220. p, err := pm.config.Store.GetV2Plugin(name)
  221. if err != nil {
  222. return errors.Wrap(err, "plugin must be installed before upgrading")
  223. }
  224. if p.IsEnabled() {
  225. return fmt.Errorf("plugin must be disabled before upgrading")
  226. }
  227. pm.muGC.RLock()
  228. defer pm.muGC.RUnlock()
  229. // revalidate because Pull is public
  230. if _, err := reference.ParseNormalizedNamed(name); err != nil {
  231. return errors.Wrapf(err, "failed to parse %q", name)
  232. }
  233. tmpRootFSDir, err := ioutil.TempDir(pm.tmpDir(), ".rootfs")
  234. if err != nil {
  235. return err
  236. }
  237. defer os.RemoveAll(tmpRootFSDir)
  238. dm := &downloadManager{
  239. tmpDir: tmpRootFSDir,
  240. blobStore: pm.blobStore,
  241. }
  242. pluginPullConfig := &distribution.ImagePullConfig{
  243. Config: distribution.Config{
  244. MetaHeaders: metaHeader,
  245. AuthConfig: authConfig,
  246. RegistryService: pm.config.RegistryService,
  247. ImageEventLogger: pm.config.LogPluginEvent,
  248. ImageStore: dm,
  249. },
  250. DownloadManager: dm, // todo: reevaluate if possible to substitute distribution/xfer dependencies instead
  251. Schema2Types: distribution.PluginTypes,
  252. }
  253. err = pm.pull(ctx, ref, pluginPullConfig, outStream)
  254. if err != nil {
  255. go pm.GC()
  256. return err
  257. }
  258. if err := pm.upgradePlugin(p, dm.configDigest, dm.blobs, tmpRootFSDir, &privileges); err != nil {
  259. return err
  260. }
  261. p.PluginObj.PluginReference = ref.String()
  262. return nil
  263. }
  264. // Pull pulls a plugin, check if the correct privileges are provided and install the plugin.
  265. func (pm *Manager) Pull(ctx context.Context, ref reference.Named, name string, metaHeader http.Header, authConfig *types.AuthConfig, privileges types.PluginPrivileges, outStream io.Writer) (err error) {
  266. pm.muGC.RLock()
  267. defer pm.muGC.RUnlock()
  268. // revalidate because Pull is public
  269. nameref, err := reference.ParseNormalizedNamed(name)
  270. if err != nil {
  271. return errors.Wrapf(err, "failed to parse %q", name)
  272. }
  273. name = reference.FamiliarString(reference.TagNameOnly(nameref))
  274. if err := pm.config.Store.validateName(name); err != nil {
  275. return err
  276. }
  277. tmpRootFSDir, err := ioutil.TempDir(pm.tmpDir(), ".rootfs")
  278. if err != nil {
  279. return err
  280. }
  281. defer os.RemoveAll(tmpRootFSDir)
  282. dm := &downloadManager{
  283. tmpDir: tmpRootFSDir,
  284. blobStore: pm.blobStore,
  285. }
  286. pluginPullConfig := &distribution.ImagePullConfig{
  287. Config: distribution.Config{
  288. MetaHeaders: metaHeader,
  289. AuthConfig: authConfig,
  290. RegistryService: pm.config.RegistryService,
  291. ImageEventLogger: pm.config.LogPluginEvent,
  292. ImageStore: dm,
  293. },
  294. DownloadManager: dm, // todo: reevaluate if possible to substitute distribution/xfer dependencies instead
  295. Schema2Types: distribution.PluginTypes,
  296. }
  297. err = pm.pull(ctx, ref, pluginPullConfig, outStream)
  298. if err != nil {
  299. go pm.GC()
  300. return err
  301. }
  302. p, err := pm.createPlugin(name, dm.configDigest, dm.blobs, tmpRootFSDir, &privileges)
  303. if err != nil {
  304. return err
  305. }
  306. p.PluginObj.PluginReference = ref.String()
  307. return nil
  308. }
  309. // List displays the list of plugins and associated metadata.
  310. func (pm *Manager) List(pluginFilters filters.Args) ([]types.Plugin, error) {
  311. if err := pluginFilters.Validate(acceptedPluginFilterTags); err != nil {
  312. return nil, err
  313. }
  314. enabledOnly := false
  315. disabledOnly := false
  316. if pluginFilters.Include("enabled") {
  317. if pluginFilters.ExactMatch("enabled", "true") {
  318. enabledOnly = true
  319. } else if pluginFilters.ExactMatch("enabled", "false") {
  320. disabledOnly = true
  321. } else {
  322. return nil, fmt.Errorf("Invalid filter 'enabled=%s'", pluginFilters.Get("enabled"))
  323. }
  324. }
  325. plugins := pm.config.Store.GetAll()
  326. out := make([]types.Plugin, 0, len(plugins))
  327. next:
  328. for _, p := range plugins {
  329. if enabledOnly && !p.PluginObj.Enabled {
  330. continue
  331. }
  332. if disabledOnly && p.PluginObj.Enabled {
  333. continue
  334. }
  335. if pluginFilters.Include("capability") {
  336. for _, f := range p.GetTypes() {
  337. if !pluginFilters.Match("capability", f.Capability) {
  338. continue next
  339. }
  340. }
  341. }
  342. out = append(out, p.PluginObj)
  343. }
  344. return out, nil
  345. }
  346. // Push pushes a plugin to the store.
  347. func (pm *Manager) Push(ctx context.Context, name string, metaHeader http.Header, authConfig *types.AuthConfig, outStream io.Writer) error {
  348. p, err := pm.config.Store.GetV2Plugin(name)
  349. if err != nil {
  350. return err
  351. }
  352. ref, err := reference.ParseNormalizedNamed(p.Name())
  353. if err != nil {
  354. return errors.Wrapf(err, "plugin has invalid name %v for push", p.Name())
  355. }
  356. var po progress.Output
  357. if outStream != nil {
  358. // Include a buffer so that slow client connections don't affect
  359. // transfer performance.
  360. progressChan := make(chan progress.Progress, 100)
  361. writesDone := make(chan struct{})
  362. defer func() {
  363. close(progressChan)
  364. <-writesDone
  365. }()
  366. var cancelFunc context.CancelFunc
  367. ctx, cancelFunc = context.WithCancel(ctx)
  368. go func() {
  369. progressutils.WriteDistributionProgress(cancelFunc, outStream, progressChan)
  370. close(writesDone)
  371. }()
  372. po = progress.ChanOutput(progressChan)
  373. } else {
  374. po = progress.DiscardOutput()
  375. }
  376. // TODO: replace these with manager
  377. is := &pluginConfigStore{
  378. pm: pm,
  379. plugin: p,
  380. }
  381. ls := &pluginLayerProvider{
  382. pm: pm,
  383. plugin: p,
  384. }
  385. rs := &pluginReference{
  386. name: ref,
  387. pluginID: p.Config,
  388. }
  389. uploadManager := xfer.NewLayerUploadManager(3)
  390. imagePushConfig := &distribution.ImagePushConfig{
  391. Config: distribution.Config{
  392. MetaHeaders: metaHeader,
  393. AuthConfig: authConfig,
  394. ProgressOutput: po,
  395. RegistryService: pm.config.RegistryService,
  396. ReferenceStore: rs,
  397. ImageEventLogger: pm.config.LogPluginEvent,
  398. ImageStore: is,
  399. RequireSchema2: true,
  400. },
  401. ConfigMediaType: schema2.MediaTypePluginConfig,
  402. LayerStore: ls,
  403. UploadManager: uploadManager,
  404. }
  405. return distribution.Push(ctx, ref, imagePushConfig)
  406. }
  407. type pluginReference struct {
  408. name reference.Named
  409. pluginID digest.Digest
  410. }
  411. func (r *pluginReference) References(id digest.Digest) []reference.Named {
  412. if r.pluginID != id {
  413. return nil
  414. }
  415. return []reference.Named{r.name}
  416. }
  417. func (r *pluginReference) ReferencesByName(ref reference.Named) []refstore.Association {
  418. return []refstore.Association{
  419. {
  420. Ref: r.name,
  421. ID: r.pluginID,
  422. },
  423. }
  424. }
  425. func (r *pluginReference) Get(ref reference.Named) (digest.Digest, error) {
  426. if r.name.String() != ref.String() {
  427. return digest.Digest(""), refstore.ErrDoesNotExist
  428. }
  429. return r.pluginID, nil
  430. }
  431. func (r *pluginReference) AddTag(ref reference.Named, id digest.Digest, force bool) error {
  432. // Read only, ignore
  433. return nil
  434. }
  435. func (r *pluginReference) AddDigest(ref reference.Canonical, id digest.Digest, force bool) error {
  436. // Read only, ignore
  437. return nil
  438. }
  439. func (r *pluginReference) Delete(ref reference.Named) (bool, error) {
  440. // Read only, ignore
  441. return false, nil
  442. }
  443. type pluginConfigStore struct {
  444. pm *Manager
  445. plugin *v2.Plugin
  446. }
  447. func (s *pluginConfigStore) Put([]byte) (digest.Digest, error) {
  448. return digest.Digest(""), errors.New("cannot store config on push")
  449. }
  450. func (s *pluginConfigStore) Get(d digest.Digest) ([]byte, error) {
  451. if s.plugin.Config != d {
  452. return nil, errors.New("plugin not found")
  453. }
  454. rwc, err := s.pm.blobStore.Get(d)
  455. if err != nil {
  456. return nil, err
  457. }
  458. defer rwc.Close()
  459. return ioutil.ReadAll(rwc)
  460. }
  461. func (s *pluginConfigStore) RootFSFromConfig(c []byte) (*image.RootFS, error) {
  462. return configToRootFS(c)
  463. }
  464. type pluginLayerProvider struct {
  465. pm *Manager
  466. plugin *v2.Plugin
  467. }
  468. func (p *pluginLayerProvider) Get(id layer.ChainID) (distribution.PushLayer, error) {
  469. rootFS := rootFSFromPlugin(p.plugin.PluginObj.Config.Rootfs)
  470. var i int
  471. for i = 1; i <= len(rootFS.DiffIDs); i++ {
  472. if layer.CreateChainID(rootFS.DiffIDs[:i]) == id {
  473. break
  474. }
  475. }
  476. if i > len(rootFS.DiffIDs) {
  477. return nil, errors.New("layer not found")
  478. }
  479. return &pluginLayer{
  480. pm: p.pm,
  481. diffIDs: rootFS.DiffIDs[:i],
  482. blobs: p.plugin.Blobsums[:i],
  483. }, nil
  484. }
  485. type pluginLayer struct {
  486. pm *Manager
  487. diffIDs []layer.DiffID
  488. blobs []digest.Digest
  489. }
  490. func (l *pluginLayer) ChainID() layer.ChainID {
  491. return layer.CreateChainID(l.diffIDs)
  492. }
  493. func (l *pluginLayer) DiffID() layer.DiffID {
  494. return l.diffIDs[len(l.diffIDs)-1]
  495. }
  496. func (l *pluginLayer) Parent() distribution.PushLayer {
  497. if len(l.diffIDs) == 1 {
  498. return nil
  499. }
  500. return &pluginLayer{
  501. pm: l.pm,
  502. diffIDs: l.diffIDs[:len(l.diffIDs)-1],
  503. blobs: l.blobs[:len(l.diffIDs)-1],
  504. }
  505. }
  506. func (l *pluginLayer) Open() (io.ReadCloser, error) {
  507. return l.pm.blobStore.Get(l.blobs[len(l.diffIDs)-1])
  508. }
  509. func (l *pluginLayer) Size() (int64, error) {
  510. return l.pm.blobStore.Size(l.blobs[len(l.diffIDs)-1])
  511. }
  512. func (l *pluginLayer) MediaType() string {
  513. return schema2.MediaTypeLayer
  514. }
  515. func (l *pluginLayer) Release() {
  516. // Nothing needs to be release, no references held
  517. }
  518. // Remove deletes plugin's root directory.
  519. func (pm *Manager) Remove(name string, config *types.PluginRmConfig) error {
  520. p, err := pm.config.Store.GetV2Plugin(name)
  521. pm.mu.RLock()
  522. c := pm.cMap[p]
  523. pm.mu.RUnlock()
  524. if err != nil {
  525. return err
  526. }
  527. if !config.ForceRemove {
  528. if p.GetRefCount() > 0 {
  529. return fmt.Errorf("plugin %s is in use", p.Name())
  530. }
  531. if p.IsEnabled() {
  532. return fmt.Errorf("plugin %s is enabled", p.Name())
  533. }
  534. }
  535. if p.IsEnabled() {
  536. if err := pm.disable(p, c); err != nil {
  537. logrus.Errorf("failed to disable plugin '%s': %s", p.Name(), err)
  538. }
  539. }
  540. defer func() {
  541. go pm.GC()
  542. }()
  543. id := p.GetID()
  544. pm.config.Store.Remove(p)
  545. pluginDir := filepath.Join(pm.config.Root, id)
  546. if err := recursiveUnmount(pluginDir); err != nil {
  547. logrus.WithField("dir", pluginDir).WithField("id", id).Warn(err)
  548. }
  549. if err := os.RemoveAll(pluginDir); err != nil {
  550. logrus.Warnf("unable to remove %q from plugin remove: %v", pluginDir, err)
  551. }
  552. pm.config.LogPluginEvent(id, name, "remove")
  553. return nil
  554. }
  555. func getMounts(root string) ([]string, error) {
  556. infos, err := mount.GetMounts()
  557. if err != nil {
  558. return nil, errors.Wrap(err, "failed to read mount table")
  559. }
  560. var mounts []string
  561. for _, m := range infos {
  562. if strings.HasPrefix(m.Mountpoint, root) {
  563. mounts = append(mounts, m.Mountpoint)
  564. }
  565. }
  566. return mounts, nil
  567. }
  568. func recursiveUnmount(root string) error {
  569. mounts, err := getMounts(root)
  570. if err != nil {
  571. return err
  572. }
  573. // sort in reverse-lexicographic order so the root mount will always be last
  574. sort.Sort(sort.Reverse(sort.StringSlice(mounts)))
  575. for i, m := range mounts {
  576. if err := mount.Unmount(m); err != nil {
  577. if i == len(mounts)-1 {
  578. return errors.Wrapf(err, "error performing recursive unmount on %s", root)
  579. }
  580. logrus.WithError(err).WithField("mountpoint", m).Warn("could not unmount")
  581. }
  582. }
  583. return nil
  584. }
  585. // Set sets plugin args
  586. func (pm *Manager) Set(name string, args []string) error {
  587. p, err := pm.config.Store.GetV2Plugin(name)
  588. if err != nil {
  589. return err
  590. }
  591. if err := p.Set(args); err != nil {
  592. return err
  593. }
  594. return pm.save(p)
  595. }
  596. // CreateFromContext creates a plugin from the given pluginDir which contains
  597. // both the rootfs and the config.json and a repoName with optional tag.
  598. func (pm *Manager) CreateFromContext(ctx context.Context, tarCtx io.ReadCloser, options *types.PluginCreateOptions) (err error) {
  599. pm.muGC.RLock()
  600. defer pm.muGC.RUnlock()
  601. ref, err := reference.ParseNormalizedNamed(options.RepoName)
  602. if err != nil {
  603. return errors.Wrapf(err, "failed to parse reference %v", options.RepoName)
  604. }
  605. if _, ok := ref.(reference.Canonical); ok {
  606. return errors.Errorf("canonical references are not permitted")
  607. }
  608. name := reference.FamiliarString(reference.TagNameOnly(ref))
  609. if err := pm.config.Store.validateName(name); err != nil { // fast check, real check is in createPlugin()
  610. return err
  611. }
  612. tmpRootFSDir, err := ioutil.TempDir(pm.tmpDir(), ".rootfs")
  613. if err != nil {
  614. return errors.Wrap(err, "failed to create temp directory")
  615. }
  616. defer os.RemoveAll(tmpRootFSDir)
  617. var configJSON []byte
  618. rootFS := splitConfigRootFSFromTar(tarCtx, &configJSON)
  619. rootFSBlob, err := pm.blobStore.New()
  620. if err != nil {
  621. return err
  622. }
  623. defer rootFSBlob.Close()
  624. gzw := gzip.NewWriter(rootFSBlob)
  625. layerDigester := digest.Canonical.Digester()
  626. rootFSReader := io.TeeReader(rootFS, io.MultiWriter(gzw, layerDigester.Hash()))
  627. if err := chrootarchive.Untar(rootFSReader, tmpRootFSDir, nil); err != nil {
  628. return err
  629. }
  630. if err := rootFS.Close(); err != nil {
  631. return err
  632. }
  633. if configJSON == nil {
  634. return errors.New("config not found")
  635. }
  636. if err := gzw.Close(); err != nil {
  637. return errors.Wrap(err, "error closing gzip writer")
  638. }
  639. var config types.PluginConfig
  640. if err := json.Unmarshal(configJSON, &config); err != nil {
  641. return errors.Wrap(err, "failed to parse config")
  642. }
  643. if err := pm.validateConfig(config); err != nil {
  644. return err
  645. }
  646. pm.mu.Lock()
  647. defer pm.mu.Unlock()
  648. rootFSBlobsum, err := rootFSBlob.Commit()
  649. if err != nil {
  650. return err
  651. }
  652. defer func() {
  653. if err != nil {
  654. go pm.GC()
  655. }
  656. }()
  657. config.Rootfs = &types.PluginConfigRootfs{
  658. Type: "layers",
  659. DiffIds: []string{layerDigester.Digest().String()},
  660. }
  661. config.DockerVersion = dockerversion.Version
  662. configBlob, err := pm.blobStore.New()
  663. if err != nil {
  664. return err
  665. }
  666. defer configBlob.Close()
  667. if err := json.NewEncoder(configBlob).Encode(config); err != nil {
  668. return errors.Wrap(err, "error encoding json config")
  669. }
  670. configBlobsum, err := configBlob.Commit()
  671. if err != nil {
  672. return err
  673. }
  674. p, err := pm.createPlugin(name, configBlobsum, []digest.Digest{rootFSBlobsum}, tmpRootFSDir, nil)
  675. if err != nil {
  676. return err
  677. }
  678. p.PluginObj.PluginReference = name
  679. pm.config.LogPluginEvent(p.PluginObj.ID, name, "create")
  680. return nil
  681. }
  682. func (pm *Manager) validateConfig(config types.PluginConfig) error {
  683. return nil // TODO:
  684. }
  685. func splitConfigRootFSFromTar(in io.ReadCloser, config *[]byte) io.ReadCloser {
  686. pr, pw := io.Pipe()
  687. go func() {
  688. tarReader := tar.NewReader(in)
  689. tarWriter := tar.NewWriter(pw)
  690. defer in.Close()
  691. hasRootFS := false
  692. for {
  693. hdr, err := tarReader.Next()
  694. if err == io.EOF {
  695. if !hasRootFS {
  696. pw.CloseWithError(errors.Wrap(err, "no rootfs found"))
  697. return
  698. }
  699. // Signals end of archive.
  700. tarWriter.Close()
  701. pw.Close()
  702. return
  703. }
  704. if err != nil {
  705. pw.CloseWithError(errors.Wrap(err, "failed to read from tar"))
  706. return
  707. }
  708. content := io.Reader(tarReader)
  709. name := path.Clean(hdr.Name)
  710. if path.IsAbs(name) {
  711. name = name[1:]
  712. }
  713. if name == configFileName {
  714. dt, err := ioutil.ReadAll(content)
  715. if err != nil {
  716. pw.CloseWithError(errors.Wrapf(err, "failed to read %s", configFileName))
  717. return
  718. }
  719. *config = dt
  720. }
  721. if parts := strings.Split(name, "/"); len(parts) != 0 && parts[0] == rootFSFileName {
  722. hdr.Name = path.Clean(path.Join(parts[1:]...))
  723. if hdr.Typeflag == tar.TypeLink && strings.HasPrefix(strings.ToLower(hdr.Linkname), rootFSFileName+"/") {
  724. hdr.Linkname = hdr.Linkname[len(rootFSFileName)+1:]
  725. }
  726. if err := tarWriter.WriteHeader(hdr); err != nil {
  727. pw.CloseWithError(errors.Wrap(err, "error writing tar header"))
  728. return
  729. }
  730. if _, err := pools.Copy(tarWriter, content); err != nil {
  731. pw.CloseWithError(errors.Wrap(err, "error copying tar data"))
  732. return
  733. }
  734. hasRootFS = true
  735. } else {
  736. io.Copy(ioutil.Discard, content)
  737. }
  738. }
  739. }()
  740. return pr
  741. }