From c8fba92811347516a19096d7e9f56055243fcd79 Mon Sep 17 00:00:00 2001 From: unkin-agent Date: Mon, 9 Nov 2026 22:18:00 +1100 Subject: [PATCH] Load types through Puppet::Type.type and evaluate title_patterns locals Puppet::Type.type(:x) loads x's module type file with its providers, whose classes .provider(:n) returns as a parent; a nil parent is Puppet::Provider. title_patterns binds locals, including Regexp.new copies. Generates ceph_config, ceph_fs and ceph_pool. --- internal/gentypes/eval.go | 146 +++++++- internal/gentypes/eval_test.go | 2 + internal/gentypes/fidelity_test.go | 44 +++ internal/gentypes/fuzz_test.go | 1 + internal/gentypes/generate.go | 39 +- internal/gentypes/load.go | 12 +- internal/gentypes/parse.go | 24 +- .../env/external_modules/ceph/LICENSE | 201 +++++++++++ .../ceph/lib/puppet/provider/ceph.rb | 18 + .../provider/ceph_config/ini_setting.rb | 50 +++ .../ceph/lib/puppet/provider/ceph_fs/ceph.rb | 58 +++ .../lib/puppet/provider/ceph_pool/ceph.rb | 81 +++++ .../ceph/lib/puppet/type/ceph_config.rb | 75 ++++ .../ceph/lib/puppet/type/ceph_fs.rb | 59 +++ .../ceph/lib/puppet/type/ceph_pool.rb | 91 +++++ .../lib/puppet/provider/ini_setting/ruby.rb | 152 ++++++++ .../lib/puppet/util/external_iterator.rb | 32 ++ .../inifile/lib/puppet/util/ini_file.rb | 338 ++++++++++++++++++ .../lib/puppet/util/ini_file/section.rb | 96 +++++ .../gentypes/testdata/golden/ceph_config.pp | 41 +++ internal/gentypes/testdata/golden/ceph_fs.pp | 46 +++ .../gentypes/testdata/golden/ceph_pool.pp | 50 +++ 22 files changed, 1623 insertions(+), 33 deletions(-) create mode 100644 internal/gentypes/testdata/env/external_modules/ceph/LICENSE create mode 100644 internal/gentypes/testdata/env/external_modules/ceph/lib/puppet/provider/ceph.rb create mode 100644 internal/gentypes/testdata/env/external_modules/ceph/lib/puppet/provider/ceph_config/ini_setting.rb create mode 100644 internal/gentypes/testdata/env/external_modules/ceph/lib/puppet/provider/ceph_fs/ceph.rb create mode 100644 internal/gentypes/testdata/env/external_modules/ceph/lib/puppet/provider/ceph_pool/ceph.rb create mode 100644 internal/gentypes/testdata/env/external_modules/ceph/lib/puppet/type/ceph_config.rb create mode 100644 internal/gentypes/testdata/env/external_modules/ceph/lib/puppet/type/ceph_fs.rb create mode 100644 internal/gentypes/testdata/env/external_modules/ceph/lib/puppet/type/ceph_pool.rb create mode 100644 internal/gentypes/testdata/env/external_modules/inifile/lib/puppet/util/external_iterator.rb create mode 100644 internal/gentypes/testdata/env/external_modules/inifile/lib/puppet/util/ini_file.rb create mode 100644 internal/gentypes/testdata/env/external_modules/inifile/lib/puppet/util/ini_file/section.rb create mode 100644 internal/gentypes/testdata/golden/ceph_config.pp create mode 100644 internal/gentypes/testdata/golden/ceph_fs.pp create mode 100644 internal/gentypes/testdata/golden/ceph_pool.pp diff --git a/internal/gentypes/eval.go b/internal/gentypes/eval.go index 9ef7726..6165da8 100644 --- a/internal/gentypes/eval.go +++ b/internal/gentypes/eval.go @@ -271,6 +271,9 @@ func (p *parser) method(v rval, m string) (rval, error) { if m == "respond_to?" || m == "is_a?" || m == "kind_of?" { return p.typeQuery(v, m) } + if m == "provider" && v.k == vType { + return p.typeProvider(v) + } if p.op("(") && !p.cur().space || p.op("{") { return v, fmt.Errorf("unsupported arguments or block for %s", m) } @@ -342,11 +345,8 @@ func (p *parser) coreConst(name string) bool { // validProperties is Puppet::Type.validproperties of the type being loaded: property names in definition order. func (p *parser) validProperties(typ string) (rval, error) { - if p.w.typ == nil || p.w.typ.name != typ { - return rval{}, fmt.Errorf("Puppet::Type.type(:%s) is not the type being loaded", typ) - } out := rval{k: vArray} - for _, n := range p.w.typ.validprops { + for _, n := range p.w.types[typ].t.validprops { if !rubyName.MatchString(n) { return rval{}, fmt.Errorf("unsupported property name %q", n) } @@ -436,6 +436,9 @@ func (p *parser) atom() (rval, error) { return rval{k: vHash}, p.skipBlock() } return rval{k: vHash}, nil + case t.kind == tConst && t.text == "Regexp" && p.at(1).text == "." && p.at(2).text == "new" && p.coreConst("Regexp"): + p.i += 3 + return p.regexpNew() case t.kind == tIdent && t.text == "defined?": return p.definedExpr() case isLocal(t) && (p.locals != nil || p.cls != nil): @@ -448,19 +451,8 @@ func (p *parser) atom() (rval, error) { } p.take() return p.call(t.text) - case t.kind == tConst && t.text == "Puppet" && p.at(1).text == "::" && p.at(2).text == "Type" && p.at(3).text == "." && p.at(4).text == "type" && p.w != nil: - p.i += 5 - args, err := p.args() - if err != nil { - return rval{}, err - } - if len(args) != 1 || args[0].k != vSym { - return rval{}, fmt.Errorf("unsupported Puppet::Type.type arguments") - } - if p.w.typ == nil || p.w.typ.name != args[0].s { - return rval{}, fmt.Errorf("Puppet::Type.type(:%s) is not the type being loaded", args[0].s) - } - return rval{k: vType, s: args[0].s}, nil + case p.typeAhead(): + return p.typeCall() } return p.primary() } @@ -1141,3 +1133,123 @@ func (o *onig) class() error { n++ } } + +// regexpNew evaluates Regexp.new(src): a copy of a Regexp, or a String compiled with no options. +func (p *parser) regexpNew() (rval, error) { + args, err := p.args() + if err != nil { + return rval{}, err + } + switch { + case len(args) != 1: + case args[0].k == vRegex: + return args[0], nil + case args[0].k == vStr: + if err := onigCheck(args[0].s, false); err != nil { + return rval{}, err + } + return rval{k: vRegex, re: regex{src: args[0].s}}, nil + } + return rval{}, fmt.Errorf("unsupported Regexp.new arguments") +} + +func capitalize(s string) string { return strings.ToUpper(s[:1]) + s[1:] } + +// loadType ports Puppet::Type.type(name): a loaded type, or the first puppet/type/.rb the typeloader finds in +// module lib dirs, analysed with all its providers, whose classes it defines; nil when no file defines it. +func (w *world) loadType(name string) (*loadedType, error) { + if lt, ok := w.types[name]; ok { + return lt, nil + } + lib := "puppet/type/" + name + switch { + case !rubyName.MatchString(name): + return nil, fmt.Errorf("Puppet::Type.type(%q) is not modelled", name) + case coreLib(lib): + return nil, fmt.Errorf("Puppet::Type.type(:%s) loads a type of puppet that w10k does not model", name) + case w.resolve == nil: + return nil, fmt.Errorf("Puppet::Type.type(:%s): module sources are not available", name) + } + srcs, err := w.resolve(lib+".rb", "") + switch { + case err != nil: + return nil, err + case len(srcs) == 0: + w.types[name] = nil + return nil, nil + case len(srcs) > 1: + return nil, fmt.Errorf("Puppet::Type.type(:%s): more than one module provides it", name) + case w.loaded[srcs[0].mod+"\x00"+srcs[0].rel]: + return nil, fmt.Errorf("Puppet::Type.type(:%s): lib/%s.rb was already required", name, lib) + } + types, err := parseFile(srcs[0], w) + if err != nil { + return nil, fmt.Errorf("Puppet::Type.type(:%s): %w", name, err) + } + i := slices.IndexFunc(types, func(t *rtype) bool { return t.name == name }) + if i < 0 || len(types) > 1 { + return nil, fmt.Errorf("Puppet::Type.type(:%s): lib/%s.rb does not define exactly that type", name, lib) + } + lt := &loadedType{t: types[i]} + w.types[name] = lt + saved := w.typ + w.typ = lt.t + defer func() { w.typ = saved }() + provs, err := loadProviders(lt.t, w.provFiles[name], w) + if err != nil { + return nil, fmt.Errorf("Puppet::Type.type(:%s): %w", name, err) + } + tc := "Puppet::Type::" + capitalize(name) + for n, pr := range provs { + cname := tc + "::Provider" + capitalize(n) + w.define(cname, pr.c.kind) + w.user[cname], w.classes[cname], w.sup[cname] = true, pr.c, pr.c.parent + if pr.parent != "" { + w.sup[cname] = tc + "::Provider" + capitalize(pr.parent) + } + w.classSdefs(cname) + w.sdefs[cname] = pr.c.sdefs + } + lt.provs = provs + return lt, nil +} + +func (p *parser) typeAhead() bool { + return p.is(tConst, "Puppet") && p.at(1).text == "::" && p.at(2).text == "Type" && p.at(3).text == "." && p.at(4).text == "type" && p.w != nil +} + +// typeCall evaluates Puppet::Type.type(:name) at the cursor to the type, or nil. +func (p *parser) typeCall() (rval, error) { + p.i += 5 + args, err := p.args() + if err != nil { + return rval{}, err + } + if len(args) != 1 || args[0].k != vSym { + return rval{}, fmt.Errorf("unsupported Puppet::Type.type arguments") + } + lt, err := p.w.loadType(args[0].s) + if err != nil || lt == nil { + return rval{k: vNil}, err + } + return rval{k: vType, s: args[0].s}, nil +} + +// typeProvider evaluates type.provider(:name) of a type whose providers have loaded: its class, or nil. +func (p *parser) typeProvider(v rval) (rval, error) { + args, err := p.args() + if err != nil { + return v, err + } + if len(args) != 1 || args[0].k != vSym && args[0].k != vStr || !rubyName.MatchString(args[0].s) { + return v, fmt.Errorf("unsupported provider arguments") + } + lt := p.w.types[v.s] + if lt == nil || lt.provs == nil { + return v, fmt.Errorf("Puppet::Type.type(:%s).provider: its providers are still loading", v.s) + } + if lt.provs[args[0].s] == nil { + return rval{k: vNil}, nil + } + return rval{k: vConst, s: "Puppet::Type::" + capitalize(v.s) + "::Provider" + capitalize(args[0].s)}, nil +} diff --git a/internal/gentypes/eval_test.go b/internal/gentypes/eval_test.go index c8ee9d7..9c19b8b 100644 --- a/internal/gentypes/eval_test.go +++ b/internal/gentypes/eval_test.go @@ -22,6 +22,7 @@ func evalProvider(src string, parent bool) (c *classCtx, consts map[string]rval, defer guard(&err) w = newWorld(nil) w.typ = &rtype{name: "t", validprops: []string{"b", "ensure", "a"}} + w.types["t"] = &loadedType{t: w.typ} if err := (&parser{w: w}).load(libFile{mod: "m", rel: "puppet_x/zqp.rb", src: evalParent}); err != nil { return nil, nil, w, err } @@ -175,6 +176,7 @@ func TestEvaluatorAlias(t *testing.T) { func TestEvaluatorUnknownParent(t *testing.T) { w := newWorld(nil) w.typ = &rtype{name: "t"} + w.types["t"] = &loadedType{t: w.typ} _, err := providerFile(libFile{mod: "m", rel: "puppet/provider/t/x.rb", src: "Puppet::Type.type(:t).provide(:x, parent: :y) do\n X = tp\nend\n"}, "t", false, w) if err == nil { t.Fatal("singleton method of an unmodelled parent provider evaluated") diff --git a/internal/gentypes/fidelity_test.go b/internal/gentypes/fidelity_test.go index da72a35..6e1a0ea 100644 --- a/internal/gentypes/fidelity_test.go +++ b/internal/gentypes/fidelity_test.go @@ -245,3 +245,47 @@ func TestFidelityProviderDocs(t *testing.T) { }) } } + +func typeWith(name, extra string) string { + return "Puppet::Type.newtype(:" + name + ") do\n newparam(:name) { isnamevar }\n" + extra + "end\n" +} + +// Puppet::Type.type(:u) loads u with its providers; openvox 9.3.0 writes t.pp with want. +func TestFidelityCrossType(t *testing.T) { + env := fidelityEnv(t, map[string]string{ + "m/lib/puppet/type/t.rb": typeWith("t", " newparam(:cluster)\n def self.title_patterns\n c = Regexp.new(/[^\\/]+/)\n n = Regexp.new('a/b')\n i = Regexp.new(/x/i)\n"+ + " [[/^(#{c})\\/(#{n})$/, [[:cluster], [:name]]], [/^(#{i})$/, [[:name]]]]\n end\n"), + "m/lib/puppet/type/u.rb": typeWith("u", ""), + "m/lib/puppet/provider/u/base.rb": "Puppet::Type.type(:u).provide(:base) do\n desc 'base doc'\n commands bb: 'bb'\nend\n", + "m/lib/puppet/provider/t/a.rb": "Puppet::Type.type(:t).provide(:a, parent: Puppet::Type.type(:u).provider(:base)) do\nend\n", + "m/lib/puppet/provider/t/b.rb": "Puppet::Type.type(:t).provide(:b, parent: Puppet::Type.type(:u).provider(:missing)) do\n desc 'b'\nend\n", + }) + want := " # a\n # : \n # \n # b\n # : b\n Puppet::Resource::Param(Any, 'provider')\n ],\n {\n" + + " /^((?-mix:[^\\/]+))\\/((?-mix:a\\/b))$/ => ['cluster', 'name'],\n /^((?i-mx:x))$/ => ['name']\n },\n" + if b := readFile(t, filepath.Join(env, OutDir, "t.pp")); !strings.Contains(b, want) { + t.Fatalf("t.pp lacks %q:\n%s", want, b) + } +} + +// Each env loads type t in openvox 9.3.0 only through state w10k does not model, so w10k writes no t.pp. +func TestCrossTypeSkips(t *testing.T) { + for name, files := range map[string]map[string]string{ + "puppet core type": {"m/lib/puppet/type/t.rb": classic, + "m/lib/puppet/provider/t/x.rb": "Puppet::Type.type(:t).provide(:x, parent: Puppet::Type.type(:file).provider(:posix)) do\nend\n"}, + "own type's providers still loading": {"m/lib/puppet/type/t.rb": classic, + "m/lib/puppet/provider/t/x.rb": "Puppet::Type.type(:t).provide(:x, parent: Puppet::Type.type(:t).provider(:y)) do\nend\n"}, + "type in two modules": {"m/lib/puppet/type/t.rb": classic, "m/lib/puppet/type/u.rb": typeWith("u", ""), "n/lib/puppet/type/u.rb": typeWith("u", ""), + "m/lib/puppet/provider/t/x.rb": "Puppet::Type.type(:t).provide(:x, parent: Puppet::Type.type(:u).provider(:y)) do\nend\n"}, + "missing type": {"m/lib/puppet/type/t.rb": classic, + "m/lib/puppet/provider/t/x.rb": "Puppet::Type.type(:t).provide(:x, parent: Puppet::Type.type(:nope).provider(:y)) do\nend\n"}, + "loaded type's provider raises": {"m/lib/puppet/type/t.rb": classic, "m/lib/puppet/type/v.rb": typeWith("v", ""), "m/lib/puppet/provider/v/x.rb": "raise 'boom'\n", + "m/lib/puppet/provider/t/x.rb": "Puppet::Type.type(:t).provide(:x, parent: Puppet::Type.type(:v).provider(:x)) do\nend\n"}, + "title_patterns compiles a bad regex": {"m/lib/puppet/type/t.rb": typeWith("t", " newparam(:c)\n def self.title_patterns\n c = Regexp.new('(')\n [[/(#{c})/, [[:name]]]]\n end\n")}, + } { + t.Run(name, func(t *testing.T) { + if exists(filepath.Join(fidelityEnv(t, files), OutDir, "t.pp")) { + t.Fatal("t.pp written") + } + }) + } +} diff --git a/internal/gentypes/fuzz_test.go b/internal/gentypes/fuzz_test.go index de87fda..9d655bc 100644 --- a/internal/gentypes/fuzz_test.go +++ b/internal/gentypes/fuzz_test.go @@ -54,6 +54,7 @@ func FuzzEval(f *testing.F) { _, _, _, _ = evalProvider(src, len(src)%2 == 0) w := newWorld(nil) w.typ = &rtype{name: "t", validprops: []string{"a", "ensure"}} + w.types["t"] = &loadedType{t: w.typ} if err := (&parser{w: w}).load(libFile{mod: "m", rel: "puppet_x/m/fm.rb", src: fm}); err != nil { t.Fatal(err) } diff --git a/internal/gentypes/generate.go b/internal/gentypes/generate.go index 011f1f8..a933f8b 100644 --- a/internal/gentypes/generate.go +++ b/internal/gentypes/generate.go @@ -18,7 +18,7 @@ import ( const OutDir = ".resource_types" // Version changes whenever generated output can change, so deploys rebuild typed environments. -const Version = "9" +const Version = "10" var moduleName = regexp.MustCompile(`^[a-z][a-z0-9_]*$`) @@ -133,7 +133,7 @@ func GenerateGems(env string, gems []string, roots ...string) (st Stats, err err var errs []error for _, in := range inputs { name := strings.TrimSuffix(filepath.Base(in), ".rb") - wrote, err := generateOne(in, out, providers[name], g.libs(mods), g.shadows, g.gems) + wrote, err := generateOne(in, out, providers, g.libs(mods), g.shadows, g.gems) switch { case err == nil && wrote: st.Generated++ @@ -196,8 +196,8 @@ func openOut(env string) (*os.Root, error) { return root.OpenRoot(OutDir) } -// generateOne writes the type defined by in; providers are the first-found provider files the autoloader loads for it. -func generateOne(in string, out *os.Root, providers []string, resolve Resolver, shadows func(string) (string, error), gems map[string]bool) (wrote bool, err error) { +// generateOne writes the type defined by in; providers are the first-found provider files the autoloader loads, by type. +func generateOne(in string, out *os.Root, providers map[string][]string, resolve Resolver, shadows func(string) (string, error), gems map[string]bool) (wrote bool, err error) { defer func() { if r := recover(); r != nil { err = fmt.Errorf("panic: %v", r) @@ -219,6 +219,7 @@ func generateOne(in string, out *os.Root, providers []string, resolve Resolver, w := newWorld(resolve) w.shadows = shadows w.gems = gems + w.provFiles = providers types, err := parseFile(libFile{mod: moduleOf(in, 4), rel: "puppet/type/" + filepath.Base(in), src: string(src)}, w) if err != nil { return false, unparsed(err) @@ -233,7 +234,8 @@ func generateOne(in string, out *os.Root, providers []string, resolve Resolver, return false, skipErr{fmt.Errorf("custom type %q was not defined", name)} } w.typ = t - docs, err := providerDocs(t, providers, w) + w.types[name] = &loadedType{t: t} + docs, err := providerDocs(t, providers[name], w) if err != nil { return false, err } @@ -255,6 +257,23 @@ func moduleOf(f string, n int) string { // providerDocs returns the doc of each provider puppet registers for t, or a skip when loading a provider file could // fail or its doc cannot be proven. func providerDocs(t *rtype, files []string, w *world) (map[string]string, error) { + provs, err := loadProviders(t, files, w) + if err != nil { + return nil, err + } + docs := map[string]string{} + for name, pr := range provs { + doc, err := t.providerDoc(pr, provs, w) + if err != nil { + return nil, unparsed(fmt.Errorf("provider %s: %w", name, err)) + } + docs[name] = doc + } + return docs, nil +} + +// loadProviders loads t's provider files as the type's providerloader.loadall does, failing when one could raise. +func loadProviders(t *rtype, files []string, w *world) (map[string]*provDecl, error) { if t.rsapi { var b strings.Builder for _, part := range strings.Split(t.name, "_") { @@ -296,15 +315,7 @@ func providerDocs(t *rtype, files []string, w *world) (map[string]string, error) return nil, skipErr{fmt.Errorf("parent provider %s is not defined", p)} } } - docs := map[string]string{} - for name, pr := range provs { - doc, err := t.providerDoc(pr, provs, w) - if err != nil { - return nil, unparsed(fmt.Errorf("provider %s: %w", name, err)) - } - docs[name] = doc - } - return docs, nil + return provs, nil } // libs resolves lib/ in every module in modulepath order, as Ruby's require searches module lib dirs, or in mod alone. diff --git a/internal/gentypes/load.go b/internal/gentypes/load.go index 0a114d9..df1c99f 100644 --- a/internal/gentypes/load.go +++ b/internal/gentypes/load.go @@ -33,6 +33,15 @@ type world struct { typ *rtype sdefs map[string]map[string]*sdef steps, alloc int + // provFiles are the provider files by type; types are the types Puppet::Type.type returns, nil where none loads + provFiles map[string][]string + types map[string]*loadedType +} + +// loadedType is a type newtype stored; provs is set once its providerloader.loadall finished. +type loadedType struct { + t *rtype + provs map[string]*provDecl } // Constant kinds: module, class, a Puppet::Provider subclass, a Puppet::Provider::ParsedFile subclass. @@ -59,7 +68,7 @@ var startup = func() map[string]byte { }() func newWorld(resolve Resolver) *world { - w := &world{resolve: resolve, defined: map[string]bool{}, kind: map[string]byte{}, sup: map[string]string{}, user: map[string]bool{}, mods: map[string][]string{}, loaded: map[string]bool{}, classes: map[string]*classCtx{}, tclasses: map[string]bool{}} + w := &world{resolve: resolve, defined: map[string]bool{}, kind: map[string]byte{}, sup: map[string]string{}, user: map[string]bool{}, mods: map[string][]string{}, loaded: map[string]bool{}, classes: map[string]*classCtx{}, tclasses: map[string]bool{}, types: map[string]*loadedType{}} for c, k := range startup { w.define(c, k) } @@ -998,6 +1007,7 @@ func providerFile(f libFile, typ string, rsapi bool, w *world) (pr *provDecl, er } if v, ok := args[1].get("parent"); ok { switch v.k { + case vNil, vFalse: case vSym, vStr: parent = v.s c.parentUnknown = true diff --git a/internal/gentypes/parse.go b/internal/gentypes/parse.go index 7dade9c..6e3d513 100644 --- a/internal/gentypes/parse.go +++ b/internal/gentypes/parse.go @@ -1378,7 +1378,21 @@ func (p *parser) titlePatterns(t *rtype) error { return err } } - p.skipNL() + saved := p.locals + p.locals = map[string]rval{} + defer func() { p.locals = saved }() + for p.skipNL(); isLocal(p.cur()) && p.assigns(); p.skipNL() { + name := p.take().text + p.take() + v, err := p.eval() + if err == nil && p.cur().kind != tNL && !p.op(";") { + err = fmt.Errorf("unsupported %s", describe(p.cur())) + } + if err != nil { + return fmt.Errorf("title_patterns: %w", err) + } + p.locals[name] = v + } v, err := p.expr() if err != nil { return fmt.Errorf("title_patterns: %w", err) @@ -1555,6 +1569,11 @@ func (p *parser) expr() (rval, error) { switch { case p.op(".") && p.at(1).kind == tIdent && p.at(1).text == "freeze": p.i += 2 + case v.k == vType && p.op(".") && p.at(1).kind == tIdent: + p.take() + if v, err = p.method(v, p.take().text); err != nil { + return v, err + } case v.k == vStr && p.cur().kind == tStr: w, err := p.primary() if err != nil { @@ -1737,6 +1756,9 @@ func (p *parser) primary() (rval, error) { } } case tConst: + if p.typeAhead() { + return p.typeCall() + } if t.text == "File" && p.at(1).text == "." && p.at(3).text == "(" && strings.Contains(" join expand_path dirname ", " "+p.at(2).text+" ") { _, err := p.pathExpr(0) return rval{k: vBlock}, err diff --git a/internal/gentypes/testdata/env/external_modules/ceph/LICENSE b/internal/gentypes/testdata/env/external_modules/ceph/LICENSE new file mode 100644 index 0000000..8d968b6 --- /dev/null +++ b/internal/gentypes/testdata/env/external_modules/ceph/LICENSE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://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 + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + 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. diff --git a/internal/gentypes/testdata/env/external_modules/ceph/lib/puppet/provider/ceph.rb b/internal/gentypes/testdata/env/external_modules/ceph/lib/puppet/provider/ceph.rb new file mode 100644 index 0000000..470096e --- /dev/null +++ b/internal/gentypes/testdata/env/external_modules/ceph/lib/puppet/provider/ceph.rb @@ -0,0 +1,18 @@ +require 'puppet' + +class Puppet::Provider::Ceph < Puppet::Provider + + initvars + commands :ceph => 'ceph' + + protected + + # NOTE(tkajinam): JSON outputs from ceph command includes garbage empty lines + def parse_json(value) + JSON.parse(value.gsub(/^$\n/, '').strip) + end + + def ceph_cmd(cluster, args) + ceph('--cluster', cluster, *args) + end +end diff --git a/internal/gentypes/testdata/env/external_modules/ceph/lib/puppet/provider/ceph_config/ini_setting.rb b/internal/gentypes/testdata/env/external_modules/ceph/lib/puppet/provider/ceph_config/ini_setting.rb new file mode 100644 index 0000000..71abca9 --- /dev/null +++ b/internal/gentypes/testdata/env/external_modules/ceph/lib/puppet/provider/ceph_config/ini_setting.rb @@ -0,0 +1,50 @@ +# Copyright (C) Dan Bode +# +# 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. +# +# Author: Dan Bode +# Author: Andrew Woodward + +Puppet::Type.type(:ceph_config).provide( + :ini_setting, + :parent => Puppet::Type.type(:ini_setting).provider(:ruby) +) do + + def section + resource[:name].split('/', 2).first + end + + def setting + resource[:name].split('/', 2).last + end + + def separator + ' = ' + end + + def self.file_path + '/etc/ceph/ceph.conf' + end + + # required to be able to hack the path in unit tests + # also required if a user wants to otherwise overwrite the default file_path + # Note: purge will not work on over-ridden file_path + def file_path + if not resource[:path] + self.class.file_path + else + resource[:path] + end + end + +end diff --git a/internal/gentypes/testdata/env/external_modules/ceph/lib/puppet/provider/ceph_fs/ceph.rb b/internal/gentypes/testdata/env/external_modules/ceph/lib/puppet/provider/ceph_fs/ceph.rb new file mode 100644 index 0000000..8857532 --- /dev/null +++ b/internal/gentypes/testdata/env/external_modules/ceph/lib/puppet/provider/ceph_fs/ceph.rb @@ -0,0 +1,58 @@ +require 'puppet' +require 'puppet/provider/ceph' + +Puppet::Type.type(:ceph_fs).provide( + :ceph, + :parent => Puppet::Provider::Ceph +) do + desc 'Provider for ceph filesystem' + + def create + ceph_cmd(@resource[:cluster], ['fs', 'new', @resource[:name], @resource[:metadata_pool_name], @resource[:data_pool_name]]) + end + + def destroy + ceph_cmd(@resource[:cluster], ['fs', 'rm', @resource[:name], '--yes-i-really-really-mean-it']) + end + + def exists? + fs = find_fs + if fs.nil? + return false + end + return true + end + + def metadata_pool_name + fs = find_fs + fs['metadata_pool'] + end + + def data_pool_name + fs = find_fs + # TODO(tkajinam): data pool is a list. Should we support multiple values ? + fs['data_pools'][0] + end + + [ + :metadata_pool_name, + :data_pool_name, + ].each do |attr| + define_method(attr.to_s + "=") do |value| + fail("Property #{attr.to_s} does not support being updated") + end + end + + private + + def find_fs + fs_list = parse_json( + ceph_cmd(@resource[:cluster], ['fs', 'ls', '-f', 'json'])) + fs_list.each do |fs| + if fs['name'] == @resource[:name] + return fs + end + end + return nil + end +end diff --git a/internal/gentypes/testdata/env/external_modules/ceph/lib/puppet/provider/ceph_pool/ceph.rb b/internal/gentypes/testdata/env/external_modules/ceph/lib/puppet/provider/ceph_pool/ceph.rb new file mode 100644 index 0000000..012005c --- /dev/null +++ b/internal/gentypes/testdata/env/external_modules/ceph/lib/puppet/provider/ceph_pool/ceph.rb @@ -0,0 +1,81 @@ +require 'puppet' +require 'puppet/provider/ceph' + +Puppet::Type.type(:ceph_pool).provide( + :ceph, + :parent => Puppet::Provider::Ceph +) do + desc 'Provider for ceph pools' + + def create + args = [] + args << @resource[:pg_num] + if @resource[:pgp_num] + args << @resource[:pgp_num] + end + ceph_cmd(@resource[:cluster], ['osd', 'pool', 'create', @resource[:name], *args]) + + if @resource[:size] + set_pool_property('size', @resource[:size]) + end + if @resource[:application] + ceph_cmd(@resource[:cluster], ['osd', 'pool', 'application','enable', @resource[:name], @resource[:application]]) + end + end + + def destroy + ceph_cmd(@resource[:cluster], ['osd', 'pool', 'delete', @resource[:name], @resource[:name], '--yes-i-really-really-mean-it']) + end + + def exists? + pools = parse_json(ceph_cmd(@resource[:cluster], ['osd', 'pool', 'ls', '-f', 'json'])) + pools.include?(@resource[:name]) + end + + def size + get_pool_property('size') + end + + def size=(value) + set_pool_property('size', value) + end + + def pg_num + get_pool_property('pg_num') + end + + def pg_num=(value) + set_pool_property('pg_num', value) + end + + def pgp_num + get_pool_property('pgp_num') + end + + def pgp_num=(value) + set_pool_property('pgp_num', value) + end + + def application + val = parse_json(ceph_cmd(@resource[:cluster], ['osd', 'pool', 'application', 'get', @resource[:name], '-f', 'json'])) + val.keys[0] + end + + def application=(value) + if application.nil? + ceph_cmd(@resource[:cluster], ['osd', 'pool', 'application', 'enable', @resource[:name], value]) + else + raise Puppet::Error, "The pool #{@resource[:name]} already has application set" + end + end + + private + + def get_pool_property(key) + parse_json(ceph_cmd(@resource[:cluster], ['osd', 'pool', 'get', @resource[:name], key, '-f', 'json']))[key] + end + + def set_pool_property(key, value) + ceph_cmd(@resource[:cluster], ['osd', 'pool', 'set', @resource[:name], key, value]) + end +end diff --git a/internal/gentypes/testdata/env/external_modules/ceph/lib/puppet/type/ceph_config.rb b/internal/gentypes/testdata/env/external_modules/ceph/lib/puppet/type/ceph_config.rb new file mode 100644 index 0000000..c4fba45 --- /dev/null +++ b/internal/gentypes/testdata/env/external_modules/ceph/lib/puppet/type/ceph_config.rb @@ -0,0 +1,75 @@ +# Copyright (C) Dan Bode +# +# 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. +# +# Author: Dan Bode +# Author: Mathieu Gagne + + +Puppet::Type.newtype(:ceph_config) do + + ensurable + + newparam(:name, :namevar => true) do + desc 'Section/setting name to manage from ./ceph.conf' + newvalues(/\S+\/\S+/) + end + + # required in order to be able to unit test file contents + # Note: purge will not work on over-ridden file_path + # lifted from ini_file + newparam(:path) do + desc 'A file path to over ride the default file path if necessary (DEPRECATED)' + validate do |value| + warning('The path property is deprecated and will be removed in a future release') + + unless value =~ /^\// + raise(Puppet::Error, "File paths must be fully qualified, not '#{value}'") + end + end + defaultto false + end + + newproperty(:value) do + desc 'The value of the setting to be defined.' + munge do |value| + value = value.to_s.strip + value.downcase! if value =~ /^(true|false)$/i + value + end + + def is_to_s( currentvalue ) + if resource.secret? + return '[old secret redacted]' + else + return currentvalue + end + end + + def should_to_s( newvalue ) + if resource.secret? + return '[new secret redacted]' + else + return newvalue + end + end + end + + newparam(:secret, :boolean => true) do + desc 'Whether to hide the value from Puppet logs. Defaults to `false`.' + + newvalues(:true, :false) + + defaultto false + end +end diff --git a/internal/gentypes/testdata/env/external_modules/ceph/lib/puppet/type/ceph_fs.rb b/internal/gentypes/testdata/env/external_modules/ceph/lib/puppet/type/ceph_fs.rb new file mode 100644 index 0000000..522b66d --- /dev/null +++ b/internal/gentypes/testdata/env/external_modules/ceph/lib/puppet/type/ceph_fs.rb @@ -0,0 +1,59 @@ +Puppet::Type.newtype(:ceph_fs) do + ensurable + + newparam(:name) do + isnamevar + desc 'Name of the file system' + newvalues(/.+/) + end + + newparam(:cluster) do + isnamevar + defaultto 'ceph' + desc 'Name of the cluster' + newvalues(/.+/) + end + + newproperty(:metadata_pool_name) do + desc 'Name of the metadata pool' + newvalues(/.+/) + end + + newproperty(:data_pool_name) do + desc 'Name of the data pool' + newvalues(/.+/) + end + + autorequire(:ceph_pool) do + [self[:metadata_pool_name], self[:data_pool_name]] + end + + validate do + if ! self[:metadata_pool_name] + raise(Puppet::Error, 'metadata_pool_name is required') + end + if ! self[:data_pool_name] + raise(Puppet::Error, 'data_pool_name is required') + end + end + + def self.title_patterns + cluster = Regexp.new(/[^\/]+/) + name = Regexp.new(/.+/) + [ + [ + /^(#{cluster})\/(#{name})$/, + [ + [:cluster], + [:name] + ] + ], + [ + /^(#{name})$/, + [ + [:name] + ] + ] + ] + end +end diff --git a/internal/gentypes/testdata/env/external_modules/ceph/lib/puppet/type/ceph_pool.rb b/internal/gentypes/testdata/env/external_modules/ceph/lib/puppet/type/ceph_pool.rb new file mode 100644 index 0000000..e12134a --- /dev/null +++ b/internal/gentypes/testdata/env/external_modules/ceph/lib/puppet/type/ceph_pool.rb @@ -0,0 +1,91 @@ +Puppet::Type.newtype(:ceph_pool) do + ensurable + + newparam(:name) do + isnamevar + desc 'Name of the pool' + newvalues(/.+/) + end + + newparam(:cluster) do + isnamevar + desc 'Name of the cluster' + newvalues(/.+/) + end + + newproperty(:pg_num) do + desc 'Number of PGs' + defaultto 64 + validate do |v| + if v.is_a?(Integer) + if v <= 0 + raise ArgumentError, "Invalid pg_num #{value}. Requires a positive value, not #{value.class}" + end + else + raise ArgumentError, "Invalid pg_num #{value}. Requires an Integer, not a #{value.class}" + end + return true + end + end + + newproperty(:pgp_num) do + desc 'Number of PGs for placement' + validate do |v| + if v.is_a?(Integer) + if v <= 0 + raise ArgumentError, "Invalid pgp_num #{value}. Requires a positive value, not #{value.class}" + end + else + raise ArgumentError, "Invalid pgp_num #{value}. Requires an Integer, not a #{value.class}" + end + return true + end + end + + newproperty(:size) do + desc 'Pool size' + validate do |v| + if v.is_a?(Integer) + if v <= 0 + raise ArgumentError, "Invalid size #{value}. Requires a positive value, not #{value.class}" + end + else + raise ArgumentError, "Invalid size #{value}. Requires an Integer, not a #{value.class}" + end + return true + end + end + + newproperty(:application) do + desc 'Associated application' + newvalues(/.+/) + end + + validate do + if self[:pgp_num] + if self[:pgp_num] > self[:pg_num] + raise(Puppet::Error, 'pgp_num should not exceed pg_num') + end + end + end + + def self.title_patterns + cluster = Regexp.new(/[^\/]+/) + name = Regexp.new(/.+/) + [ + [ + /^(#{cluster})\/(#{name})$/, + [ + [:cluster], + [:name] + ] + ], + [ + /^(#{name})$/, + [ + [:name] + ] + ] + ] + end +end diff --git a/internal/gentypes/testdata/env/external_modules/inifile/lib/puppet/provider/ini_setting/ruby.rb b/internal/gentypes/testdata/env/external_modules/inifile/lib/puppet/provider/ini_setting/ruby.rb index 40e0c15..c3a1f66 100644 --- a/internal/gentypes/testdata/env/external_modules/inifile/lib/puppet/provider/ini_setting/ruby.rb +++ b/internal/gentypes/testdata/env/external_modules/inifile/lib/puppet/provider/ini_setting/ruby.rb @@ -1,2 +1,154 @@ +# frozen_string_literal: true + +require File.expand_path('../../util/ini_file', __dir__) + Puppet::Type.type(:ini_setting).provide(:ruby) do + def self.instances + desc ' + Creates new ini_setting file, a specific config file with a provider that uses + this as its parent and implements the method + self.file_path, and that will provide the value for the path to the + ini file.' + raise(Puppet::Error, 'Ini_settings only support collecting instances when a file path is hard coded') unless respond_to?(:file_path) + + # figure out what to do about the seperator + ini_file = Puppet::Util::IniFile.new(file_path, '=') + resources = [] + ini_file.section_names.each do |section_name| + ini_file.get_settings(section_name).each do |setting, value| + resources.push( + new( + name: namevar(section_name, setting), + value: value, + ensure: :present, + ), + ) + end + end + resources + end + + def self.namevar(section_name, setting) + setting.nil? ? section_name : "#{section_name}/#{setting}" + end + + def exists? + if setting.nil? + ini_file.section_names.include?(section) + elsif ini_file.section?(section) + !ini_file.get_value(section, setting).nil? + elsif resource.parameters.key?(:force_new_section_creation) && !resource[:force_new_section_creation] + # for backwards compatibility, if a user is using their own ini_setting + # types but does not have this parameter, we need to fall back to the + # previous functionality which was to create the section. Anyone + # wishing to leverage this setting must define it in their provider + # type. See comments on + # https://github.com/puppetlabs/puppetlabs-inifile/pull/286 + resource[:ensure] = :absent + resource[:force_new_section_creation] + elsif resource.parameters.key?(:force_new_section_creation) && resource[:force_new_section_creation] + !resource[:force_new_section_creation] + else + false + end + end + + def create + if setting.nil? && resource[:value].nil? + ini_file.set_value(section) + else + ini_file.set_value(section, setting, separator, resource[:value]) + end + ini_file.save + @ini_file = nil + end + + def destroy + ini_file.remove_setting(section, setting) + ini_file.save + @ini_file = nil + end + + def value + ini_file.get_value(section, setting) + end + + def value=(_value) + if setting.nil? && resource[:value].nil? + ini_file.set_value(section) + else + ini_file.set_value(section, setting, separator, resource[:value]) + end + ini_file.save + end + + def section + # this method is here so that it can be overridden by a child provider + resource[:section] + end + + def setting + # this method is here so that it can be overridden by a child provider + resource[:setting] + end + + def file_path + # this method is here to support purging and sub-classing. + # if a user creates a type and subclasses our provider and provides a + # 'file_path' method, then they don't have to specify the + # path as a parameter for every ini_setting declaration. + # This implementation allows us to support that while still + # falling back to the parameter value when necessary. + if self.class.respond_to?(:file_path) + self.class.file_path + else + resource[:path] + end + end + + def separator + if resource.class.validattr?(:key_val_separator) + resource[:key_val_separator] || '=' + else + '=' + end + end + + def section_prefix + if resource.class.validattr?(:section_prefix) + resource[:section_prefix] || '[' + else + '[' + end + end + + def section_suffix + if resource.class.validattr?(:section_suffix) + resource[:section_suffix] || ']' + else + ']' + end + end + + def indent_char + if resource.class.validattr?(:indent_char) + resource[:indent_char] || ' ' + else + ' ' + end + end + + def indent_width + if resource.class.validattr?(:indent_width) + resource[:indent_width] || nil + else + nil + end + end + + private + + def ini_file + @ini_file ||= Puppet::Util::IniFile.new(file_path, separator, section_prefix, section_suffix, indent_char, indent_width) + end end diff --git a/internal/gentypes/testdata/env/external_modules/inifile/lib/puppet/util/external_iterator.rb b/internal/gentypes/testdata/env/external_modules/inifile/lib/puppet/util/external_iterator.rb new file mode 100644 index 0000000..19185af --- /dev/null +++ b/internal/gentypes/testdata/env/external_modules/inifile/lib/puppet/util/external_iterator.rb @@ -0,0 +1,32 @@ +# frozen_string_literal: true + +module Puppet::Util # rubocop:disable Style/ClassAndModuleChildren + # + # external_iterator.rb + # + class ExternalIterator + def initialize(coll) + @coll = coll + @cur_index = -1 + end + + def next + @cur_index += 1 + item_at(@cur_index) + end + + def peek + item_at(@cur_index + 1) + end + + private + + def item_at(index) + if @coll.length > index + [@coll[index], index] + else + [nil, nil] + end + end + end +end diff --git a/internal/gentypes/testdata/env/external_modules/inifile/lib/puppet/util/ini_file.rb b/internal/gentypes/testdata/env/external_modules/inifile/lib/puppet/util/ini_file.rb new file mode 100644 index 0000000..3acbf7a --- /dev/null +++ b/internal/gentypes/testdata/env/external_modules/inifile/lib/puppet/util/ini_file.rb @@ -0,0 +1,338 @@ +# frozen_string_literal: true + +require File.expand_path('external_iterator', __dir__) +require File.expand_path('ini_file/section', __dir__) + +module Puppet::Util # rubocop:disable Style/ClassAndModuleChildren + # + # ini_file.rb + # + class IniFile + def initialize(path, key_val_separator = ' = ', section_prefix = '[', section_suffix = ']', + indent_char = ' ', indent_width = nil) + + k_v_s = (key_val_separator =~ %r{^\s+$}) ? ' ' : key_val_separator.strip + + @section_prefix = section_prefix + @section_suffix = section_suffix + @indent_char = indent_char + @indent_width = indent_width&.to_i + + @section_regex = section_regex + @setting_regex = %r{^(\s*)([^#;\s]|[^#;\s].*?[^\s#{k_v_s}])(\s*#{k_v_s}[ \t]*)(.*)\s*$} + @commented_setting_regex = %r{^(\s*)[#;]+(\s*)(.*?[^\s#{k_v_s}])(\s*#{k_v_s}[ \t]*)(.*)\s*$} + + @path = path + @key_val_separator = key_val_separator + @section_names = [] + @sections_hash = {} + parse_file + end + + def section_regex + # Only put in prefix/suffix if they exist + r_string = '^\s*' + r_string += Regexp.escape(@section_prefix) + r_string += '(.*)' + r_string += Regexp.escape(@section_suffix) + r_string += '\s*$' + %r{#{r_string}} + end + + attr_reader :section_names + + def get_settings(section_name) + section = @sections_hash[section_name] + section.setting_names.each_with_object({}) do |setting, result| + result[setting] = section.get_value(setting) + end + end + + def section?(section_name) + @sections_hash.key?(section_name) + end + + def get_value(section_name, setting) + @sections_hash[section_name].get_value(setting) if @sections_hash.key?(section_name) + end + + def set_value(*args) + case args.size + when 1 + section_name = args[0] + when 3 + # Backwards compatible set_value function, See MODULES-5172 + (section_name, setting, value) = args + when 4 + (section_name, setting, separator, value) = args + end + + complete_setting = { + setting: setting, + separator: separator, + value: value + } + add_section(Section.new(section_name, nil, nil, nil, nil)) unless @sections_hash.key?(section_name) + + section = @sections_hash[section_name] + + if section.existing_setting?(setting) + update_line(section, setting, value) + section.update_existing_setting(setting, value) + elsif find_commented_setting(section, setting) + # So, this stanza is a bit of a hack. What we're trying + # to do here is this: for settings that don't already + # exist, we want to take a quick peek to see if there + # is a commented-out version of them in the section. + # If so, we'd prefer to add the setting directly after + # the commented line, rather than at the end of the section. + + # If we get here then we found a commented line, so we + # call "insert_inline_setting_line" to update the lines array + insert_inline_setting_line(find_commented_setting(section, setting), section, complete_setting) + + # Then, we need to tell the setting object that we hacked + # in an inline setting + section.insert_inline_setting(setting, value) + + # Finally, we need to update all of the start/end line + # numbers for all of the sections *after* the one that + # was modified. + section_index = @section_names.index(section_name) + increment_section_line_numbers(section_index + 1) + elsif !setting.nil? || !value.nil? + section.set_additional_setting(setting, value) + end + end + + def remove_setting(section_name, setting) + section = @sections_hash[section_name] + return unless section.existing_setting?(setting) + + # If the setting is found, we have some work to do. + # First, we remove the line from our array of lines: + remove_line(section, setting) + + # Then, we need to tell the setting object to remove + # the setting from its state: + section.remove_existing_setting(setting) + + # Finally, we need to update all of the start/end line + # numbers for all of the sections *after* the one that + # was modified. + section_index = @section_names.index(section_name) + decrement_section_line_numbers(section_index + 1) + + return unless section.empty? + + # By convention, it's time to remove this newly emptied out section + lines.delete_at(section.start_line) + decrement_section_line_numbers(section_index + 1) + @section_names.delete_at(section_index) + @sections_hash.delete(section.name) + end + + def save + global_empty = @sections_hash[''].empty? && @sections_hash[''].additional_settings.empty? + File.open(@path, 'w') do |fh| + @section_names.each_index do |index| + name = @section_names[index] + + section = @sections_hash[name] + + # We need a buffer to cache lines that are only whitespace + whitespace_buffer = [] + + if section.new_section? && !section.global? + fh.puts('') if (index == 1 && !global_empty) || index > 1 + + fh.puts("#{@section_prefix}#{section.name}#{@section_suffix}") + end + + unless section.new_section? + # write all of the pre-existing lines + (section.start_line..section.end_line).each do |line_num| + line = lines[line_num] + + # We buffer any lines that are only whitespace so that + # if they are at the end of a section, we can insert + # any new settings *before* the final chunk of whitespace + # lines. + if line.match?(%r{^\s*$}) + whitespace_buffer << line + else + # If we get here, we've found a non-whitespace line. + # We'll flush any cached whitespace lines before we + # write it. + flush_buffer_to_file(whitespace_buffer, fh) + fh.puts(line) + end + end + end + + # write new settings, if there are any + section.additional_settings.each_pair do |key, value| + fh.puts("#{@indent_char * (@indent_width || section.indentation || 0)}#{key}#{@key_val_separator}#{value}") + end + + if !whitespace_buffer.empty? + flush_buffer_to_file(whitespace_buffer, fh) + elsif section.new_section? && !section.additional_settings.empty? && (index < @section_names.length - 1) + # We get here if there were no blank lines at the end of the + # section. + # + # If we are adding a new section with a new setting, + # and if there are more sections that come after this one, + # we'll write one blank line just so that there is a little + # whitespace between the sections. + # if (section.end_line.nil? && + fh.puts('') + end + end + end + end + + private + + def add_section(section) + @sections_hash[section.name] = section + @section_names << section.name + end + + def parse_file + line_iter = create_line_iter + + # We always create a "global" section at the beginning of the file, for + # anything that appears before the first named section. + section = read_section('', 0, line_iter) + add_section(section) + line, line_num = line_iter.next + + while line + if (match = @section_regex.match(line)) + section = read_section(match[1], line_num, line_iter) + add_section(section) + end + line, line_num = line_iter.next + end + end + + def read_section(name, start_line, line_iter) + settings = {} + end_line_num = start_line + min_indentation = nil + empty = true + empty_line_count = 0 + loop do + line, line_num = line_iter.peek + if line_num.nil? || @section_regex.match(line) + # the global section always exists, even when it's empty; + # when it's empty, we must be sure it's thought of as new, + # which is signalled with a nil ending line + end_line_num = nil if name == '' && empty + return Section.new(name, start_line, end_line_num, settings, min_indentation, empty_line_count) + end + if (match = @setting_regex.match(line)) + settings[match[2]] = match[4] + indentation = match[1].length + min_indentation = [indentation, min_indentation || indentation].min + end + end_line_num = line_num + empty_line_count += 1 if line == "\n" + + empty = false + line_iter.next + end + end + + def update_line(section, setting, value) + (section.start_line..section.end_line).each do |line_num| + next unless (match = @setting_regex.match(lines[line_num])) + + lines[line_num] = "#{match[1]}#{match[2]}#{match[3]}#{value}" if match[2] == setting + end + end + + def remove_line(section, setting) + (section.start_line..section.end_line).each do |line_num| + next unless (match = @setting_regex.match(lines[line_num])) + + lines.delete_at(line_num) if match[2] == setting + end + end + + def create_line_iter + ExternalIterator.new(lines) + end + + def lines + @lines ||= IniFile.readlines(@path) + end + + # This is mostly here because it makes testing easier--we don't have + # to try to stub any methods on File. + def self.readlines(path) # rubocop:disable Lint/IneffectiveAccessModifier : Attempting to change breaks tests + # If this type is ever used with very large files, we should + # write this in a different way, using a temp + # file; for now assuming that this type is only used on + # small-ish config files that can fit into memory without + # too much trouble. + File.file?(path) ? File.readlines(path) : [] + end + + # This utility method scans through the lines for a section looking for + # commented-out versions of a setting. It returns `nil` if it doesn't + # find one. If it does find one, then it returns a hash containing + # two keys: + # + # :line_num - the line number that contains the commented version + # of the setting + # :match - the ruby regular expression match object, which can + # be used to mimic the whitespace from the comment line + def find_commented_setting(section, setting) + return nil if section.new_section? + + (section.start_line..section.end_line).each do |line_num| + next unless (match = @commented_setting_regex.match(lines[line_num])) + return { match: match, line_num: line_num } if match[3] == setting + end + nil + end + + # This utility method is for inserting a line into the existing + # lines array. The `result` argument is expected to be in the + # format of the return value of `find_commented_setting`. + def insert_inline_setting_line(result, section, complete_setting) + line_num = result[:line_num] + s = complete_setting + lines.insert(line_num + 1, "#{@indent_char * (@indent_width || section.indentation || 0)}#{s[:setting]}#{s[:separator]}#{s[:value]}") + end + + # Utility method; given a section index (index into the @section_names + # array), decrement the start/end line numbers for that section and all + # all of the other sections that appear *after* the specified section. + def decrement_section_line_numbers(section_index) + @section_names[section_index..(@section_names.length - 1)].each do |name| + section = @sections_hash[name] + section.decrement_line_nums + end + end + + # Utility method; given a section index (index into the @section_names + # array), increment the start/end line numbers for that section and all + # all of the other sections that appear *after* the specified section. + def increment_section_line_numbers(section_index) + @section_names[section_index..(@section_names.length - 1)].each do |name| + section = @sections_hash[name] + section.increment_line_nums + end + end + + def flush_buffer_to_file(buffer, file) + return if buffer.empty? + + buffer.each { |l| file.puts(l) } + buffer.clear + end + end +end diff --git a/internal/gentypes/testdata/env/external_modules/inifile/lib/puppet/util/ini_file/section.rb b/internal/gentypes/testdata/env/external_modules/inifile/lib/puppet/util/ini_file/section.rb new file mode 100644 index 0000000..4e29b5f --- /dev/null +++ b/internal/gentypes/testdata/env/external_modules/inifile/lib/puppet/util/ini_file/section.rb @@ -0,0 +1,96 @@ +# frozen_string_literal: true + +class Puppet::Util::IniFile # rubocop:disable Style/ClassAndModuleChildren + # + # section.rb + # + class Section + # Some implementation details: + # + # * `name` will be set to the empty string for the 'global' section. + # * there will always be a 'global' section, with a `start_line` of 0, + # but if the file actually begins with a real section header on + # the first line, then the 'global' section will have an + # `end_line` of `nil`. + # * `start_line` and `end_line` will be set to `nil` for a new non-global + # section. + def initialize(name, start_line, end_line, settings, indentation, empty_line_count = 0) + @name = name + @start_line = start_line + @end_line = end_line + @existing_settings = settings.nil? ? {} : settings + @additional_settings = {} + @indentation = indentation + @empty_line_count = empty_line_count + end + + attr_reader :name, :start_line, :end_line, :additional_settings, :indentation + + def global? + @name == '' + end + + def new_section? + # a new section (global or named) will always have `end_line` + # set to `nil` + @end_line.nil? + end + + def setting_names + @existing_settings.keys | @additional_settings.keys + end + + def get_value(setting_name) + @existing_settings[setting_name] || @additional_settings[setting_name] + end + + def existing_setting?(setting_name) + @existing_settings.key?(setting_name) + end + + # the global section is empty whenever it's new; + # other sections are empty when they have no lines + def empty? + global? ? new_section? : (start_line == end_line || (end_line && (end_line - @empty_line_count)) == start_line) + end + + def update_existing_setting(setting_name, value) + @existing_settings[setting_name] = value + end + + def remove_existing_setting(setting_name) + @end_line -= 1 if @existing_settings.delete(setting_name) && @end_line + end + + # This is a hacky method; it's basically called when we need to insert + # a new setting but we don't want it to appear at the very end of the + # section. Instead we hack it into the existing settings list and + # increment our end_line number--this assumes that the caller (`ini_file`) + # is doing some babysitting w/rt the other sections and the actual data + # of the lines. + def insert_inline_setting(setting_name, value) + @existing_settings[setting_name] = value + @end_line += 1 if @end_line + end + + def set_additional_setting(setting_name, value) + @additional_settings[setting_name] = value + end + + # Decrement the start and end line numbers for the section (if they are + # defined); this is intended to be called when a setting is removed + # from a section that comes before this section in the ini file. + def decrement_line_nums + @start_line -= 1 if @start_line + @end_line -= 1 if @end_line + end + + # Increment the start and end line numbers for the section (if they are + # defined); this is intended to be called when an inline setting is added + # to a section that comes before this section in the ini file. + def increment_line_nums + @start_line += 1 if @start_line + @end_line += 1 if @end_line + end + end +end diff --git a/internal/gentypes/testdata/golden/ceph_config.pp b/internal/gentypes/testdata/golden/ceph_config.pp new file mode 100644 index 0000000..a05cdc6 --- /dev/null +++ b/internal/gentypes/testdata/golden/ceph_config.pp @@ -0,0 +1,41 @@ +# This file was automatically generated on 2026-11-08 22:33:55 +1100. +# Use the 'puppet generate types' command to regenerate this file. + +Puppet::Resource::ResourceType3.new( + 'ceph_config', + [ + # The basic property that the resource should be in. + # + # Valid values are `present`, `absent`. + Puppet::Resource::Param(Enum['present', 'absent'], 'ensure'), + + # The value of the setting to be defined. + Puppet::Resource::Param(Any, 'value') + ], + [ + # Section/setting name to manage from ./ceph.conf + # + # Values can match `/\S+\/\S+/`. + Puppet::Resource::Param(Pattern[/\S+\/\S+/], 'name', true), + + # A file path to over ride the default file path if necessary (DEPRECATED) + Puppet::Resource::Param(Any, 'path'), + + # Whether to hide the value from Puppet logs. Defaults to `false`. + # + # Valid values are `true`, `false`. + Puppet::Resource::Param(Variant[Boolean, Enum['true', 'false']], 'secret'), + + # The specific backend to use for this `ceph_config` + # resource. You will seldom need to specify this --- OpenVox will usually + # discover the appropriate provider for your platform.Available providers are: + # + # ini_setting + # : + Puppet::Resource::Param(Any, 'provider') + ], + { + /(?m-ix:(.*))/ => ['name'] + }, + true, + false) diff --git a/internal/gentypes/testdata/golden/ceph_fs.pp b/internal/gentypes/testdata/golden/ceph_fs.pp new file mode 100644 index 0000000..72a190b --- /dev/null +++ b/internal/gentypes/testdata/golden/ceph_fs.pp @@ -0,0 +1,46 @@ +# This file was automatically generated on 2026-11-08 22:33:55 +1100. +# Use the 'puppet generate types' command to regenerate this file. + +Puppet::Resource::ResourceType3.new( + 'ceph_fs', + [ + # The basic property that the resource should be in. + # + # Valid values are `present`, `absent`. + Puppet::Resource::Param(Enum['present', 'absent'], 'ensure'), + + # Name of the metadata pool + # + # Values can match `/.+/`. + Puppet::Resource::Param(Pattern[/.+/], 'metadata_pool_name'), + + # Name of the data pool + # + # Values can match `/.+/`. + Puppet::Resource::Param(Pattern[/.+/], 'data_pool_name') + ], + [ + # Name of the file system + # + # Values can match `/.+/`. + Puppet::Resource::Param(Pattern[/.+/], 'name', true), + + # Name of the cluster + # + # Values can match `/.+/`. + Puppet::Resource::Param(Pattern[/.+/], 'cluster', true), + + # The specific backend to use for this `ceph_fs` + # resource. You will seldom need to specify this --- OpenVox will usually + # discover the appropriate provider for your platform.Available providers are: + # + # ceph + # : Provider for ceph filesystem + Puppet::Resource::Param(Any, 'provider') + ], + { + /^((?-mix:[^\/]+))\/((?-mix:.+))$/ => ['cluster', 'name'], + /^((?-mix:.+))$/ => ['name'] + }, + true, + false) diff --git a/internal/gentypes/testdata/golden/ceph_pool.pp b/internal/gentypes/testdata/golden/ceph_pool.pp new file mode 100644 index 0000000..1fe821f --- /dev/null +++ b/internal/gentypes/testdata/golden/ceph_pool.pp @@ -0,0 +1,50 @@ +# This file was automatically generated on 2026-11-08 22:33:55 +1100. +# Use the 'puppet generate types' command to regenerate this file. + +Puppet::Resource::ResourceType3.new( + 'ceph_pool', + [ + # The basic property that the resource should be in. + # + # Valid values are `present`, `absent`. + Puppet::Resource::Param(Enum['present', 'absent'], 'ensure'), + + # Number of PGs + Puppet::Resource::Param(Any, 'pg_num'), + + # Number of PGs for placement + Puppet::Resource::Param(Any, 'pgp_num'), + + # Pool size + Puppet::Resource::Param(Any, 'size'), + + # Associated application + # + # Values can match `/.+/`. + Puppet::Resource::Param(Pattern[/.+/], 'application') + ], + [ + # Name of the pool + # + # Values can match `/.+/`. + Puppet::Resource::Param(Pattern[/.+/], 'name', true), + + # Name of the cluster + # + # Values can match `/.+/`. + Puppet::Resource::Param(Pattern[/.+/], 'cluster', true), + + # The specific backend to use for this `ceph_pool` + # resource. You will seldom need to specify this --- OpenVox will usually + # discover the appropriate provider for your platform.Available providers are: + # + # ceph + # : Provider for ceph pools + Puppet::Resource::Param(Any, 'provider') + ], + { + /^((?-mix:[^\/]+))\/((?-mix:.+))$/ => ['cluster', 'name'], + /^((?-mix:.+))$/ => ['name'] + }, + true, + false)