backend_linux.go 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828
  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. specs "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 specs.Descriptor) ([]specs.Descriptor, error) {
  154. switch desc.MediaType {
  155. case schema2.MediaTypeManifest, specs.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 specs.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 []specs.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. if pluginFilters.ExactMatch("enabled", "true") {
  277. enabledOnly = true
  278. } else if pluginFilters.ExactMatch("enabled", "false") {
  279. disabledOnly = true
  280. } else {
  281. return nil, invalidFilter{"enabled", pluginFilters.Get("enabled")}
  282. }
  283. }
  284. plugins := pm.config.Store.GetAll()
  285. out := make([]types.Plugin, 0, len(plugins))
  286. next:
  287. for _, p := range plugins {
  288. if enabledOnly && !p.PluginObj.Enabled {
  289. continue
  290. }
  291. if disabledOnly && p.PluginObj.Enabled {
  292. continue
  293. }
  294. if pluginFilters.Contains("capability") {
  295. for _, f := range p.GetTypes() {
  296. if !pluginFilters.Match("capability", f.Capability) {
  297. continue next
  298. }
  299. }
  300. }
  301. out = append(out, p.PluginObj)
  302. }
  303. return out, nil
  304. }
  305. // Push pushes a plugin to the registry.
  306. func (pm *Manager) Push(ctx context.Context, name string, metaHeader http.Header, authConfig *registry.AuthConfig, outStream io.Writer) error {
  307. p, err := pm.config.Store.GetV2Plugin(name)
  308. if err != nil {
  309. return err
  310. }
  311. ref, err := reference.ParseNormalizedNamed(p.Name())
  312. if err != nil {
  313. return errors.Wrapf(err, "plugin has invalid name %v for push", p.Name())
  314. }
  315. statusTracker := docker.NewInMemoryTracker()
  316. resolver, err := pm.newResolver(ctx, statusTracker, authConfig, metaHeader, false)
  317. if err != nil {
  318. return err
  319. }
  320. pusher, err := resolver.Pusher(ctx, ref.String())
  321. if err != nil {
  322. return errors.Wrap(err, "error creating plugin pusher")
  323. }
  324. pj := newPushJobs(statusTracker)
  325. ctx, cancel := context.WithCancel(ctx)
  326. out, waitProgress := setupProgressOutput(outStream, cancel)
  327. defer waitProgress()
  328. progressHandler := images.HandlerFunc(func(ctx context.Context, desc specs.Descriptor) ([]specs.Descriptor, error) {
  329. logrus.WithField("mediaType", desc.MediaType).WithField("digest", desc.Digest.String()).Debug("Preparing to push plugin layer")
  330. id := stringid.TruncateID(desc.Digest.String())
  331. pj.add(remotes.MakeRefKey(ctx, desc), id)
  332. progress.Update(out, id, "Preparing")
  333. return nil, nil
  334. })
  335. desc, err := pm.getManifestDescriptor(ctx, p)
  336. if err != nil {
  337. return errors.Wrap(err, "error reading plugin manifest")
  338. }
  339. progress.Messagef(out, "", "The push refers to repository [%s]", reference.FamiliarName(ref))
  340. // TODO: If a layer already exists on the registry, the progress output just says "Preparing"
  341. go func() {
  342. timer := time.NewTimer(100 * time.Millisecond)
  343. defer timer.Stop()
  344. if !timer.Stop() {
  345. <-timer.C
  346. }
  347. var statuses []contentStatus
  348. for {
  349. timer.Reset(100 * time.Millisecond)
  350. select {
  351. case <-ctx.Done():
  352. return
  353. case <-timer.C:
  354. statuses = pj.status()
  355. }
  356. for _, s := range statuses {
  357. out.WriteProgress(progress.Progress{ID: s.Ref, Current: s.Offset, Total: s.Total, Action: s.Status, LastUpdate: s.Offset == s.Total})
  358. }
  359. }
  360. }()
  361. // Make sure we can authenticate the request since the auth scope for plugin repos is different than a normal repo.
  362. ctx = docker.WithScope(ctx, scope(ref, true))
  363. if err := remotes.PushContent(ctx, pusher, desc, pm.blobStore, nil, nil, func(h images.Handler) images.Handler {
  364. return images.Handlers(progressHandler, h)
  365. }); err != nil {
  366. // Try fallback to http.
  367. // This is needed because the containerd pusher will only attempt the first registry config we pass, which would
  368. // typically be https.
  369. // If there are no http-only host configs found we'll error out anyway.
  370. resolver, _ := pm.newResolver(ctx, statusTracker, authConfig, metaHeader, true)
  371. if resolver != nil {
  372. pusher, _ := resolver.Pusher(ctx, ref.String())
  373. if pusher != nil {
  374. logrus.WithField("ref", ref).Debug("Re-attmpting push with http-fallback")
  375. err2 := remotes.PushContent(ctx, pusher, desc, pm.blobStore, nil, nil, func(h images.Handler) images.Handler {
  376. return images.Handlers(progressHandler, h)
  377. })
  378. if err2 == nil {
  379. err = nil
  380. } else {
  381. logrus.WithError(err2).WithField("ref", ref).Debug("Error while attempting push with http-fallback")
  382. }
  383. }
  384. }
  385. if err != nil {
  386. return errors.Wrap(err, "error pushing plugin")
  387. }
  388. }
  389. // For blobs that already exist in the registry we need to make sure to update the progress otherwise it will just say "pending"
  390. // TODO: How to check if the layer already exists? Is it worth it?
  391. for _, j := range pj.jobs {
  392. progress.Update(out, pj.names[j], "Upload complete")
  393. }
  394. // Signal the client for content trust verification
  395. progress.Aux(out, types.PushResult{Tag: ref.(reference.Tagged).Tag(), Digest: desc.Digest.String(), Size: int(desc.Size)})
  396. return nil
  397. }
  398. // manifest wraps an OCI manifest, because...
  399. // Historically the registry does not support plugins unless the media type on the manifest is specifically schema2.MediaTypeManifest
  400. // So the OCI manifest media type is not supported.
  401. // Additionally, there is extra validation for the docker schema2 manifest than there is a mediatype set on the manifest itself
  402. // even though this is set on the descriptor
  403. // The OCI types do not have this field.
  404. type manifest struct {
  405. specs.Manifest
  406. MediaType string `json:"mediaType,omitempty"`
  407. }
  408. func buildManifest(ctx context.Context, s content.Manager, config digest.Digest, layers []digest.Digest) (manifest, error) {
  409. var m manifest
  410. m.MediaType = images.MediaTypeDockerSchema2Manifest
  411. m.SchemaVersion = 2
  412. configInfo, err := s.Info(ctx, config)
  413. if err != nil {
  414. return m, errors.Wrapf(err, "error reading plugin config content for digest %s", config)
  415. }
  416. m.Config = specs.Descriptor{
  417. MediaType: mediaTypePluginConfig,
  418. Size: configInfo.Size,
  419. Digest: configInfo.Digest,
  420. }
  421. for _, l := range layers {
  422. info, err := s.Info(ctx, l)
  423. if err != nil {
  424. return m, errors.Wrapf(err, "error fetching info for content digest %s", l)
  425. }
  426. m.Layers = append(m.Layers, specs.Descriptor{
  427. MediaType: images.MediaTypeDockerSchema2LayerGzip, // TODO: This is assuming everything is a gzip compressed layer, but that may not be true.
  428. Digest: l,
  429. Size: info.Size,
  430. })
  431. }
  432. return m, nil
  433. }
  434. // getManifestDescriptor gets the OCI descriptor for a manifest
  435. // It will generate a manifest if one does not exist
  436. func (pm *Manager) getManifestDescriptor(ctx context.Context, p *v2.Plugin) (specs.Descriptor, error) {
  437. logger := logrus.WithField("plugin", p.Name()).WithField("digest", p.Manifest)
  438. if p.Manifest != "" {
  439. info, err := pm.blobStore.Info(ctx, p.Manifest)
  440. if err == nil {
  441. desc := specs.Descriptor{
  442. Size: info.Size,
  443. Digest: info.Digest,
  444. MediaType: images.MediaTypeDockerSchema2Manifest,
  445. }
  446. return desc, nil
  447. }
  448. logger.WithError(err).Debug("Could not find plugin manifest in content store")
  449. } else {
  450. logger.Info("Plugin does not have manifest digest")
  451. }
  452. logger.Info("Building a new plugin manifest")
  453. manifest, err := buildManifest(ctx, pm.blobStore, p.Config, p.Blobsums)
  454. if err != nil {
  455. return specs.Descriptor{}, err
  456. }
  457. desc, err := writeManifest(ctx, pm.blobStore, &manifest)
  458. if err != nil {
  459. return desc, err
  460. }
  461. if err := pm.save(p); err != nil {
  462. logger.WithError(err).Error("Could not save plugin with manifest digest")
  463. }
  464. return desc, nil
  465. }
  466. func writeManifest(ctx context.Context, cs content.Store, m *manifest) (specs.Descriptor, error) {
  467. platform := platforms.DefaultSpec()
  468. desc := specs.Descriptor{
  469. MediaType: images.MediaTypeDockerSchema2Manifest,
  470. Platform: &platform,
  471. }
  472. data, err := json.Marshal(m)
  473. if err != nil {
  474. return desc, errors.Wrap(err, "error encoding manifest")
  475. }
  476. desc.Digest = digest.FromBytes(data)
  477. desc.Size = int64(len(data))
  478. if err := content.WriteBlob(ctx, cs, remotes.MakeRefKey(ctx, desc), bytes.NewReader(data), desc); err != nil {
  479. return desc, errors.Wrap(err, "error writing plugin manifest")
  480. }
  481. return desc, nil
  482. }
  483. // Remove deletes plugin's root directory.
  484. func (pm *Manager) Remove(name string, config *types.PluginRmConfig) error {
  485. p, err := pm.config.Store.GetV2Plugin(name)
  486. pm.mu.RLock()
  487. c := pm.cMap[p]
  488. pm.mu.RUnlock()
  489. if err != nil {
  490. return err
  491. }
  492. if !config.ForceRemove {
  493. if p.GetRefCount() > 0 {
  494. return inUseError(p.Name())
  495. }
  496. if p.IsEnabled() {
  497. return enabledError(p.Name())
  498. }
  499. }
  500. if p.IsEnabled() {
  501. if err := pm.disable(p, c); err != nil {
  502. logrus.Errorf("failed to disable plugin '%s': %s", p.Name(), err)
  503. }
  504. }
  505. defer func() {
  506. go pm.GC()
  507. }()
  508. id := p.GetID()
  509. pluginDir := filepath.Join(pm.config.Root, id)
  510. if err := mount.RecursiveUnmount(pluginDir); err != nil {
  511. return errors.Wrap(err, "error unmounting plugin data")
  512. }
  513. if err := atomicRemoveAll(pluginDir); err != nil {
  514. return err
  515. }
  516. pm.config.Store.Remove(p)
  517. pm.config.LogPluginEvent(id, name, "remove")
  518. pm.publisher.Publish(EventRemove{Plugin: p.PluginObj})
  519. return nil
  520. }
  521. // Set sets plugin args
  522. func (pm *Manager) Set(name string, args []string) error {
  523. p, err := pm.config.Store.GetV2Plugin(name)
  524. if err != nil {
  525. return err
  526. }
  527. if err := p.Set(args); err != nil {
  528. return err
  529. }
  530. return pm.save(p)
  531. }
  532. // CreateFromContext creates a plugin from the given pluginDir which contains
  533. // both the rootfs and the config.json and a repoName with optional tag.
  534. func (pm *Manager) CreateFromContext(ctx context.Context, tarCtx io.ReadCloser, options *types.PluginCreateOptions) (err error) {
  535. pm.muGC.RLock()
  536. defer pm.muGC.RUnlock()
  537. ref, err := reference.ParseNormalizedNamed(options.RepoName)
  538. if err != nil {
  539. return errors.Wrapf(err, "failed to parse reference %v", options.RepoName)
  540. }
  541. if _, ok := ref.(reference.Canonical); ok {
  542. return errors.Errorf("canonical references are not permitted")
  543. }
  544. name := reference.FamiliarString(reference.TagNameOnly(ref))
  545. if err := pm.config.Store.validateName(name); err != nil { // fast check, real check is in createPlugin()
  546. return err
  547. }
  548. tmpRootFSDir, err := os.MkdirTemp(pm.tmpDir(), ".rootfs")
  549. if err != nil {
  550. return errors.Wrap(err, "failed to create temp directory")
  551. }
  552. defer os.RemoveAll(tmpRootFSDir)
  553. var configJSON []byte
  554. rootFS := splitConfigRootFSFromTar(tarCtx, &configJSON)
  555. rootFSBlob, err := pm.blobStore.Writer(ctx, content.WithRef(name))
  556. if err != nil {
  557. return err
  558. }
  559. defer rootFSBlob.Close()
  560. gzw := gzip.NewWriter(rootFSBlob)
  561. rootFSReader := io.TeeReader(rootFS, gzw)
  562. if err := chrootarchive.Untar(rootFSReader, tmpRootFSDir, nil); err != nil {
  563. return err
  564. }
  565. if err := rootFS.Close(); err != nil {
  566. return err
  567. }
  568. if configJSON == nil {
  569. return errors.New("config not found")
  570. }
  571. if err := gzw.Close(); err != nil {
  572. return errors.Wrap(err, "error closing gzip writer")
  573. }
  574. var config types.PluginConfig
  575. if err := json.Unmarshal(configJSON, &config); err != nil {
  576. return errors.Wrap(err, "failed to parse config")
  577. }
  578. if err := pm.validateConfig(config); err != nil {
  579. return err
  580. }
  581. pm.mu.Lock()
  582. defer pm.mu.Unlock()
  583. if err := rootFSBlob.Commit(ctx, 0, ""); err != nil {
  584. return err
  585. }
  586. defer func() {
  587. if err != nil {
  588. go pm.GC()
  589. }
  590. }()
  591. config.Rootfs = &types.PluginConfigRootfs{
  592. Type: "layers",
  593. DiffIds: []string{rootFSBlob.Digest().String()},
  594. }
  595. config.DockerVersion = dockerversion.Version
  596. configBlob, err := pm.blobStore.Writer(ctx, content.WithRef(name+"-config.json"))
  597. if err != nil {
  598. return err
  599. }
  600. defer configBlob.Close()
  601. if err := json.NewEncoder(configBlob).Encode(config); err != nil {
  602. return errors.Wrap(err, "error encoding json config")
  603. }
  604. if err := configBlob.Commit(ctx, 0, ""); err != nil {
  605. return err
  606. }
  607. configDigest := configBlob.Digest()
  608. layers := []digest.Digest{rootFSBlob.Digest()}
  609. manifest, err := buildManifest(ctx, pm.blobStore, configDigest, layers)
  610. if err != nil {
  611. return err
  612. }
  613. desc, err := writeManifest(ctx, pm.blobStore, &manifest)
  614. if err != nil {
  615. return
  616. }
  617. p, err := pm.createPlugin(name, configDigest, desc.Digest, layers, tmpRootFSDir, nil)
  618. if err != nil {
  619. return err
  620. }
  621. p.PluginObj.PluginReference = name
  622. pm.publisher.Publish(EventCreate{Plugin: p.PluginObj})
  623. pm.config.LogPluginEvent(p.PluginObj.ID, name, "create")
  624. return nil
  625. }
  626. func (pm *Manager) validateConfig(config types.PluginConfig) error {
  627. return nil // TODO:
  628. }
  629. func splitConfigRootFSFromTar(in io.ReadCloser, config *[]byte) io.ReadCloser {
  630. pr, pw := io.Pipe()
  631. go func() {
  632. tarReader := tar.NewReader(in)
  633. tarWriter := tar.NewWriter(pw)
  634. defer in.Close()
  635. hasRootFS := false
  636. for {
  637. hdr, err := tarReader.Next()
  638. if err == io.EOF {
  639. if !hasRootFS {
  640. pw.CloseWithError(errors.Wrap(err, "no rootfs found"))
  641. return
  642. }
  643. // Signals end of archive.
  644. tarWriter.Close()
  645. pw.Close()
  646. return
  647. }
  648. if err != nil {
  649. pw.CloseWithError(errors.Wrap(err, "failed to read from tar"))
  650. return
  651. }
  652. content := io.Reader(tarReader)
  653. name := path.Clean(hdr.Name)
  654. if path.IsAbs(name) {
  655. name = name[1:]
  656. }
  657. if name == configFileName {
  658. dt, err := io.ReadAll(content)
  659. if err != nil {
  660. pw.CloseWithError(errors.Wrapf(err, "failed to read %s", configFileName))
  661. return
  662. }
  663. *config = dt
  664. }
  665. if parts := strings.Split(name, "/"); len(parts) != 0 && parts[0] == rootFSFileName {
  666. hdr.Name = path.Clean(path.Join(parts[1:]...))
  667. if hdr.Typeflag == tar.TypeLink && strings.HasPrefix(strings.ToLower(hdr.Linkname), rootFSFileName+"/") {
  668. hdr.Linkname = hdr.Linkname[len(rootFSFileName)+1:]
  669. }
  670. if err := tarWriter.WriteHeader(hdr); err != nil {
  671. pw.CloseWithError(errors.Wrap(err, "error writing tar header"))
  672. return
  673. }
  674. if _, err := pools.Copy(tarWriter, content); err != nil {
  675. pw.CloseWithError(errors.Wrap(err, "error copying tar data"))
  676. return
  677. }
  678. hasRootFS = true
  679. } else {
  680. io.Copy(io.Discard, content)
  681. }
  682. }
  683. }()
  684. return pr
  685. }
  686. func atomicRemoveAll(dir string) error {
  687. renamed := dir + "-removing"
  688. err := os.Rename(dir, renamed)
  689. switch {
  690. case os.IsNotExist(err), err == nil:
  691. // even if `dir` doesn't exist, we can still try and remove `renamed`
  692. case os.IsExist(err):
  693. // Some previous remove failed, check if the origin dir exists
  694. if e := containerfs.EnsureRemoveAll(renamed); e != nil {
  695. return errors.Wrap(err, "rename target already exists and could not be removed")
  696. }
  697. if _, err := os.Stat(dir); os.IsNotExist(err) {
  698. // origin doesn't exist, nothing left to do
  699. return nil
  700. }
  701. // attempt to rename again
  702. if err := os.Rename(dir, renamed); err != nil {
  703. return errors.Wrap(err, "failed to rename dir for atomic removal")
  704. }
  705. default:
  706. return errors.Wrap(err, "failed to rename dir for atomic removal")
  707. }
  708. if err := containerfs.EnsureRemoveAll(renamed); err != nil {
  709. os.Rename(renamed, dir)
  710. return err
  711. }
  712. return nil
  713. }