backend_linux.go 24 KB

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