backend_linux.go 24 KB

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