pax_global_header00006660000000000000000000000064147052770510014522gustar00rootroot0000000000000052 comment=19cedbf730bb9ae1c106c4d4df8492bb3d3fb8fd plugin-1.0.0/000077500000000000000000000000001470527705100130165ustar00rootroot00000000000000plugin-1.0.0/.github/000077500000000000000000000000001470527705100143565ustar00rootroot00000000000000plugin-1.0.0/.github/workflows/000077500000000000000000000000001470527705100164135ustar00rootroot00000000000000plugin-1.0.0/.github/workflows/ci.yml000066400000000000000000000043311470527705100175320ustar00rootroot00000000000000name: CI on: push: branches: [ main ] pull_request: branches: [ main ] env: # Go version we currently use to build containerd across all CI. # Note: don't forget to update `Binaries` step, as it contains the matrix of all supported Go versions. GO_VERSION: "1.22.8" permissions: # added using https://github.com/step-security/secure-workflows contents: read jobs: # # golangci-lint # linters: permissions: contents: read # for actions/checkout to fetch code pull-requests: read # for golangci/golangci-lint-action to fetch pull requests name: Linters runs-on: ${{ matrix.os }} timeout-minutes: 10 strategy: matrix: os: [ubuntu-22.04, macos-13] # TODO: Add windows-2019 steps: - uses: actions/setup-go@v5 with: go-version: ${{ env.GO_VERSION }} cache: false # see actions/setup-go#368 - uses: actions/checkout@v4 - uses: golangci/golangci-lint-action@v6 with: version: v1.61.0 skip-cache: true args: --timeout=5m # # Project checks # project: name: Project Checks if: github.repository == 'containerd/plugin' runs-on: ubuntu-22.04 timeout-minutes: 5 steps: - uses: actions/setup-go@v5 with: go-version: ${{ env.GO_VERSION }} cache: false # see actions/setup-go#368 - uses: actions/checkout@v4 with: path: src/github.com/containerd/plugin fetch-depth: 25 - uses: containerd/project-checks@v1.1.0 with: working-directory: src/github.com/containerd/plugin repo-access-token: ${{ secrets.GITHUB_TOKEN }} tests: name: Tests runs-on: ubuntu-22.04 timeout-minutes: 5 steps: - uses: actions/checkout@v4 with: path: src/github.com/containerd/plugin - uses: actions/setup-go@v5 with: go-version: ${{ env.GO_VERSION }} - name: Set env shell: bash run: | echo "GOPATH=${{ github.workspace }}" >> $GITHUB_ENV echo "${{ github.workspace }}/bin" >> $GITHUB_PATH - run: | go test -v -race working-directory: src/github.com/containerd/plugin plugin-1.0.0/.golangci.yml000066400000000000000000000010101470527705100153720ustar00rootroot00000000000000linters: enable: - copyloopvar - gofmt - goimports - gosec - ineffassign - misspell - nolintlint - revive - staticcheck - tenv # Detects using os.Setenv instead of t.Setenv since Go 1.17 - unconvert - unused - govet - dupword # Checks for duplicate words in the source code disable: - errcheck run: timeout: 5m issues: exclude-dirs: - api - cluster - design - docs - docs/man - releases - reports - test # e2e scripts plugin-1.0.0/LICENSE000066400000000000000000000250151470527705100140260ustar00rootroot00000000000000 Apache License Version 2.0, January 2004 https://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS Copyright The containerd Authors Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at https://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. plugin-1.0.0/README.md000066400000000000000000000020551470527705100142770ustar00rootroot00000000000000# plugin A Go package providing a common plugin interface across containerd repositories. This package is intended to be imported by the main containerd repository as well as plugin implementations. By sharing a common implementations, plugins can register themselves without needing to import the main containerd repository. This plugin is intended to provide an interface and common functionality, but is not intended to define plugin types used by containerd. Plugins should copy plugin type strings to avoid creating unintended depdenencies. ## Project details **plugin** is a containerd sub-project, licensed under the [Apache 2.0 license](./LICENSE). As a containerd sub-project, you will find the: * [Project governance](https://github.com/containerd/project/blob/main/GOVERNANCE.md), * [Maintainers](https://github.com/containerd/project/blob/main/MAINTAINERS), * and [Contributing guidelines](https://github.com/containerd/project/blob/main/CONTRIBUTING.md) information in our [`containerd/project`](https://github.com/containerd/project) repository. plugin-1.0.0/context.go000066400000000000000000000125331470527705100150350ustar00rootroot00000000000000/* Copyright The containerd Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package plugin import ( "context" "fmt" imagespec "github.com/opencontainers/image-spec/specs-go/v1" ) // InitContext is used for plugin initialization type InitContext struct { Context context.Context Properties map[string]string Config interface{} RegisterReadiness func() func() // Meta is metadata plugins can fill in at init Meta *Meta plugins *Set } // NewContext returns a new plugin InitContext func NewContext(ctx context.Context, plugins *Set, properties map[string]string) *InitContext { if properties == nil { properties = map[string]string{} } return &InitContext{ Context: ctx, Properties: properties, Meta: &Meta{ Exports: map[string]string{}, }, plugins: plugins, } } // Meta contains information gathered from the registration and initialization // process. type Meta struct { Platforms []imagespec.Platform // platforms supported by plugin Exports map[string]string // values exported by plugin Capabilities []string // feature switches for plugin } // Plugin represents an initialized plugin, used with an init context. type Plugin struct { Registration Registration // registration, as initialized Config interface{} // config, as initialized Meta Meta instance interface{} err error // will be set if there was an error initializing the plugin } // Err returns the errors during initialization. // returns nil if no error was encountered func (p *Plugin) Err() error { return p.err } // Instance returns the instance and any initialization error of the plugin func (p *Plugin) Instance() (interface{}, error) { return p.instance, p.err } // Set defines a plugin collection, used with InitContext. // // This maintains ordering and unique indexing over the set. // // After iteratively instantiating plugins, this set should represent, the // ordered, initialization set of plugins for a containerd instance. type Set struct { ordered []*Plugin // order of initialization byTypeAndID map[Type]map[string]*Plugin } // NewPluginSet returns an initialized plugin set func NewPluginSet() *Set { return &Set{ byTypeAndID: make(map[Type]map[string]*Plugin), } } // Add a plugin to the set func (ps *Set) Add(p *Plugin) error { if byID, typeok := ps.byTypeAndID[p.Registration.Type]; !typeok { ps.byTypeAndID[p.Registration.Type] = map[string]*Plugin{ p.Registration.ID: p, } } else if _, idok := byID[p.Registration.ID]; !idok { byID[p.Registration.ID] = p } else { return fmt.Errorf("plugin add failed for %s: %w", p.Registration.URI(), ErrPluginInitialized) } ps.ordered = append(ps.ordered, p) return nil } // Get returns the plugin with the given type and id func (ps *Set) Get(t Type, id string) *Plugin { p, ok := ps.byTypeAndID[t] if !ok { return nil } return p[id] } // GetAll returns all initialized plugins func (ps *Set) GetAll() []*Plugin { return ps.ordered } // GetSingle returns a plugin instance of the given type when only a single instance // of that type is expected. Throws an ErrPluginNotFound if no plugin is found and // ErrPluginMultipleInstances when multiple instances are found. // Since plugins are not ordered, if multiple instances is suported then // GetByType should be used. If only one is expected, then to switch plugins, // disable or remove the unused plugins of the same type. func (i *InitContext) GetSingle(t Type) (interface{}, error) { var ( found bool instance interface{} ) for _, v := range i.plugins.byTypeAndID[t] { i, err := v.Instance() if err != nil { if IsSkipPlugin(err) { continue } return i, err } if found { return nil, fmt.Errorf("multiple plugins registered for %s: %w", t, ErrPluginMultipleInstances) } instance = i found = true } if !found { return nil, fmt.Errorf("no plugins registered for %s: %w", t, ErrPluginNotFound) } return instance, nil } // Plugins returns plugin set func (i *InitContext) Plugins() *Set { return i.plugins } // GetAll plugins in the set func (i *InitContext) GetAll() []*Plugin { return i.plugins.GetAll() } // GetByID returns the plugin of the given type and ID func (i *InitContext) GetByID(t Type, id string) (interface{}, error) { p := i.plugins.Get(t, id) if p == nil { return nil, fmt.Errorf("no plugins registered for %s.%s: %w", t, id, ErrPluginNotFound) } return p.Instance() } // GetByType returns all plugins with the specific type. func (i *InitContext) GetByType(t Type) (map[string]interface{}, error) { pi := map[string]interface{}{} for id, p := range i.plugins.byTypeAndID[t] { i, err := p.Instance() if err != nil { if IsSkipPlugin(err) { continue } return nil, err } pi[id] = i } if len(pi) == 0 { return nil, fmt.Errorf("no plugins registered for %s: %w", t, ErrPluginNotFound) } return pi, nil } plugin-1.0.0/dynamic/000077500000000000000000000000001470527705100144425ustar00rootroot00000000000000plugin-1.0.0/dynamic/dynamic.go000066400000000000000000000021061470527705100164140ustar00rootroot00000000000000/* Copyright The containerd Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package dynamic import "fmt" // Load loads all plugins at the provided path into containerd. // // Load is currently only implemented on non-static, non-gccgo builds for amd64 // and arm64, and plugins must be built with the exact same version of Go as // containerd itself. func Load(path string) (loaded int, err error) { defer func() { if v := recover(); v != nil { rerr, ok := v.(error) if !ok { rerr = fmt.Errorf("%s", v) } err = rerr } }() return loadPlugins(path) } plugin-1.0.0/dynamic/dynamic_supported.go000066400000000000000000000027341470527705100205300ustar00rootroot00000000000000//go:build (amd64 || arm64) && !static_build && !gccgo /* Copyright The containerd Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package dynamic import ( "fmt" "path/filepath" "plugin" "runtime" ) // loadPlugins loads all plugins for the OS and Arch // that containerd is built for inside the provided path func loadPlugins(path string) (int, error) { abs, err := filepath.Abs(path) if err != nil { return 0, err } pattern := filepath.Join(abs, fmt.Sprintf( "*-%s-%s.%s", runtime.GOOS, runtime.GOARCH, getLibExt(), )) libs, err := filepath.Glob(pattern) if err != nil { return 0, err } loaded := 0 for _, lib := range libs { if _, err := plugin.Open(lib); err != nil { return loaded, err } loaded++ } return loaded, nil } // getLibExt returns a platform specific lib extension for // the platform that containerd is running on func getLibExt() string { switch runtime.GOOS { case "windows": return "dll" default: return "so" } } plugin-1.0.0/dynamic/dynamic_unsupported.go000066400000000000000000000020051470527705100210620ustar00rootroot00000000000000//go:build (!amd64 && !arm64) || static_build || gccgo /* Copyright The containerd Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package dynamic // loadPlugins is not supported; // // - with gccgo: gccgo has no plugin support golang/go#36403 // - on static builds; https://github.com/containerd/containerd/commit/0d682e24a1ba8e93e5e54a73d64f7d256f87492f // - on architectures other than amd64 and arm64 (other architectures need to be tested) func loadPlugins(path string) (int, error) { return 0, nil } plugin-1.0.0/go.mod000066400000000000000000000002421470527705100141220ustar00rootroot00000000000000module github.com/containerd/plugin go 1.20 require github.com/opencontainers/image-spec v1.1.0 require github.com/opencontainers/go-digest v1.0.0 // indirect plugin-1.0.0/go.sum000066400000000000000000000005741470527705100141570ustar00rootroot00000000000000github.com/opencontainers/go-digest v1.0.0 h1:apOUWs51W5PlhuyGyz9FCeeBIOUDA/6nW8Oi/yOhh5U= github.com/opencontainers/go-digest v1.0.0/go.mod h1:0JzlMkj0TRzQZfJkVvzbP0HBR3IKzErnv2BNG4W4MAM= github.com/opencontainers/image-spec v1.1.0 h1:8SG7/vwALn54lVB/0yZ/MMwhFrPYtpEHQb2IpWsCzug= github.com/opencontainers/image-spec v1.1.0/go.mod h1:W4s4sFTMaBeK1BQLXbG4AdM2szdn85PY75RI83NrTrM= plugin-1.0.0/plugin.go000066400000000000000000000130101470527705100146360ustar00rootroot00000000000000/* Copyright The containerd Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package plugin import ( "context" "errors" "fmt" ) var ( // ErrNoType is returned when no type is specified ErrNoType = errors.New("plugin: no type") // ErrNoPluginID is returned when no id is specified ErrNoPluginID = errors.New("plugin: no id") // ErrIDRegistered is returned when a duplicate id is already registered ErrIDRegistered = errors.New("plugin: id already registered") // ErrSkipPlugin is used when a plugin is not initialized and should not be loaded, // this allows the plugin loader differentiate between a plugin which is configured // not to load and one that fails to load. ErrSkipPlugin = errors.New("skip plugin") // ErrPluginInitialized is used when a plugin is already initialized ErrPluginInitialized = errors.New("plugin: already initialized") // ErrPluginNotFound is used when a plugin is looked up but not found ErrPluginNotFound = errors.New("plugin: not found") // ErrPluginMultipleInstances is used when a plugin is expected a single instance but has multiple ErrPluginMultipleInstances = errors.New("plugin: multiple instances") // ErrInvalidRequires will be thrown if the requirements for a plugin are // defined in an invalid manner. ErrInvalidRequires = errors.New("invalid requires") ) // IsSkipPlugin returns true if the error is skipping the plugin func IsSkipPlugin(err error) bool { return errors.Is(err, ErrSkipPlugin) } // Type is the type of the plugin type Type string func (t Type) String() string { return string(t) } // Registration contains information for registering a plugin type Registration struct { // Type of the plugin Type Type // ID of the plugin ID string // Config specific to the plugin Config interface{} // Requires is a list of plugins that the registered plugin requires to be available Requires []Type // InitFn is called when initializing a plugin. The registration and // context are passed in. The init function may modify the registration to // add exports, capabilities and platform support declarations. InitFn func(*InitContext) (interface{}, error) // ConfigMigration allows a plugin to migrate configurations from an older // version to handle plugin renames or moving of features from one plugin // to another in a later version. // The configuration map is keyed off the plugin name and the value // is the configuration for that objects, with the structure defined // for the plugin. No validation is done on the value before performing // the migration. ConfigMigration func(context.Context, int, map[string]interface{}) error } // Init the registered plugin func (r Registration) Init(ic *InitContext) *Plugin { p, err := r.InitFn(ic) return &Plugin{ Registration: r, Config: ic.Config, Meta: *ic.Meta, instance: p, err: err, } } // URI returns the full plugin URI func (r *Registration) URI() string { return r.Type.String() + "." + r.ID } // DisableFilter filters out disabled plugins type DisableFilter func(r *Registration) bool // Registry is list of registrations which can be registered to and // produce a filtered and ordered output. // The Registry itself is immutable and the list will be copied // and appeneded to a new registry when new items are registered. type Registry []*Registration // Graph computes the ordered list of registrations based on their dependencies, // filtering out any plugins which match the provided filter. func (registry Registry) Graph(filter DisableFilter) []Registration { disabled := map[*Registration]bool{} for _, r := range registry { if filter(r) { disabled[r] = true } } ordered := make([]Registration, 0, len(registry)-len(disabled)) added := map[*Registration]bool{} for _, r := range registry { if disabled[r] { continue } children(r, registry, added, disabled, &ordered) if !added[r] { ordered = append(ordered, *r) added[r] = true } } return ordered } func children(reg *Registration, registry []*Registration, added, disabled map[*Registration]bool, ordered *[]Registration) { for _, t := range reg.Requires { for _, r := range registry { if !disabled[r] && r.URI() != reg.URI() && (t == "*" || r.Type == t) { children(r, registry, added, disabled, ordered) if !added[r] { *ordered = append(*ordered, *r) added[r] = true } } } } } // Register adds the registration to a Registry and returns the // updated Registry, panicking if registration could not succeed. func (registry Registry) Register(r *Registration) Registry { if r.Type == "" { panic(ErrNoType) } if r.ID == "" { panic(ErrNoPluginID) } if err := checkUnique(registry, r); err != nil { panic(err) } for _, requires := range r.Requires { if requires == "*" && len(r.Requires) != 1 { panic(ErrInvalidRequires) } } return append(registry, r) } func checkUnique(registry Registry, r *Registration) error { for _, registered := range registry { if r.URI() == registered.URI() { return fmt.Errorf("%s: %w", r.URI(), ErrIDRegistered) } } return nil } plugin-1.0.0/plugin_test.go000066400000000000000000000275161470527705100157150ustar00rootroot00000000000000/* Copyright The containerd Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package plugin import ( "errors" "fmt" "testing" ) func mockPluginFilter(*Registration) bool { return false } // TestContainerdPlugin tests the logic of Graph, use the containerd's plugin func TestContainerdPlugin(t *testing.T) { // Plugin types commonly used by containerd const ( InternalPlugin Type = "io.containerd.internal.v1" RuntimePlugin Type = "io.containerd.runtime.v1" RuntimePluginV2 Type = "io.containerd.runtime.v2" ServicePlugin Type = "io.containerd.service.v1" GRPCPlugin Type = "io.containerd.grpc.v1" SnapshotPlugin Type = "io.containerd.snapshotter.v1" TaskMonitorPlugin Type = "io.containerd.monitor.v1" DiffPlugin Type = "io.containerd.differ.v1" MetadataPlugin Type = "io.containerd.metadata.v1" ContentPlugin Type = "io.containerd.content.v1" GCPlugin Type = "io.containerd.gc.v1" LeasePlugin Type = "io.containerd.lease.v1" TracingProcessorPlugin Type = "io.containerd.tracing.processor.v1" ) var register Registry register = register.Register(&Registration{ Type: TaskMonitorPlugin, ID: "cgroups", }).Register(&Registration{ Type: ServicePlugin, ID: "tasks-service", Requires: []Type{ RuntimePlugin, RuntimePluginV2, MetadataPlugin, TaskMonitorPlugin, }, }).Register(&Registration{ Type: ServicePlugin, ID: "introspection-service", }).Register(&Registration{ Type: ServicePlugin, ID: "namespaces-service", Requires: []Type{ MetadataPlugin, }, }).Register(&Registration{ Type: GRPCPlugin, ID: "namespaces", Requires: []Type{ ServicePlugin, }, }).Register(&Registration{ Type: GRPCPlugin, ID: "content", Requires: []Type{ ServicePlugin, }, }).Register(&Registration{ Type: GRPCPlugin, ID: "containers", Requires: []Type{ ServicePlugin, }, }).Register(&Registration{ Type: ServicePlugin, ID: "containers-service", Requires: []Type{ MetadataPlugin, }, }).Register(&Registration{ Type: GRPCPlugin, ID: "events", }).Register(&Registration{ Type: GRPCPlugin, ID: "leases", Requires: []Type{ LeasePlugin, }, }).Register(&Registration{ Type: LeasePlugin, ID: "manager", Requires: []Type{ MetadataPlugin, }, }).Register(&Registration{ Type: GRPCPlugin, ID: "diff", Requires: []Type{ ServicePlugin, }, }).Register(&Registration{ Type: ServicePlugin, ID: "diff-service", Requires: []Type{ DiffPlugin, }, }).Register(&Registration{ Type: ServicePlugin, ID: "snapshots-service", Requires: []Type{ MetadataPlugin, }, }).Register(&Registration{ Type: GRPCPlugin, ID: "snapshots", Requires: []Type{ ServicePlugin, }, }).Register(&Registration{ Type: GRPCPlugin, ID: "version", }).Register(&Registration{ Type: GRPCPlugin, ID: "images", Requires: []Type{ ServicePlugin, }, }).Register(&Registration{ Type: GCPlugin, ID: "scheduler", Requires: []Type{ MetadataPlugin, }, }).Register(&Registration{ Type: RuntimePluginV2, ID: "task", Requires: []Type{ MetadataPlugin, }, }).Register(&Registration{ Type: GRPCPlugin, ID: "tasks", Requires: []Type{ ServicePlugin, }, }).Register(&Registration{ Type: GRPCPlugin, ID: "introspection", Requires: []Type{"*"}, }).Register(&Registration{ Type: ServicePlugin, ID: "content-service", Requires: []Type{ MetadataPlugin, }, }).Register(&Registration{ Type: GRPCPlugin, ID: "healthcheck", }).Register(&Registration{ Type: InternalPlugin, ID: "opt", }).Register(&Registration{ Type: GRPCPlugin, ID: "cri", Requires: []Type{ ServicePlugin, }, }).Register(&Registration{ Type: RuntimePlugin, ID: "linux", Requires: []Type{ MetadataPlugin, }, }).Register(&Registration{ Type: InternalPlugin, Requires: []Type{ ServicePlugin, }, ID: "restart", }).Register(&Registration{ Type: DiffPlugin, ID: "walking", Requires: []Type{ MetadataPlugin, }, }).Register(&Registration{ Type: SnapshotPlugin, ID: "native", }).Register(&Registration{ Type: SnapshotPlugin, ID: "overlayfs", }).Register(&Registration{ Type: ContentPlugin, ID: "content", }).Register(&Registration{ Type: MetadataPlugin, ID: "bolt", Requires: []Type{ ContentPlugin, SnapshotPlugin, }, }).Register(&Registration{ Type: TracingProcessorPlugin, ID: "otlp", }).Register(&Registration{ Type: InternalPlugin, ID: "tracing", Requires: []Type{ TracingProcessorPlugin, }, }) ordered := register.Graph(mockPluginFilter) expectedURI := []string{ "io.containerd.monitor.v1.cgroups", "io.containerd.content.v1.content", "io.containerd.snapshotter.v1.native", "io.containerd.snapshotter.v1.overlayfs", "io.containerd.metadata.v1.bolt", "io.containerd.runtime.v1.linux", "io.containerd.runtime.v2.task", "io.containerd.service.v1.tasks-service", "io.containerd.service.v1.introspection-service", "io.containerd.service.v1.namespaces-service", "io.containerd.service.v1.containers-service", "io.containerd.differ.v1.walking", "io.containerd.service.v1.diff-service", "io.containerd.service.v1.snapshots-service", "io.containerd.service.v1.content-service", "io.containerd.grpc.v1.namespaces", "io.containerd.grpc.v1.content", "io.containerd.grpc.v1.containers", "io.containerd.grpc.v1.events", "io.containerd.lease.v1.manager", "io.containerd.grpc.v1.leases", "io.containerd.grpc.v1.diff", "io.containerd.grpc.v1.snapshots", "io.containerd.grpc.v1.version", "io.containerd.grpc.v1.images", "io.containerd.gc.v1.scheduler", "io.containerd.grpc.v1.tasks", "io.containerd.grpc.v1.healthcheck", "io.containerd.internal.v1.opt", "io.containerd.grpc.v1.cri", "io.containerd.internal.v1.restart", "io.containerd.tracing.processor.v1.otlp", "io.containerd.internal.v1.tracing", "io.containerd.grpc.v1.introspection", } cmpOrdered(t, ordered, expectedURI) } func cmpOrdered(t *testing.T, ordered []Registration, expectedURI []string) { if len(ordered) != len(expectedURI) { t.Fatalf("ordered compare failed, %d != %d", len(ordered), len(expectedURI)) } for i := range ordered { if ordered[i].URI() != expectedURI[i] { t.Fatalf("graph failed, expected: %s, but return: %s", expectedURI[i], ordered[i].URI()) } } } // TestPluginGraph tests the logic of Graph func TestPluginGraph(t *testing.T) { for _, testcase := range []struct { input []*Registration expectedURI []string filter DisableFilter }{ // test requires * { input: []*Registration{ { Type: "grpc", ID: "introspection", Requires: []Type{ "*", }, }, { Type: "service", ID: "container", }, }, expectedURI: []string{ "service.container", "grpc.introspection", }, }, // test requires { input: []*Registration{ { Type: "service", ID: "container", Requires: []Type{ "metadata", }, }, { Type: "metadata", ID: "bolt", }, }, expectedURI: []string{ "metadata.bolt", "service.container", }, }, { input: []*Registration{ { Type: "metadata", ID: "bolt", Requires: []Type{ "content", "snapshotter", }, }, { Type: "snapshotter", ID: "overlayfs", }, { Type: "content", ID: "content", }, }, expectedURI: []string{ "content.content", "snapshotter.overlayfs", "metadata.bolt", }, }, // test disable { input: []*Registration{ { Type: "content", ID: "content", }, { Type: "disable", ID: "disable", }, }, expectedURI: []string{ "content.content", }, filter: func(r *Registration) bool { return r.Type == "disable" }, }, } { var register Registry for _, in := range testcase.input { register = register.Register(in) } var filter DisableFilter = mockPluginFilter if testcase.filter != nil { filter = testcase.filter } ordered := register.Graph(filter) cmpOrdered(t, ordered, testcase.expectedURI) } } func TestGetPlugins(t *testing.T) { otherError := fmt.Errorf("other error") plugins := NewPluginSet() for _, p := range []*Plugin{ testPlugin("type1", "id1", "id1", nil), testPlugin("type1", "id2", "id2", ErrSkipPlugin), testPlugin("type2", "id3", "id3", ErrSkipPlugin), testPlugin("type3", "id4", "id4", nil), testPlugin("type4", "id5", "id5", nil), testPlugin("type4", "id6", "id6", nil), testPlugin("type5", "id7", "id7", otherError), } { plugins.Add(p) } ic := InitContext{ plugins: plugins, } for _, tc := range []struct { pluginType string err error }{ {"type1", nil}, {"type2", ErrPluginNotFound}, {"type3", nil}, {"type4", ErrPluginMultipleInstances}, {"type5", otherError}, } { t.Run("GetSingle", func(t *testing.T) { instance, err := ic.GetSingle(Type(tc.pluginType)) if err != nil { if tc.err == nil { t.Fatalf("unexpected error %v", err) } else if !errors.Is(err, tc.err) { t.Fatalf("unexpected error %v, expected %v", err, tc.err) } return } else if tc.err != nil { t.Fatalf("expected error %v, got no error", tc.err) } _, ok := instance.(string) if !ok { t.Fatalf("unexpected instance value %v", instance) } }) } for _, tc := range []struct { pluginType string expected []string err error }{ {"type1", []string{"id1"}, nil}, {"type2", nil, ErrPluginNotFound}, {"type3", []string{"id4"}, nil}, {"type4", []string{"id5", "id6"}, nil}, {"type5", nil, otherError}, } { t.Run("GetByType", func(t *testing.T) { m, err := ic.GetByType(Type(tc.pluginType)) if err != nil { if tc.err == nil { t.Fatalf("unexpected error %v", err) } else if !errors.Is(err, tc.err) { t.Fatalf("unexpected error %v, expected %v", err, tc.err) } return } else if tc.err != nil { t.Fatalf("expected error %v, got no error", tc.err) } if len(m) != len(tc.expected) { t.Fatalf("unexpected result %v, expected %v", m, tc.expected) } for _, v := range tc.expected { instance, ok := m[v] if !ok { t.Errorf("missing value for %q", v) continue } if instance.(string) != v { t.Errorf("unexpected value %v, expected %v", instance, v) } } }) } for _, tc := range []struct { pluginType string id string err error }{ {"type1", "id1", nil}, {"type1", "id2", ErrSkipPlugin}, {"type2", "id3", ErrSkipPlugin}, {"type3", "id4", nil}, {"type4", "id5", nil}, {"type4", "id6", nil}, {"type5", "id7", otherError}, } { t.Run("GetByID", func(t *testing.T) { instance, err := ic.GetByID(Type(tc.pluginType), tc.id) if err != nil { if tc.err == nil { t.Fatalf("unexpected error %v", err) } else if !errors.Is(err, tc.err) { t.Fatalf("unexpected error %v, expected %v", err, tc.err) } return } else if tc.err != nil { t.Fatalf("expected error %v, got no error", tc.err) } if instance.(string) != tc.id { t.Errorf("unexpected value %v, expected %v", instance, tc.id) } }) } } func testPlugin(t Type, id string, i interface{}, err error) *Plugin { return &Plugin{ Registration: Registration{ Type: t, ID: id, }, instance: i, err: err, } } plugin-1.0.0/registry/000077500000000000000000000000001470527705100146665ustar00rootroot00000000000000plugin-1.0.0/registry/register.go000066400000000000000000000024101470527705100170360ustar00rootroot00000000000000/* Copyright The containerd Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package registry import ( "sync" "github.com/containerd/plugin" ) var register = struct { sync.RWMutex r plugin.Registry }{} // Register allows plugins to register func Register(r *plugin.Registration) { register.Lock() defer register.Unlock() register.r = register.r.Register(r) } // Reset removes all global registrations func Reset() { register.Lock() defer register.Unlock() register.r = nil } // Graph returns an ordered list of registered plugins for initialization. // Plugins in disableList specified by id will be disabled. func Graph(filter plugin.DisableFilter) []plugin.Registration { register.RLock() defer register.RUnlock() return register.r.Graph(filter) }