backend_linux.go 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830
  1. package plugin // import "github.com/docker/docker/plugin"
  2. import (
  3. "archive/tar"
  4. "bytes"
  5. "compress/gzip"
  6. "context"
  7. "encoding/json"
  8. "io"
  9. "net/http"
  10. "os"
  11. "path"
  12. "path/filepath"
  13. "strings"
  14. "time"
  15. "github.com/containerd/containerd/content"
  16. "github.com/containerd/containerd/images"
  17. "github.com/containerd/containerd/platforms"
  18. "github.com/containerd/containerd/remotes"
  19. "github.com/containerd/containerd/remotes/docker"
  20. "github.com/docker/distribution/manifest/schema2"
  21. "github.com/docker/distribution/reference"
  22. "github.com/docker/docker/api/types"
  23. "github.com/docker/docker/api/types/filters"
  24. "github.com/docker/docker/api/types/registry"
  25. "github.com/docker/docker/dockerversion"
  26. "github.com/docker/docker/errdefs"
  27. "github.com/docker/docker/pkg/authorization"
  28. "github.com/docker/docker/pkg/chrootarchive"
  29. "github.com/docker/docker/pkg/containerfs"
  30. "github.com/docker/docker/pkg/pools"
  31. "github.com/docker/docker/pkg/progress"
  32. "github.com/docker/docker/pkg/stringid"
  33. v2 "github.com/docker/docker/plugin/v2"
  34. "github.com/moby/sys/mount"
  35. "github.com/opencontainers/go-digest"
  36. ocispec "github.com/opencontainers/image-spec/specs-go/v1"
  37. "github.com/pkg/errors"
  38. "github.com/sirupsen/logrus"
  39. )
  40. var acceptedPluginFilterTags = map[string]bool{
  41. "enabled": true,
  42. "capability": true,
  43. }
  44. // Disable deactivates a plugin. This means resources (volumes, networks) cant use them.
  45. func (pm *Manager) Disable(refOrID string, config *types.PluginDisableConfig) error {
  46. p, err := pm.config.Store.GetV2Plugin(refOrID)
  47. if err != nil {
  48. return err
  49. }
  50. pm.mu.RLock()
  51. c := pm.cMap[p]
  52. pm.mu.RUnlock()
  53. if !config.ForceDisable && p.GetRefCount() > 0 {
  54. return errors.WithStack(inUseError(p.Name()))
  55. }
  56. for _, typ := range p.GetTypes() {
  57. if typ.Capability == authorization.AuthZApiImplements {
  58. pm.config.AuthzMiddleware.RemovePlugin(p.Name())
  59. }
  60. }
  61. if err := pm.disable(p, c); err != nil {
  62. return err
  63. }
  64. pm.publisher.Publish(EventDisable{Plugin: p.PluginObj})
  65. pm.config.LogPluginEvent(p.GetID(), refOrID, "disable")
  66. return nil
  67. }
  68. // Enable activates a plugin, which implies that they are ready to be used by containers.
  69. func (pm *Manager) Enable(refOrID string, config *types.PluginEnableConfig) error {
  70. p, err := pm.config.Store.GetV2Plugin(refOrID)
  71. if err != nil {
  72. return err
  73. }
  74. c := &controller{timeoutInSecs: config.Timeout}
  75. if err := pm.enable(p, c, false); err != nil {
  76. return err
  77. }
  78. pm.publisher.Publish(EventEnable{Plugin: p.PluginObj})
  79. pm.config.LogPluginEvent(p.GetID(), refOrID, "enable")
  80. return nil
  81. }
  82. // Inspect examines a plugin config
  83. func (pm *Manager) Inspect(refOrID string) (tp *types.Plugin, err error) {
  84. p, err := pm.config.Store.GetV2Plugin(refOrID)
  85. if err != nil {
  86. return nil, err
  87. }
  88. return &p.PluginObj, nil
  89. }
  90. func computePrivileges(c types.PluginConfig) types.PluginPrivileges {
  91. var privileges types.PluginPrivileges
  92. if c.Network.Type != "null" && c.Network.Type != "bridge" && c.Network.Type != "" {
  93. privileges = append(privileges, types.PluginPrivilege{
  94. Name: "network",
  95. Description: "permissions to access a network",
  96. Value: []string{c.Network.Type},
  97. })
  98. }
  99. if c.IpcHost {
  100. privileges = append(privileges, types.PluginPrivilege{
  101. Name: "host ipc namespace",
  102. Description: "allow access to host ipc namespace",
  103. Value: []string{"true"},
  104. })
  105. }
  106. if c.PidHost {
  107. privileges = append(privileges, types.PluginPrivilege{
  108. Name: "host pid namespace",
  109. Description: "allow access to host pid namespace",
  110. Value: []string{"true"},
  111. })
  112. }
  113. for _, mnt := range c.Mounts {
  114. if mnt.Source != nil {
  115. privileges = append(privileges, types.PluginPrivilege{
  116. Name: "mount",
  117. Description: "host path to mount",
  118. Value: []string{*mnt.Source},
  119. })
  120. }
  121. }
  122. for _, device := range c.Linux.Devices {
  123. if device.Path != nil {
  124. privileges = append(privileges, types.PluginPrivilege{
  125. Name: "device",
  126. Description: "host device to access",
  127. Value: []string{*device.Path},
  128. })
  129. }
  130. }
  131. if c.Linux.AllowAllDevices {
  132. privileges = append(privileges, types.PluginPrivilege{
  133. Name: "allow-all-devices",
  134. Description: "allow 'rwm' access to all devices",
  135. Value: []string{"true"},
  136. })
  137. }
  138. if len(c.Linux.Capabilities) > 0 {
  139. privileges = append(privileges, types.PluginPrivilege{
  140. Name: "capabilities",
  141. Description: "list of additional capabilities required",
  142. Value: c.Linux.Capabilities,
  143. })
  144. }
  145. return privileges
  146. }
  147. // Privileges pulls a plugin config and computes the privileges required to install it.
  148. func (pm *Manager) Privileges(ctx context.Context, ref reference.Named, metaHeader http.Header, authConfig *registry.AuthConfig) (types.PluginPrivileges, error) {
  149. var (
  150. config types.PluginConfig
  151. configSeen bool
  152. )
  153. h := func(ctx context.Context, desc ocispec.Descriptor) ([]ocispec.Descriptor, error) {
  154. switch desc.MediaType {
  155. case schema2.MediaTypeManifest, ocispec.MediaTypeImageManifest:
  156. data, err := content.ReadBlob(ctx, pm.blobStore, desc)
  157. if err != nil {
  158. return nil, errors.Wrapf(err, "error reading image manifest from blob store for %s", ref)
  159. }
  160. var m ocispec.Manifest
  161. if err := json.Unmarshal(data, &m); err != nil {
  162. return nil, errors.Wrapf(err, "error unmarshaling image manifest for %s", ref)
  163. }
  164. return []ocispec.Descriptor{m.Config}, nil
  165. case schema2.MediaTypePluginConfig:
  166. configSeen = true
  167. data, err := content.ReadBlob(ctx, pm.blobStore, desc)
  168. if err != nil {
  169. return nil, errors.Wrapf(err, "error reading plugin config from blob store for %s", ref)
  170. }
  171. if err := json.Unmarshal(data, &config); err != nil {
  172. return nil, errors.Wrapf(err, "error unmarshaling plugin config for %s", ref)
  173. }
  174. }
  175. return nil, nil
  176. }
  177. if err := pm.fetch(ctx, ref, authConfig, progress.DiscardOutput(), metaHeader, images.HandlerFunc(h)); err != nil {
  178. return types.PluginPrivileges{}, nil
  179. }
  180. if !configSeen {
  181. return types.PluginPrivileges{}, errors.Errorf("did not find plugin config for specified reference %s", ref)
  182. }
  183. return computePrivileges(config), nil
  184. }
  185. // Upgrade upgrades a plugin
  186. //
  187. // TODO: replace reference package usage with simpler url.Parse semantics
  188. func (pm *Manager) Upgrade(ctx context.Context, ref reference.Named, name string, metaHeader http.Header, authConfig *registry.AuthConfig, privileges types.PluginPrivileges, outStream io.Writer) (err error) {
  189. p, err := pm.config.Store.GetV2Plugin(name)
  190. if err != nil {
  191. return err
  192. }
  193. if p.IsEnabled() {
  194. return errors.Wrap(enabledError(p.Name()), "plugin must be disabled before upgrading")
  195. }
  196. // revalidate because Pull is public
  197. if _, err := reference.ParseNormalizedNamed(name); err != nil {
  198. return errors.Wrapf(errdefs.InvalidParameter(err), "failed to parse %q", name)
  199. }
  200. pm.muGC.RLock()
  201. defer pm.muGC.RUnlock()
  202. tmpRootFSDir, err := os.MkdirTemp(pm.tmpDir(), ".rootfs")
  203. if err != nil {
  204. return errors.Wrap(err, "error creating tmp dir for plugin rootfs")
  205. }
  206. var md fetchMeta
  207. ctx, cancel := context.WithCancel(ctx)
  208. out, waitProgress := setupProgressOutput(outStream, cancel)
  209. defer waitProgress()
  210. if err := pm.fetch(ctx, ref, authConfig, out, metaHeader, storeFetchMetadata(&md), childrenHandler(pm.blobStore), applyLayer(pm.blobStore, tmpRootFSDir, out)); err != nil {
  211. return err
  212. }
  213. pm.config.LogPluginEvent(reference.FamiliarString(ref), name, "pull")
  214. if err := validateFetchedMetadata(md); err != nil {
  215. return err
  216. }
  217. if err := pm.upgradePlugin(p, md.config, md.manifest, md.blobs, tmpRootFSDir, &privileges); err != nil {
  218. return err
  219. }
  220. p.PluginObj.PluginReference = ref.String()
  221. return nil
  222. }
  223. // Pull pulls a plugin, check if the correct privileges are provided and install the plugin.
  224. //
  225. // TODO: replace reference package usage with simpler url.Parse semantics
  226. func (pm *Manager) Pull(ctx context.Context, ref reference.Named, name string, metaHeader http.Header, authConfig *registry.AuthConfig, privileges types.PluginPrivileges, outStream io.Writer, opts ...CreateOpt) (err error) {
  227. pm.muGC.RLock()
  228. defer pm.muGC.RUnlock()
  229. // revalidate because Pull is public
  230. nameref, err := reference.ParseNormalizedNamed(name)
  231. if err != nil {
  232. return errors.Wrapf(errdefs.InvalidParameter(err), "failed to parse %q", name)
  233. }
  234. name = reference.FamiliarString(reference.TagNameOnly(nameref))
  235. if err := pm.config.Store.validateName(name); err != nil {
  236. return errdefs.InvalidParameter(err)
  237. }
  238. tmpRootFSDir, err := os.MkdirTemp(pm.tmpDir(), ".rootfs")
  239. if err != nil {
  240. return errors.Wrap(errdefs.System(err), "error preparing upgrade")
  241. }
  242. defer os.RemoveAll(tmpRootFSDir)
  243. var md fetchMeta
  244. ctx, cancel := context.WithCancel(ctx)
  245. out, waitProgress := setupProgressOutput(outStream, cancel)
  246. defer waitProgress()
  247. if err := pm.fetch(ctx, ref, authConfig, out, metaHeader, storeFetchMetadata(&md), childrenHandler(pm.blobStore), applyLayer(pm.blobStore, tmpRootFSDir, out)); err != nil {
  248. return err
  249. }
  250. pm.config.LogPluginEvent(reference.FamiliarString(ref), name, "pull")
  251. if err := validateFetchedMetadata(md); err != nil {
  252. return err
  253. }
  254. refOpt := func(p *v2.Plugin) {
  255. p.PluginObj.PluginReference = ref.String()
  256. }
  257. optsList := make([]CreateOpt, 0, len(opts)+1)
  258. optsList = append(optsList, opts...)
  259. optsList = append(optsList, refOpt)
  260. // TODO: tmpRootFSDir is empty but should have layers in it
  261. p, err := pm.createPlugin(name, md.config, md.manifest, md.blobs, tmpRootFSDir, &privileges, optsList...)
  262. if err != nil {
  263. return err
  264. }
  265. pm.publisher.Publish(EventCreate{Plugin: p.PluginObj})
  266. return nil
  267. }
  268. // List displays the list of plugins and associated metadata.
  269. func (pm *Manager) List(pluginFilters filters.Args) ([]types.Plugin, error) {
  270. if err := pluginFilters.Validate(acceptedPluginFilterTags); err != nil {
  271. return nil, err
  272. }
  273. enabledOnly := false
  274. disabledOnly := false
  275. if pluginFilters.Contains("enabled") {
  276. enabledFilter, err := pluginFilters.GetBoolOrDefault("enabled", false)
  277. if err != nil {
  278. return nil, err
  279. }
  280. if enabledFilter {
  281. enabledOnly = true
  282. } else {
  283. disabledOnly = true
  284. }
  285. }
  286. plugins := pm.config.Store.GetAll()
  287. out := make([]types.Plugin, 0, len(plugins))
  288. next:
  289. for _, p := range plugins {
  290. if enabledOnly && !p.PluginObj.Enabled {
  291. continue
  292. }
  293. if disabledOnly && p.PluginObj.Enabled {
  294. continue
  295. }
  296. if pluginFilters.Contains("capability") {
  297. for _, f := range p.GetTypes() {
  298. if !pluginFilters.Match("capability", f.Capability) {
  299. continue next
  300. }
  301. }
  302. }
  303. out = append(out, p.PluginObj)
  304. }
  305. return out, nil
  306. }
  307. // Push pushes a plugin to the registry.
  308. func (pm *Manager) Push(ctx context.Context, name string, metaHeader http.Header, authConfig *registry.AuthConfig, outStream io.Writer) error {
  309. p, err := pm.config.Store.GetV2Plugin(name)
  310. if err != nil {
  311. return err
  312. }
  313. ref, err := reference.ParseNormalizedNamed(p.Name())
  314. if err != nil {
  315. return errors.Wrapf(err, "plugin has invalid name %v for push", p.Name())
  316. }
  317. statusTracker := docker.NewInMemoryTracker()
  318. resolver, err := pm.newResolver(ctx, statusTracker, authConfig, metaHeader, false)
  319. if err != nil {
  320. return err
  321. }
  322. pusher, err := resolver.Pusher(ctx, ref.String())
  323. if err != nil {
  324. return errors.Wrap(err, "error creating plugin pusher")
  325. }
  326. pj := newPushJobs(statusTracker)
  327. ctx, cancel := context.WithCancel(ctx)
  328. out, waitProgress := setupProgressOutput(outStream, cancel)
  329. defer waitProgress()
  330. progressHandler := images.HandlerFunc(func(ctx context.Context, desc ocispec.Descriptor) ([]ocispec.Descriptor, error) {
  331. logrus.WithField("mediaType", desc.MediaType).WithField("digest", desc.Digest.String()).Debug("Preparing to push plugin layer")
  332. id := stringid.TruncateID(desc.Digest.String())
  333. pj.add(remotes.MakeRefKey(ctx, desc), id)
  334. progress.Update(out, id, "Preparing")
  335. return nil, nil
  336. })
  337. desc, err := pm.getManifestDescriptor(ctx, p)
  338. if err != nil {
  339. return errors.Wrap(err, "error reading plugin manifest")
  340. }
  341. progress.Messagef(out, "", "The push refers to repository [%s]", reference.FamiliarName(ref))
  342. // TODO: If a layer already exists on the registry, the progress output just says "Preparing"
  343. go func() {
  344. timer := time.NewTimer(100 * time.Millisecond)
  345. defer timer.Stop()
  346. if !timer.Stop() {
  347. <-timer.C
  348. }
  349. var statuses []contentStatus
  350. for {
  351. timer.Reset(100 * time.Millisecond)
  352. select {
  353. case <-ctx.Done():
  354. return
  355. case <-timer.C:
  356. statuses = pj.status()
  357. }
  358. for _, s := range statuses {
  359. out.WriteProgress(progress.Progress{ID: s.Ref, Current: s.Offset, Total: s.Total, Action: s.Status, LastUpdate: s.Offset == s.Total})
  360. }
  361. }
  362. }()
  363. // Make sure we can authenticate the request since the auth scope for plugin repos is different than a normal repo.
  364. ctx = docker.WithScope(ctx, scope(ref, true))
  365. if err := remotes.PushContent(ctx, pusher, desc, pm.blobStore, nil, nil, func(h images.Handler) images.Handler {
  366. return images.Handlers(progressHandler, h)
  367. }); err != nil {
  368. // Try fallback to http.
  369. // This is needed because the containerd pusher will only attempt the first registry config we pass, which would
  370. // typically be https.
  371. // If there are no http-only host configs found we'll error out anyway.
  372. resolver, _ := pm.newResolver(ctx, statusTracker, authConfig, metaHeader, true)
  373. if resolver != nil {
  374. pusher, _ := resolver.Pusher(ctx, ref.String())
  375. if pusher != nil {
  376. logrus.WithField("ref", ref).Debug("Re-attmpting push with http-fallback")
  377. err2 := remotes.PushContent(ctx, pusher, desc, pm.blobStore, nil, nil, func(h images.Handler) images.Handler {
  378. return images.Handlers(progressHandler, h)
  379. })
  380. if err2 == nil {
  381. err = nil
  382. } else {
  383. logrus.WithError(err2).WithField("ref", ref).Debug("Error while attempting push with http-fallback")
  384. }
  385. }
  386. }
  387. if err != nil {
  388. return errors.Wrap(err, "error pushing plugin")
  389. }
  390. }
  391. // For blobs that already exist in the registry we need to make sure to update the progress otherwise it will just say "pending"
  392. // TODO: How to check if the layer already exists? Is it worth it?
  393. for _, j := range pj.jobs {
  394. progress.Update(out, pj.names[j], "Upload complete")
  395. }
  396. // Signal the client for content trust verification
  397. progress.Aux(out, types.PushResult{Tag: ref.(reference.Tagged).Tag(), Digest: desc.Digest.String(), Size: int(desc.Size)})
  398. return nil
  399. }
  400. // manifest wraps an OCI manifest, because...
  401. // Historically the registry does not support plugins unless the media type on the manifest is specifically schema2.MediaTypeManifest
  402. // So the OCI manifest media type is not supported.
  403. // Additionally, there is extra validation for the docker schema2 manifest than there is a mediatype set on the manifest itself
  404. // even though this is set on the descriptor
  405. // The OCI types do not have this field.
  406. type manifest struct {
  407. ocispec.Manifest
  408. MediaType string `json:"mediaType,omitempty"`
  409. }
  410. func buildManifest(ctx context.Context, s content.Manager, config digest.Digest, layers []digest.Digest) (manifest, error) {
  411. var m manifest
  412. m.MediaType = images.MediaTypeDockerSchema2Manifest
  413. m.SchemaVersion = 2
  414. configInfo, err := s.Info(ctx, config)
  415. if err != nil {
  416. return m, errors.Wrapf(err, "error reading plugin config content for digest %s", config)
  417. }
  418. m.Config = ocispec.Descriptor{
  419. MediaType: mediaTypePluginConfig,
  420. Size: configInfo.Size,
  421. Digest: configInfo.Digest,
  422. }
  423. for _, l := range layers {
  424. info, err := s.Info(ctx, l)
  425. if err != nil {
  426. return m, errors.Wrapf(err, "error fetching info for content digest %s", l)
  427. }
  428. m.Layers = append(m.Layers, ocispec.Descriptor{
  429. MediaType: images.MediaTypeDockerSchema2LayerGzip, // TODO: This is assuming everything is a gzip compressed layer, but that may not be true.
  430. Digest: l,
  431. Size: info.Size,
  432. })
  433. }
  434. return m, nil
  435. }
  436. // getManifestDescriptor gets the OCI descriptor for a manifest
  437. // It will generate a manifest if one does not exist
  438. func (pm *Manager) getManifestDescriptor(ctx context.Context, p *v2.Plugin) (ocispec.Descriptor, error) {
  439. logger := logrus.WithField("plugin", p.Name()).WithField("digest", p.Manifest)
  440. if p.Manifest != "" {
  441. info, err := pm.blobStore.Info(ctx, p.Manifest)
  442. if err == nil {
  443. desc := ocispec.Descriptor{
  444. Size: info.Size,
  445. Digest: info.Digest,
  446. MediaType: images.MediaTypeDockerSchema2Manifest,
  447. }
  448. return desc, nil
  449. }
  450. logger.WithError(err).Debug("Could not find plugin manifest in content store")
  451. } else {
  452. logger.Info("Plugin does not have manifest digest")
  453. }
  454. logger.Info("Building a new plugin manifest")
  455. manifest, err := buildManifest(ctx, pm.blobStore, p.Config, p.Blobsums)
  456. if err != nil {
  457. return ocispec.Descriptor{}, err
  458. }
  459. desc, err := writeManifest(ctx, pm.blobStore, &manifest)
  460. if err != nil {
  461. return desc, err
  462. }
  463. if err := pm.save(p); err != nil {
  464. logger.WithError(err).Error("Could not save plugin with manifest digest")
  465. }
  466. return desc, nil
  467. }
  468. func writeManifest(ctx context.Context, cs content.Store, m *manifest) (ocispec.Descriptor, error) {
  469. platform := platforms.DefaultSpec()
  470. desc := ocispec.Descriptor{
  471. MediaType: images.MediaTypeDockerSchema2Manifest,
  472. Platform: &platform,
  473. }
  474. data, err := json.Marshal(m)
  475. if err != nil {
  476. return desc, errors.Wrap(err, "error encoding manifest")
  477. }
  478. desc.Digest = digest.FromBytes(data)
  479. desc.Size = int64(len(data))
  480. if err := content.WriteBlob(ctx, cs, remotes.MakeRefKey(ctx, desc), bytes.NewReader(data), desc); err != nil {
  481. return desc, errors.Wrap(err, "error writing plugin manifest")
  482. }
  483. return desc, nil
  484. }
  485. // Remove deletes plugin's root directory.
  486. func (pm *Manager) Remove(name string, config *types.PluginRmConfig) error {
  487. p, err := pm.config.Store.GetV2Plugin(name)
  488. pm.mu.RLock()
  489. c := pm.cMap[p]
  490. pm.mu.RUnlock()
  491. if err != nil {
  492. return err
  493. }
  494. if !config.ForceRemove {
  495. if p.GetRefCount() > 0 {
  496. return inUseError(p.Name())
  497. }
  498. if p.IsEnabled() {
  499. return enabledError(p.Name())
  500. }
  501. }
  502. if p.IsEnabled() {
  503. if err := pm.disable(p, c); err != nil {
  504. logrus.Errorf("failed to disable plugin '%s': %s", p.Name(), err)
  505. }
  506. }
  507. defer func() {
  508. go pm.GC()
  509. }()
  510. id := p.GetID()
  511. pluginDir := filepath.Join(pm.config.Root, id)
  512. if err := mount.RecursiveUnmount(pluginDir); err != nil {
  513. return errors.Wrap(err, "error unmounting plugin data")
  514. }
  515. if err := atomicRemoveAll(pluginDir); err != nil {
  516. return err
  517. }
  518. pm.config.Store.Remove(p)
  519. pm.config.LogPluginEvent(id, name, "remove")
  520. pm.publisher.Publish(EventRemove{Plugin: p.PluginObj})
  521. return nil
  522. }
  523. // Set sets plugin args
  524. func (pm *Manager) Set(name string, args []string) error {
  525. p, err := pm.config.Store.GetV2Plugin(name)
  526. if err != nil {
  527. return err
  528. }
  529. if err := p.Set(args); err != nil {
  530. return err
  531. }
  532. return pm.save(p)
  533. }
  534. // CreateFromContext creates a plugin from the given pluginDir which contains
  535. // both the rootfs and the config.json and a repoName with optional tag.
  536. func (pm *Manager) CreateFromContext(ctx context.Context, tarCtx io.ReadCloser, options *types.PluginCreateOptions) (err error) {
  537. pm.muGC.RLock()
  538. defer pm.muGC.RUnlock()
  539. ref, err := reference.ParseNormalizedNamed(options.RepoName)
  540. if err != nil {
  541. return errors.Wrapf(err, "failed to parse reference %v", options.RepoName)
  542. }
  543. if _, ok := ref.(reference.Canonical); ok {
  544. return errors.Errorf("canonical references are not permitted")
  545. }
  546. name := reference.FamiliarString(reference.TagNameOnly(ref))
  547. if err := pm.config.Store.validateName(name); err != nil { // fast check, real check is in createPlugin()
  548. return err
  549. }
  550. tmpRootFSDir, err := os.MkdirTemp(pm.tmpDir(), ".rootfs")
  551. if err != nil {
  552. return errors.Wrap(err, "failed to create temp directory")
  553. }
  554. defer os.RemoveAll(tmpRootFSDir)
  555. var configJSON []byte
  556. rootFS := splitConfigRootFSFromTar(tarCtx, &configJSON)
  557. rootFSBlob, err := pm.blobStore.Writer(ctx, content.WithRef(name))
  558. if err != nil {
  559. return err
  560. }
  561. defer rootFSBlob.Close()
  562. gzw := gzip.NewWriter(rootFSBlob)
  563. rootFSReader := io.TeeReader(rootFS, gzw)
  564. if err := chrootarchive.Untar(rootFSReader, tmpRootFSDir, nil); err != nil {
  565. return err
  566. }
  567. if err := rootFS.Close(); err != nil {
  568. return err
  569. }
  570. if configJSON == nil {
  571. return errors.New("config not found")
  572. }
  573. if err := gzw.Close(); err != nil {
  574. return errors.Wrap(err, "error closing gzip writer")
  575. }
  576. var config types.PluginConfig
  577. if err := json.Unmarshal(configJSON, &config); err != nil {
  578. return errors.Wrap(err, "failed to parse config")
  579. }
  580. if err := pm.validateConfig(config); err != nil {
  581. return err
  582. }
  583. pm.mu.Lock()
  584. defer pm.mu.Unlock()
  585. if err := rootFSBlob.Commit(ctx, 0, ""); err != nil {
  586. return err
  587. }
  588. defer func() {
  589. if err != nil {
  590. go pm.GC()
  591. }
  592. }()
  593. config.Rootfs = &types.PluginConfigRootfs{
  594. Type: "layers",
  595. DiffIds: []string{rootFSBlob.Digest().String()},
  596. }
  597. config.DockerVersion = dockerversion.Version
  598. configBlob, err := pm.blobStore.Writer(ctx, content.WithRef(name+"-config.json"))
  599. if err != nil {
  600. return err
  601. }
  602. defer configBlob.Close()
  603. if err := json.NewEncoder(configBlob).Encode(config); err != nil {
  604. return errors.Wrap(err, "error encoding json config")
  605. }
  606. if err := configBlob.Commit(ctx, 0, ""); err != nil {
  607. return err
  608. }
  609. configDigest := configBlob.Digest()
  610. layers := []digest.Digest{rootFSBlob.Digest()}
  611. manifest, err := buildManifest(ctx, pm.blobStore, configDigest, layers)
  612. if err != nil {
  613. return err
  614. }
  615. desc, err := writeManifest(ctx, pm.blobStore, &manifest)
  616. if err != nil {
  617. return
  618. }
  619. p, err := pm.createPlugin(name, configDigest, desc.Digest, layers, tmpRootFSDir, nil)
  620. if err != nil {
  621. return err
  622. }
  623. p.PluginObj.PluginReference = name
  624. pm.publisher.Publish(EventCreate{Plugin: p.PluginObj})
  625. pm.config.LogPluginEvent(p.PluginObj.ID, name, "create")
  626. return nil
  627. }
  628. func (pm *Manager) validateConfig(config types.PluginConfig) error {
  629. return nil // TODO:
  630. }
  631. func splitConfigRootFSFromTar(in io.ReadCloser, config *[]byte) io.ReadCloser {
  632. pr, pw := io.Pipe()
  633. go func() {
  634. tarReader := tar.NewReader(in)
  635. tarWriter := tar.NewWriter(pw)
  636. defer in.Close()
  637. hasRootFS := false
  638. for {
  639. hdr, err := tarReader.Next()
  640. if err == io.EOF {
  641. if !hasRootFS {
  642. pw.CloseWithError(errors.Wrap(err, "no rootfs found"))
  643. return
  644. }
  645. // Signals end of archive.
  646. tarWriter.Close()
  647. pw.Close()
  648. return
  649. }
  650. if err != nil {
  651. pw.CloseWithError(errors.Wrap(err, "failed to read from tar"))
  652. return
  653. }
  654. content := io.Reader(tarReader)
  655. name := path.Clean(hdr.Name)
  656. if path.IsAbs(name) {
  657. name = name[1:]
  658. }
  659. if name == configFileName {
  660. dt, err := io.ReadAll(content)
  661. if err != nil {
  662. pw.CloseWithError(errors.Wrapf(err, "failed to read %s", configFileName))
  663. return
  664. }
  665. *config = dt
  666. }
  667. if parts := strings.Split(name, "/"); len(parts) != 0 && parts[0] == rootFSFileName {
  668. hdr.Name = path.Clean(path.Join(parts[1:]...))
  669. if hdr.Typeflag == tar.TypeLink && strings.HasPrefix(strings.ToLower(hdr.Linkname), rootFSFileName+"/") {
  670. hdr.Linkname = hdr.Linkname[len(rootFSFileName)+1:]
  671. }
  672. if err := tarWriter.WriteHeader(hdr); err != nil {
  673. pw.CloseWithError(errors.Wrap(err, "error writing tar header"))
  674. return
  675. }
  676. if _, err := pools.Copy(tarWriter, content); err != nil {
  677. pw.CloseWithError(errors.Wrap(err, "error copying tar data"))
  678. return
  679. }
  680. hasRootFS = true
  681. } else {
  682. io.Copy(io.Discard, content)
  683. }
  684. }
  685. }()
  686. return pr
  687. }
  688. func atomicRemoveAll(dir string) error {
  689. renamed := dir + "-removing"
  690. err := os.Rename(dir, renamed)
  691. switch {
  692. case os.IsNotExist(err), err == nil:
  693. // even if `dir` doesn't exist, we can still try and remove `renamed`
  694. case os.IsExist(err):
  695. // Some previous remove failed, check if the origin dir exists
  696. if e := containerfs.EnsureRemoveAll(renamed); e != nil {
  697. return errors.Wrap(err, "rename target already exists and could not be removed")
  698. }
  699. if _, err := os.Stat(dir); os.IsNotExist(err) {
  700. // origin doesn't exist, nothing left to do
  701. return nil
  702. }
  703. // attempt to rename again
  704. if err := os.Rename(dir, renamed); err != nil {
  705. return errors.Wrap(err, "failed to rename dir for atomic removal")
  706. }
  707. default:
  708. return errors.Wrap(err, "failed to rename dir for atomic removal")
  709. }
  710. if err := containerfs.EnsureRemoveAll(renamed); err != nil {
  711. os.Rename(renamed, dir)
  712. return err
  713. }
  714. return nil
  715. }