| 1 |
// Copyright 2024 The Kubernetes Authors. |
| 2 |
// SPDX-License-Identifier: Apache-2.0 |
| 3 |
//go:build !kustomize_disable_go_plugin_support |
| 4 |
|
| 5 |
package loader |
| 6 |
|
| 7 |
import ( |
| 8 |
"fmt" |
| 9 |
"log" |
| 10 |
"plugin" |
| 11 |
"reflect" |
| 12 |
|
| 13 |
"sigs.k8s.io/kustomize/api/internal/plugins/utils" |
| 14 |
"sigs.k8s.io/kustomize/api/konfig" |
| 15 |
"sigs.k8s.io/kustomize/api/resmap" |
| 16 |
"sigs.k8s.io/kustomize/kyaml/errors" |
| 17 |
"sigs.k8s.io/kustomize/kyaml/resid" |
| 18 |
) |
| 19 |
|
| 20 |
// registry is a means to avoid trying to load the same .so file |
| 21 |
// into memory more than once, which results in an error. |
| 22 |
// Each test makes its own loader, and tries to load its own plugins, |
| 23 |
// but the loaded .so files are in shared memory, so one will get |
| 24 |
// "this plugin already loaded" errors if the registry is maintained |
| 25 |
// as a Loader instance variable. So make it a package variable. |
| 26 |
var registry = make(map[string]resmap.Configurable) //nolint:gochecknoglobals |
| 27 |
|
| 28 |
func copyPlugin(c resmap.Configurable) resmap.Configurable { |
| 29 |
indirect := reflect.Indirect(reflect.ValueOf(c)) |
| 30 |
newIndirect := reflect.New(indirect.Type()) |
| 31 |
newIndirect.Elem().Set(reflect.ValueOf(indirect.Interface())) |
| 32 |
newNamed := newIndirect.Interface() |
| 33 |
return newNamed.(resmap.Configurable) //nolint:forcetypeassert |
| 34 |
} |
| 35 |
|
| 36 |
func (l *Loader) loadGoPlugin(id resid.ResId, absPath string) (resmap.Configurable, error) { |
| 37 |
regId := relativePluginPath(id) |
| 38 |
if c, ok := registry[regId]; ok { |
| 39 |
return copyPlugin(c), nil |
| 40 |
} |
| 41 |
if !utils.FileExists(absPath) { |
| 42 |
return nil, fmt.Errorf( |
| 43 |
"expected file with Go object code at: %s", absPath) |
| 44 |
} |
| 45 |
log.Printf("Attempting plugin load from %q", absPath) |
| 46 |
p, err := plugin.Open(absPath) |
| 47 |
if err != nil { |
| 48 |
return nil, errors.WrapPrefixf(err, "plugin %s fails to load", absPath) |
| 49 |
} |
| 50 |
symbol, err := p.Lookup(konfig.PluginSymbol) |
| 51 |
if err != nil { |
| 52 |
return nil, errors.WrapPrefixf( |
| 53 |
err, "plugin %s doesn't have symbol %s", |
| 54 |
regId, konfig.PluginSymbol) |
| 55 |
} |
| 56 |
c, ok := symbol.(resmap.Configurable) |
| 57 |
if !ok { |
| 58 |
return nil, fmt.Errorf("plugin %q not configurable", regId) |
| 59 |
} |
| 60 |
registry[regId] = c |
| 61 |
return copyPlugin(c), nil |
| 62 |
} |