backend_linux.go 17 KB

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