backend_linux.go 22 KB

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