backend_linux.go 22 KB

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