backend_linux.go 21 KB

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