From a1ea0e06e0d4f944cd92d591420301c803587bae Mon Sep 17 00:00:00 2001 From: Alec Rabold Date: Tue, 26 Nov 2024 23:35:22 -0800 Subject: [PATCH] inject options --- kwok/{cloudprovider => options}/options.go | 40 +++++++++++++++------- 1 file changed, 27 insertions(+), 13 deletions(-) rename kwok/{cloudprovider => options}/options.go (62%) diff --git a/kwok/cloudprovider/options.go b/kwok/options/options.go similarity index 62% rename from kwok/cloudprovider/options.go rename to kwok/options/options.go index 8cb819303b..1799b61e5f 100644 --- a/kwok/cloudprovider/options.go +++ b/kwok/options/options.go @@ -14,37 +14,35 @@ See the License for the specific language governing permissions and limitations under the License. */ -package kwok +package options import ( + "context" "errors" "flag" "fmt" "os" - "github.com/samber/lo" - + "sigs.k8s.io/karpenter/pkg/operator/options" "sigs.k8s.io/karpenter/pkg/utils/env" ) +func init() { + options.Injectables = append(options.Injectables, &Options{}) +} + +type optionsKey struct{} + // Options contains all CLI flags / env vars for the KWOK cloudprovider. type Options struct { InstanceTypesFilePath string } -func GetOptionsOrDie() *Options { - opts := &Options{} - fs := flag.NewFlagSet("kwok", flag.ContinueOnError) - opts.AddFlags(fs) - lo.Must0(opts.Parse(fs, os.Args[1:]...)) - return opts -} - -func (o *Options) AddFlags(fs *flag.FlagSet) { +func (o *Options) AddFlags(fs *options.FlagSet) { fs.StringVar(&o.InstanceTypesFilePath, "instance-types-file-path", env.WithDefaultString("INSTANCE_TYPES_FILE_PATH", ""), "Path to a custom instance-types file") } -func (o *Options) Parse(fs *flag.FlagSet, args ...string) error { +func (o *Options) Parse(fs *options.FlagSet, args ...string) error { if err := fs.Parse(args); err != nil { if errors.Is(err, flag.ErrHelp) { os.Exit(0) @@ -53,3 +51,19 @@ func (o *Options) Parse(fs *flag.FlagSet, args ...string) error { } return nil } + +func (o *Options) ToContext(ctx context.Context) context.Context { + return ToContext(ctx, o) +} + +func ToContext(ctx context.Context, opts *Options) context.Context { + return context.WithValue(ctx, optionsKey{}, opts) +} + +func FromContext(ctx context.Context) *Options { + retval := ctx.Value(optionsKey{}) + if retval == nil { + return nil + } + return retval.(*Options) +}