From f10800bd062e17a47848d044c77852fa8208cee0 Mon Sep 17 00:00:00 2001 From: unkin-agent Date: Mon, 9 Nov 2026 00:08:09 +1100 Subject: [PATCH] Evaluate provider load-time code in a bounded subset - add an evaluator for constants, locals, define loops, inlined singleton methods and own-type validproperties - cap inline depth, world steps and allocation - model puppet/util/inifile's classes and %i symbols - vendor patroni and zfs_core fixtures and the full yumrepo provider --- internal/gentypes/eval.go | 527 ++++++++++++++++++ internal/gentypes/eval_test.go | 183 ++++++ internal/gentypes/fuzz_test.go | 12 + internal/gentypes/generate.go | 3 +- internal/gentypes/lexer.go | 2 +- internal/gentypes/load.go | 67 ++- internal/gentypes/parse.go | 112 +++- .../env/external_modules/patroni/LICENSE | 14 + .../provider/patroni_dcs_config/patronictl.rb | 62 +++ .../patroni/lib/puppet/provider/patronictl.rb | 40 ++ .../lib/puppet/type/patroni_dcs_config.rb | 21 + .../lib/puppet/provider/yumrepo/inifile.rb | 408 +++++++++++++- .../env/external_modules/zfs_core/LICENSE | 201 +++++++ .../zfs_core/lib/puppet/provider/zfs/zfs.rb | 102 ++++ .../zfs_core/lib/puppet/type/zfs.rb | 192 +++++++ .../testdata/golden/patroni_dcs_config.pp | 31 ++ internal/gentypes/testdata/golden/zfs.pp | 146 +++++ 17 files changed, 2082 insertions(+), 41 deletions(-) create mode 100644 internal/gentypes/eval.go create mode 100644 internal/gentypes/eval_test.go create mode 100644 internal/gentypes/testdata/env/external_modules/patroni/LICENSE create mode 100644 internal/gentypes/testdata/env/external_modules/patroni/lib/puppet/provider/patroni_dcs_config/patronictl.rb create mode 100644 internal/gentypes/testdata/env/external_modules/patroni/lib/puppet/provider/patronictl.rb create mode 100644 internal/gentypes/testdata/env/external_modules/patroni/lib/puppet/type/patroni_dcs_config.rb create mode 100644 internal/gentypes/testdata/env/external_modules/zfs_core/LICENSE create mode 100644 internal/gentypes/testdata/env/external_modules/zfs_core/lib/puppet/provider/zfs/zfs.rb create mode 100644 internal/gentypes/testdata/env/external_modules/zfs_core/lib/puppet/type/zfs.rb create mode 100644 internal/gentypes/testdata/golden/patroni_dcs_config.pp create mode 100644 internal/gentypes/testdata/golden/zfs.pp diff --git a/internal/gentypes/eval.go b/internal/gentypes/eval.go new file mode 100644 index 0000000..3f21e23 --- /dev/null +++ b/internal/gentypes/eval.go @@ -0,0 +1,527 @@ +package gentypes + +import ( + "errors" + "fmt" + "slices" + "strings" +) + +// Evaluator budgets: inlined singleton-method depth, and the tokens and bytes one world may spend. +const ( + maxCalls = 8 + maxWorldSteps = 1 << 24 + maxWorldAlloc = 1 << 26 +) + +// sdef is a singleton method body without parameters, evaluated in the lexical scope of the file defining it. +type sdef struct { + toks []token + start, end int + consts map[string]rval + cref []string + mod, dir string + file, src string +} + +var errNext = errors.New("next") + +func (w *world) classSdefs(name string) map[string]*sdef { + if w.sdefs == nil { + w.sdefs = map[string]map[string]*sdef{} + } + if w.sdefs[name] == nil { + w.sdefs[name] = map[string]*sdef{} + } + return w.sdefs[name] +} + +// charge counts n bytes against the world's allocation budget. +func (p *parser) charge(n int) { + b := &p.alloc + if p.w != nil { + b = &p.w.alloc + } + if *b += n; *b > maxWorldAlloc { + panic(errBudget) + } +} + +// defSingleton records the singleton method whose name is at p.i+off; a method taking parameters is opaque. +func (c *classCtx) defSingleton(p *parser, name string, off int) *sdef { + start := p.i + off + 1 + switch t := p.at(off + 1); { + case t.kind == tNL || t.text == ";": + case t.text == "(" && !t.space && p.at(off+2).text == ")": + start += 2 + default: + c.opaque(name) + return nil + } + sd := &sdef{toks: p.toks, start: start, consts: p.consts, cref: slices.Clone(p.cref), mod: p.mod, dir: p.dir, file: p.file, src: p.src} + if c.sdefs == nil { + c.sdefs = map[string]*sdef{} + } + c.sdefs[name] = sd + return sd +} + +// opaque marks singleton methods w10k does not evaluate, such as accessors and command methods. +func (c *classCtx) opaque(names ...string) { + if c.sdefs == nil { + c.sdefs = map[string]*sdef{} + } + for _, n := range names { + c.sdefs[n] = nil + } +} + +// singleton finds singleton method name on c's class, then up its user superclasses. +func (p *parser) singleton(c *classCtx, name string) (sd *sdef, found bool, err error) { + if sd, ok := c.sdefs[name]; ok { + return sd, true, nil + } + if c.parentUnknown { + return nil, false, fmt.Errorf("singleton method %s: the parent provider is not modelled", name) + } + for k := c.parent; k != "" && p.w.user[k]; k = p.w.sup[k] { + if sd, ok := p.w.sdefs[k][name]; ok { + return sd, true, nil + } + } + return nil, false, nil +} + +// call evaluates a method call on self without arguments: a user singleton method, or resource_type in a provider. +func (p *parser) call(name string) (rval, error) { + c := p.cls + if c == nil { + return rval{}, fmt.Errorf("undefined local variable or method %s", name) + } + sd, found, err := p.singleton(c, name) + switch { + case err != nil: + return rval{}, err + case found && sd == nil: + return rval{}, fmt.Errorf("singleton method %s is not evaluable", name) + case found: + return p.inline(sd, name) + case name == "resource_type" && c.typ != nil: + return rval{k: vType, s: c.typ.name}, nil + } + return rval{}, fmt.Errorf("undefined local variable or method %s", name) +} + +// inline evaluates a singleton method body of local assignments and expressions and returns its last value. +func (p *parser) inline(sd *sdef, name string) (rval, error) { + if p.calls >= maxCalls { + return rval{}, fmt.Errorf("singleton method %s nested deeper than %d", name, maxCalls) + } + q := &parser{toks: sd.toks, i: sd.start, consts: sd.consts, used: map[int]bool{}, w: p.w, defined: p.w.defined, mod: sd.mod, dir: sd.dir, + file: sd.file, src: sd.src, cref: sd.cref, depth: p.depth, cls: p.cls, calls: p.calls + 1, locals: map[string]rval{}} + if len(sd.cref) > 0 { + q.scope = sd.cref[len(sd.cref)-1] + } + last := rval{k: vNil} + for { + q.skipNL() + if q.is(tIdent, "end") { + if q.i != sd.end { + return rval{}, fmt.Errorf("%s: unsupported end", name) + } + return last, nil + } + local := "" + if isLocal(q.cur()) && q.assigns() { + local = q.take().text + q.take() + } + v, err := q.eval() + if err != nil { + return rval{}, fmt.Errorf("%s: %w", name, err) + } + if local != "" { + q.locals[local] = v + } + last = v + if t := q.cur(); t.kind != tNL && t.text != ";" && !q.is(tIdent, "end") { + return rval{}, fmt.Errorf("%s: unsupported %s", name, describe(t)) + } + } +} + +// eval evaluates an expression: literals, locals, constants, defined?, calls on self, allowlisted methods, String#+ +// and ==/!=. It stops before .each, which only a statement takes. +func (p *parser) eval() (rval, error) { + defer func() { p.depth-- }() + if err := p.enter(); err != nil { + return rval{}, err + } + v, err := p.sum() + if err != nil || !p.op("==") && !p.op("!=") { + return v, err + } + neg := p.take().text == "!=" + p.skipNL() + w, err := p.sum() + if err != nil { + return v, err + } + eq, err := rubyEq(v, w) + if eq != neg { + return rval{k: vTrue}, err + } + return rval{k: vFalse}, err +} + +func (p *parser) sum() (rval, error) { + v, err := p.postfix() + for err == nil && p.op("+") { + p.take() + p.skipNL() + var w rval + if w, err = p.postfix(); err != nil { + break + } + if v.k != vStr || w.k != vStr { + return v, fmt.Errorf("%s + %s", v.kindName(), w.kindName()) + } + p.charge(len(v.s) + len(w.s)) + v.s += w.s + } + return v, err +} + +func (p *parser) postfix() (rval, error) { + v, err := p.atom() + for err == nil { + switch { + case v.k == vStr && p.cur().kind == tStr: + var w rval + if w, err = p.primary(); err == nil { + p.charge(len(v.s) + len(w.s)) + v.s += w.s + } + case p.op(".") && p.at(1).kind == tIdent && p.at(1).text != "each": + p.take() + v, err = p.method(v, p.take().text) + default: + return v, nil + } + } + return v, err +} + +// method applies allowlisted method m to v. Only reject takes a block; a do block after any other method belongs to +// the enclosing call. +func (p *parser) method(v rval, m string) (rval, error) { + if m == "reject" && v.k == vArray { + return p.reject(v) + } + if p.op("(") && !p.cur().space || p.op("{") { + return v, fmt.Errorf("unsupported arguments or block for %s", m) + } + switch { + case m == "freeze" && v.k != vType: + return v, nil + case m == "to_s" && (v.k == vStr || v.k == vSym): + return rval{k: vStr, s: v.s}, nil + case m == "to_sym" && (v.k == vStr || v.k == vSym): + return rval{k: vSym, s: v.s}, nil + case m == "validproperties" && v.k == vType: + return p.validProperties(v.s) + } + return v, fmt.Errorf("unsupported %s#%s", v.kindName(), m) +} + +// 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 { + if !rubyName.MatchString(n) { + return rval{}, fmt.Errorf("unsupported property name %q", n) + } + out.arr = append(out.arr, rval{k: vSym, s: n}) + } + p.charge(16 * len(out.arr)) + return out, nil +} + +// reject keeps the elements for which its block, with the element bound to the block's parameter, is falsy. +func (p *parser) reject(v rval) (rval, error) { + if p.is(tIdent, "do") && p.noDo { + return v, fmt.Errorf("a do block here belongs to the enclosing call") + } + out := rval{k: vArray} + err := p.block(v.arr, func(e rval, closeTok string) error { + p.skipNL() + r, err := p.eval() + p.skipNL() + if err == nil && !p.closes(closeTok) { + err = fmt.Errorf("reject: unsupported %s", describe(p.cur())) + } + if r.k == vNil || r.k == vFalse { + out.arr = append(out.arr, e) + } + return err + }) + p.charge(16 * len(out.arr)) + return out, err +} + +// block runs body once per element with the cursor at the start of the do or brace block at the cursor and the +// element bound to its one parameter, then leaves the cursor after the block. An empty list never runs the body. +func (p *parser) block(elems []rval, body func(e rval, closeTok string) error) error { + if !p.is(tIdent, "do") && !p.op("{") { + return fmt.Errorf("expected a block") + } + open := p.i + if err := p.skipBlock(); err != nil { + return err + } + end := p.i + p.i = open + closeTok := "end" + if p.take().text == "{" { + closeTok = "}" + } + if !p.op("|") || !isLocal(p.at(1)) || p.at(2).text != "|" { + return fmt.Errorf("unsupported block parameters") + } + param := p.at(1).text + start := p.i + 3 + saved := p.locals + defer func() { p.locals = saved }() + for _, e := range elems { + p.locals = make(map[string]rval, len(saved)+1) + for k, x := range saved { + p.locals[k] = x + } + p.locals[param] = e + p.i = start + if err := body(e, closeTok); err != nil && err != errNext { + return err + } + } + p.i = end + return nil +} + +func (p *parser) atom() (rval, error) { + t := p.cur() + switch { + case t.kind == tIdent && t.text == "defined?": + return p.definedExpr() + case isLocal(t) && (p.locals != nil || p.cls != nil): + if _, ok := p.locals[t.text]; ok { + return p.primary() + } + binary := p.at(1).text == "+" && (!p.at(1).space || p.at(2).space) + if n := p.at(1); n.kind != tNL && n.kind != tEOF && (n.kind != tOp || !callEnds[n.text] && !binary) && (n.kind != tIdent || !reserved[n.text]) { + return rval{}, fmt.Errorf("unsupported call %s with arguments", t.text) + } + 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 + } + return p.primary() +} + +// callEnds are the tokens that may follow a method call without arguments. +var callEnds = set(". == != ) ] } , ;") + +// definedExpr evaluates defined?(Const) or defined? Const. A constant w10k does not see may be defined by a file +// another input loaded first, so a false result is only allowed where conditional assignment accounts for it. +func (p *parser) definedExpr() (rval, error) { + p.take() + paren := p.op("(") && !p.cur().space + if paren { + p.take() + } + if p.cur().kind != tConst { + return rval{}, fmt.Errorf("unsupported defined? operand %s", describe(p.cur())) + } + path, err := p.constPath() + if err != nil { + return rval{}, err + } + if paren { + if err := p.expect(")"); err != nil { + return rval{}, err + } + } + if p.constDefined(path) { + return rval{k: vStr, s: "constant"}, nil + } + if !p.condAssign { + return rval{}, fmt.Errorf("defined?(%s) depends on what other inputs loaded", path) + } + p.undetermined = true + return rval{k: vNil}, nil +} + +func (p *parser) constDefined(path string) bool { + if _, ok := p.consts[path]; ok { + return true + } + if _, ok := p.consts[p.scope+"::"+path]; ok && p.scope != "" { + return true + } + return p.defined[path] || p.w != nil && p.crefConst(path) != "" +} + +// crefConst resolves path in the enclosing lexical scopes' own constants, innermost first, which Ruby searches +// before any ancestor. +func (p *parser) crefConst(path string) string { + for i := len(p.cref) - 1; i >= 0; i-- { + if q := p.cref[i] + "::" + path; p.w.defined[q] { + return q + } + } + return "" +} + +// rubyEq is == on two evaluated values; Float operands and values w10k cannot compare are an error. +func rubyEq(a, b rval) (bool, error) { + comparable := func(v rval) bool { + return v.k == vStr || v.k == vSym || v.k == vNil || v.k == vTrue || v.k == vFalse || v.k == vNum && !strings.ContainsAny(v.s, ".e") + } + if !comparable(a) || !comparable(b) { + return false, fmt.Errorf("unsupported %s == %s", a.kindName(), b.kindName()) + } + return a.k == b.k && a.s == b.s, nil +} + +// rubyToS is to_s as string interpolation calls it. +func rubyToS(v rval) (string, bool) { + switch v.k { + case vStr, vSym, vNum, vNil: + return v.s, true + case vTrue: + return "true", true + case vFalse: + return "false", true + } + return "", false +} + +// evalStmt evaluates a class-level define_method or .each loop, declining any other statement. +func (p *parser) evalStmt(c *classCtx) (bool, error) { + if p.is(tIdent, "define_method") { + return true, p.defineMethod(c) + } + if !p.eachAhead() { + return false, nil + } + saved, savedLocals := p.cls, p.locals + p.cls = c + if p.locals == nil { + p.locals = map[string]rval{} + } + defer func() { p.cls, p.locals = saved, savedLocals }() + v, err := p.eval() + if err != nil { + return true, err + } + if !p.op(".") || p.at(1).text != "each" { + return true, fmt.Errorf("unsupported %s", p.construct()) + } + p.i += 2 + if v.k != vArray { + return true, fmt.Errorf("%s#each", v.kindName()) + } + return true, p.block(v.arr, func(_ rval, closeTok string) error { + return p.body(closeTok, func() (bool, error) { return p.loopStmt(c) }) + }) +} + +// eachAhead reports whether the statement at the cursor calls .each with a block outside any brackets. +func (p *parser) eachAhead() bool { + depth := 0 + for j := p.i; j+2 < len(p.toks); j++ { + t := p.toks[j] + switch { + case t.kind == tEOF || depth == 0 && (t.kind == tNL || t.text == ";"): + return false + case t.kind == tOp && strings.Contains("([{", t.text): + depth++ + case t.kind == tOp && strings.Contains(")]}", t.text): + depth-- + case depth == 0 && t.kind == tOp && t.text == "." && p.toks[j+1].text == "each" && (p.toks[j+2].text == "do" || p.toks[j+2].text == "{"): + return true + } + } + return false +} + +// loopStmt allows define_method and next, optionally under an if or unless modifier, in a define loop. +func (p *parser) loopStmt(c *classCtx) (bool, error) { + switch { + case p.is(tIdent, "define_method"): + return true, p.defineMethod(c) + case p.is(tIdent, "next"): + p.take() + next := true + if p.is(tIdent, "if") || p.is(tIdent, "unless") { + unless := p.take().text == "unless" + v, err := p.eval() + if err != nil { + return true, err + } + next = (v.k != vNil && v.k != vFalse) != unless + } + if next { + return true, errNext + } + return true, nil + } + return true, fmt.Errorf("unsupported %s in a define loop", p.construct()) +} + +// defineMethod records define_method(name) do ... end as an instance method with the current default visibility; +// the block runs only when the method is called. +func (p *parser) defineMethod(c *classCtx) error { + p.take() + saved, savedNoDo := p.cls, p.noDo + p.cls = c + paren := p.op("(") && !p.cur().space + p.noDo = !paren + defer func() { p.cls, p.noDo = saved, savedNoDo }() + if paren { + p.take() + } + v, err := p.eval() + if err != nil { + return err + } + if paren { + if err := p.expect(")"); err != nil { + return err + } + } + if v.k != vSym && v.k != vStr { + return fmt.Errorf("define_method name is a %s", v.kindName()) + } + if !p.is(tIdent, "do") && (!p.op("{") || !paren) { + return fmt.Errorf("define_method without a block") + } + if !c.private { + c.methods[v.s] = true + } + return p.skipBlock() +} diff --git a/internal/gentypes/eval_test.go b/internal/gentypes/eval_test.go new file mode 100644 index 0000000..33277d8 --- /dev/null +++ b/internal/gentypes/eval_test.go @@ -0,0 +1,183 @@ +package gentypes + +import ( + "errors" + "slices" + "strconv" + "strings" + "testing" + "time" +) + +const evalParent = "require 'puppet/util/inifile'\nclass Puppet::Provider::Zqp < Puppet::Provider\n initvars\n def self.tp\n" + + " resource_type.validproperties.reject { |p| p.to_sym == :ensure }\n end\n PP = [:x]\n def self.pp\n PP\n end\nend\n" + + "module PuppetX\n module Q\n class FileCollection < Puppet::Util::IniConfig::FileCollection; end\n" + + " File = FileCollection\n class Sub < File; end\n end\nend\n" + +// evalProvider evaluates src as the body of Puppet::Type.type(:t).provide(:x) for a type t with properties b, +// ensure and a, after loading evalParent; parent sets parent: Puppet::Provider::Zqp. +func evalProvider(src string, parent bool) (c *classCtx, consts map[string]rval, w *world, err error) { + defer guard(&err) + w = newWorld(nil) + w.typ = &rtype{name: "t", validprops: []string{"b", "ensure", "a"}} + if err := (&parser{w: w}).load(libFile{mod: "m", rel: "puppet_x/zqp.rb", src: evalParent}); err != nil { + return nil, nil, w, err + } + toks, err := lex(src) + if err != nil { + return nil, nil, w, err + } + p := &parser{toks: toks, consts: map[string]rval{}, used: map[int]bool{}, w: w, defined: w.defined, mod: "m", dir: "puppet/provider/t", file: "x.rb", src: src} + c = &classCtx{kind: kProv, methods: map[string]bool{}, smethods: map[string]bool{}, parent: "Puppet::Provider", block: true, typ: w.typ} + if parent { + c.parent = "Puppet::Provider::Zqp" + } + return c, p.consts, w, p.body("", p.classStmt("Puppet::Type::t", c)) +} + +func inspect(v rval) string { + switch v.k { + case vStr: + return `"` + v.s + `"` + case vSym: + return ":" + v.s + case vArray: + var parts []string + for _, e := range v.arr { + parts = append(parts, inspect(e)) + } + return "[" + strings.Join(parts, ", ") + "]" + case vNum: + return v.s + } + s, _ := rubyToS(v) + return s +} + +// Each body loads in openvox 9.3.0 on Ruby 3.3 with the result in ruby (X's inspect, or - when X is unset, and the +// provider's public and private instance methods); w10k must reach want, or skip where it cannot prove the result. +var evalCases = []struct{ name, src, ruby, want string }{ + {"selftype", "X = Puppet::Type.type(:t).validproperties\n", "[:b, :ensure, :a] pub=[] priv=[]", "[:b, :ensure, :a] pub=[]"}, + {"scall own", "def self.tp\n resource_type.validproperties.reject { |p| p.to_sym == :ensure }\nend\nX = tp\n", "[:b, :a] pub=[] priv=[]", "[:b, :a] pub=[]"}, + {"parent", "X = tp\n", "[:b, :a] pub=[] priv=[]", "[:b, :a] pub=[]"}, + {"reject do", "X = [:c, :ensure, :a].reject do |q|\n q == :ensure\nend\n", "[:c, :a] pub=[] priv=[]", "[:c, :a] pub=[]"}, + {"sym to_s plus", "X = :a.to_s + '='\n", "\"a=\" pub=[] priv=[]", "\"a=\" pub=[]"}, + {"interp to_s", "X = \"#{:s}#{nil}#{1}#{true}#{'x'}\"\n", "\"s1truex\" pub=[] priv=[]", "\"s1truex\" pub=[]"}, + {"to_sym", "X = 'a'.to_sym\n", ":a pub=[] priv=[]", ":a pub=[]"}, + {"sym to_sym freeze", "X = :a.to_sym.to_s.freeze\n", "\"a\" pub=[] priv=[]", "\"a\" pub=[]"}, + {"eq sym", "X = :a == :a\n", "true pub=[] priv=[]", "true pub=[]"}, + {"eq sym str", "X = :a == 'a'\n", "false pub=[] priv=[]", "false pub=[]"}, + {"ne", "X = :a != 'a'\n", "true pub=[] priv=[]", "true pub=[]"}, + {"eq nil false", "X = nil == false\n", "false pub=[] priv=[]", "false pub=[]"}, + {"eq int", "X = 1 == 1\n", "true pub=[] priv=[]", "true pub=[]"}, + {"eq float", "X = 1.0 == 1\n", "true pub=[] priv=[]", "skip"}, + {"percent i", "X = %i[a b]\n", "[:a, :b] pub=[] priv=[]", "[:a, :b] pub=[]"}, + {"percent w", "X = %w[a b]\n", "[\"a\", \"b\"] pub=[] priv=[]", "[\"a\", \"b\"] pub=[]"}, + {"defined true", "X = defined?(String)\n", "\"constant\" pub=[] priv=[]", "\"constant\" pub=[]"}, + {"defined false", "X = defined?(Nope)\n", "nil pub=[] priv=[]", "skip"}, + {"unless defined", "K = '-'.freeze unless defined? K\n", "- pub=[] priv=[]", "- pub=[]"}, + {"unless defined read", "K = '-'.freeze unless defined? K\nX = K\n", "\"-\" pub=[] priv=[]", "skip"}, + {"unless defined skip", "K = 1\nK2 = 2 unless defined?(K)\nX = K2\n", "raise NameError", "skip"}, + {"if modifier", "X = 1 if 1 == 1\n", "1 pub=[] priv=[]", "1 pub=[]"}, + {"unless modifier", "X = 1 unless 1 == 1\n", "- pub=[] priv=[]", "- pub=[]"}, + {"loop literal", "[:a, :b].each do |f|\n define_method(f) do\n end\n define_method(f.to_s + '=') { |v| }\nend\n", "- pub=[:a, :a=, :b, :b=] priv=[]", "- pub=[:a, :a=, :b, :b=]"}, + {"loop next if", "X = Puppet::Type.type(:t).validproperties\nX.each do |p|\n next if p == :ensure\n define_method(p) do\n end\n define_method(\"#{p}=\") do |v|\n end\nend\n", "[:b, :ensure, :a] pub=[:a, :a=, :b, :b=] priv=[]", "[:b, :ensure, :a] pub=[:a, :a=, :b, :b=]"}, + {"loop next unless", "[:q1, :q2].each do |m|\n next unless m == :q2\n define_method(m) {}\nend\n", "- pub=[:q2] priv=[]", "- pub=[:q2]"}, + {"loop scall to_sym", "def self.tp\n resource_type.validproperties\nend\ntp.each do |prop|\n define_method \"#{prop}=\".to_sym do |value|\n end\nend\n", "- pub=[:a=, :b=, :ensure=] priv=[]", "- pub=[:a=, :b=, :ensure=]"}, + {"visibility", "private\n[:p1].each { |m| define_method(m) {} }\ndefine_method(\"p2\") {}\npublic\ndefine_method(:z) {}\n", "- pub=[:z] priv=[:p1, :p2]", "- pub=[:z]"}, + {"bare define_method", "define_method(:zoned) do\nend\ndefine_method('zoned=') do |s|\nend\n", "- pub=[:zoned, :zoned=] priv=[]", "- pub=[:zoned, :zoned=]"}, + {"empty loop", "[].each do |x|\n raise 'no'\nend\n", "- pub=[] priv=[]", "- pub=[]"}, + {"raise loop", "[1].each do |x|\n raise 'no'\nend\n", "raise RuntimeError", "skip"}, + {"other type", "X = Puppet::Type.type(:file).validproperties\n", "[:content, :checksum_value, :target, :ensure, :owner, :group, :mode, :type, :seluser, :selrole, :seltype, :selrange, :ctime, :mtime] pub=[] priv=[]", "skip"}, + {"params", "def self.m(a)\n 1\nend\nX = m\n", "raise ArgumentError", "skip"}, + {"command", "commands tp: 'tp'\nX = tp\n", "raise Puppet::MissingCommand", "skip"}, + {"recursion", "def self.a\n a\nend\nX = a\n", "raise SystemStackError", "skip"}, + {"str plus sym", "X = 'a' + :b\n", "raise TypeError", "skip"}, + {"define_method int", "define_method(1) do\nend\n", "raise TypeError", "skip"}, + {"define_method no block", "define_method(:x)\n", "raise ArgumentError", "skip"}, + {"brace binds", "define_method \"q\".to_sym { }\n", "raise ArgumentError", "skip"}, + {"overwrite File", "File = 1\n", "- pub=[] priv=[]", "skip"}, + {"undefined", "X = Nope\n", "raise NameError", "skip"}, + {"call args", "X = foo 1\n", "raise NoMethodError", "skip"}, + {"hash each", "{ a: 1 }.each do |k|\n define_method(k) {}\nend\n", "raise TypeError", "skip"}, + {"call plus", "def self.s\n 'a'\nend\nX = s + s\n", "\"aa\" pub=[] priv=[]", "\"aa\" pub=[]"}, + {"if defined false", "X = 1 if defined?(Nope)\n", "- pub=[] priv=[]", "- pub=[]"}, + {"unless defined true", "X = 1 unless defined?(String)\n", "- pub=[] priv=[]", "- pub=[]"}, + {"parent const", "X = pp\n\n", "[:x] pub=[] priv=[]", "[:x] pub=[]"}, +} + +func TestEvaluator(t *testing.T) { + for _, c := range evalCases { + t.Run(c.name, func(t *testing.T) { + ctx, consts, _, err := evalProvider(c.src, strings.HasPrefix(c.name, "parent")) + got := "skip" + if err == nil { + x, ok := consts["X"] + got = "-" + if ok { + got = inspect(x) + } + var pub []string + for m := range ctx.methods { + pub = append(pub, ":"+m) + } + slices.Sort(pub) + got += " pub=[" + strings.Join(pub, ", ") + "]" + } + if got != c.want { + t.Fatalf("got %s (%v), want %s; ruby gives %s", got, err, c.want, c.ruby) + } + }) + } +} + +// In Ruby, File = FileCollection inside module Q makes class Sub < File a subclass of FileCollection. +func TestEvaluatorAlias(t *testing.T) { + _, _, w, err := evalProvider("", false) + if err != nil { + t.Fatal(err) + } + if w.kind["PuppetX::Q::File"] != kClass || w.sup["PuppetX::Q::Sub"] != "PuppetX::Q::File" { + t.Fatalf("alias File = FileCollection not usable as a superclass: %c %q", w.kind["PuppetX::Q::File"], w.sup["PuppetX::Q::Sub"]) + } +} + +func TestEvaluatorUnknownParent(t *testing.T) { + w := newWorld(nil) + w.typ = &rtype{name: "t"} + _, _, 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") + } +} + +// Each body costs more than the evaluator budgets allow; w10k must stop with a budget error, quickly. +func TestEvaluatorBudgets(t *testing.T) { + var b strings.Builder + b.WriteString("A0 = '" + strings.Repeat("x", 1024) + "'\n") + for i := 1; i <= 40; i++ { + b.WriteString("A" + strconv.Itoa(i) + " = A" + strconv.Itoa(i-1) + " + A" + strconv.Itoa(i-1) + "\n") + } + doubling := b.String() + fan := func(leaf string) string { + var b strings.Builder + b.WriteString("def self.a0\n " + leaf + "\nend\n") + for i := 1; i <= 6; i++ { + b.WriteString("def self.a" + strconv.Itoa(i) + "\n a" + strconv.Itoa(i-1) + strings.Repeat(" + a"+strconv.Itoa(i-1), 199) + "\nend\n") + } + return b.String() + "X = a6\n" + } + loop := "[" + strings.Repeat(":a, ", 3000) + ":a].each do |x|\n" + strings.Repeat(" next if x == :b\n", 3000) + "end\n" + for name, src := range map[string]string{"doubling constants": doubling, "fanned-out calls": fan("''"), "fanned-out strings": fan("'" + strings.Repeat("x", 1024) + "'"), "long loop": loop} { + t.Run(name, func(t *testing.T) { + start := time.Now() + _, _, _, err := evalProvider(src, false) + if !errors.Is(err, errLimit) { + t.Fatalf("got %v, want a budget error", err) + } + if d := time.Since(start); d > 30*time.Second { + t.Fatalf("budget took %v", d) + } + }) + } +} diff --git a/internal/gentypes/fuzz_test.go b/internal/gentypes/fuzz_test.go index c311c16..57fd0ed 100644 --- a/internal/gentypes/fuzz_test.go +++ b/internal/gentypes/fuzz_test.go @@ -40,3 +40,15 @@ func FuzzParseFile(f *testing.F) { _, _ = parsePType(src) }) } + +func FuzzEval(f *testing.F) { + for _, c := range evalCases { + f.Add(c.src) + } + f.Fuzz(func(t *testing.T, src string) { + _, _, _, _ = evalProvider(src, len(src)%2 == 0) + w := newWorld(nil) + w.typ = &rtype{name: "t", validprops: []string{"a", "ensure"}} + _, _, _ = providerFile(libFile{mod: "m", rel: "puppet/provider/t/x.rb", src: "Puppet::Type.type(:t).provide(:x) do\n" + src + "\nend\n"}, "t", false, w) + }) +} diff --git a/internal/gentypes/generate.go b/internal/gentypes/generate.go index d0d7582..f1b309a 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 = "5" +const Version = "6" var moduleName = regexp.MustCompile(`^[a-z][a-z0-9_]*$`) @@ -232,6 +232,7 @@ func generateOne(in string, out *os.Root, providers []string, resolve Resolver, if t == nil { return false, skipErr{fmt.Errorf("custom type %q was not defined", name)} } + w.typ = t names, err := providerNames(t, providers, w) if err != nil { return false, err diff --git a/internal/gentypes/lexer.go b/internal/gentypes/lexer.go index 8d9ffa7..39d5586 100644 --- a/internal/gentypes/lexer.go +++ b/internal/gentypes/lexer.go @@ -331,7 +331,7 @@ func (l *lexer) percent() error { if strings.ContainsRune(body, '\\') || (typ == 'W' || typ == 'I') && strings.Contains(body, "#") { return fmt.Errorf("unsupported escape or interpolation in %%%c literal", typ) } - l.emit(token{kind: tWords, words: strings.Fields(body)}) + l.emit(token{kind: tWords, words: strings.Fields(body), flags: string(typ)}) case 's': parts, err := l.quoted(open, cl, false, 0) if err != nil { diff --git a/internal/gentypes/load.go b/internal/gentypes/load.go index 76c4c9f..1bcc65a 100644 --- a/internal/gentypes/load.go +++ b/internal/gentypes/load.go @@ -26,6 +26,10 @@ type world struct { mods map[string][]string loaded map[string]bool gems map[string]bool + // typ is the type whose providers are loading; sdefs are user classes' singleton methods by class + typ *rtype + sdefs map[string]map[string]*sdef + steps, alloc int } // Constant kinds: module, class, a Puppet::Provider subclass, a Puppet::Provider::ParsedFile subclass. @@ -301,7 +305,7 @@ func (p *parser) namespace() error { }) } p.w.user[name] = true - return p.body("end", p.classStmt(name, &classCtx{kind: p.w.kind[name], methods: map[string]bool{}, smethods: map[string]bool{}})) + return p.body("end", p.classStmt(name, &classCtx{kind: p.w.kind[name], methods: map[string]bool{}, smethods: map[string]bool{}, sdefs: p.w.classSdefs(name), parent: p.w.sup[name]})) } func (p *parser) constPath() (string, error) { @@ -321,6 +325,13 @@ type classCtx struct { methods map[string]bool smethods map[string]bool lines map[string]bool + // singleton methods so far, the user superclass searched next, and for a provide block its type and top-level cref + sdefs map[string]*sdef + parent string + parentUnknown bool + typ *rtype + block bool + private bool } // Hooks Ruby or Puppet::Provider call on a class or module while loading it; defining one runs code w10k cannot see. @@ -352,9 +363,15 @@ func (p *parser) classStmt(name string, c *classCtx) func() (bool, error) { case t.kind == tIdent && (t.text == "module" || t.text == "class") && p.at(1).kind == tConst: return true, p.namespace() case t.kind == tConst && p.assigns(): - saved := p.scope - p.scope = name - defer func() { p.scope = saved }() + saved, savedCls := p.scope, p.cls + p.scope, p.cls = name, c + if c.block { + p.scope = "" + } + defer func() { p.scope, p.cls = saved, savedCls }() + if c.block && p.defined[t.text] { + return true, fmt.Errorf("%s = overwrites a constant puppet defines", t.text) + } return true, p.strictConstAssign() case p.assigns() && (t.kind == tIVar && !strings.HasPrefix(t.text, "@@") && (!providerIvars[t.text[1:]] || c.kind != kProv && c.kind != kParsed) || t.kind == tGVar && plainGlobal.MatchString(t.text) && t.text != "$stdout" && t.text != "$stderr" && t.text != "$stdin"): @@ -380,24 +397,32 @@ func (p *parser) classStmt(name string, c *classCtx) func() (bool, error) { case t.kind == tIdent && (c.kind == kProv || c.kind == kParsed) && providerDSL[t.text] && !c.smethods[t.text]: return true, p.providerCall(c) } + if ok, err := p.evalStmt(c); ok { + return true, err + } return true, fmt.Errorf("unsupported %s in %s", p.construct(), name) } } func (p *parser) defMethod(c *classCtx, single bool) error { - n := p.at(1).text + n, off := p.at(1).text, 1 if p.at(1).text == "self" && p.at(2).text == "." { - single, n = true, p.at(3).text + single, n, off = true, p.at(3).text, 3 } - if single { - if hooks[n] || providerDSL[n] || strings.HasPrefix(n, "dochook_") { - return fmt.Errorf("def self.%s runs while loading", n) - } - c.smethods[n] = true - } else { + if !single { c.methods[n] = true + return p.skipStatement() } - return p.skipStatement() + if hooks[n] || providerDSL[n] || strings.HasPrefix(n, "dochook_") { + return fmt.Errorf("def self.%s runs while loading", n) + } + c.smethods[n] = true + sd := c.defSingleton(p, n, off) + err := p.skipStatement() + if sd != nil { + sd.end = p.i - 1 + } + return err } func (p *parser) singletonBody(c *classCtx) (bool, error) { @@ -412,6 +437,7 @@ func (p *parser) singletonBody(c *classCtx) (bool, error) { return true, fmt.Errorf("%s %s shadows a class method", t.text, a) } c.smethods[a] = true + c.opaque(a, a+"=") } return true, err case t.kind == tIdent && (t.text == "private" || t.text == "protected" || t.text == "public") && (p.at(1).kind == tNL || p.at(1).text == ";"): @@ -453,7 +479,7 @@ func (p *parser) accessors(c *classCtx) error { func (p *parser) visibility(c *classCtx) error { if p.at(1).kind == tNL || p.at(1).text == ";" || p.at(1).kind == tEOF || p.closes("end") { - p.take() + c.private = p.take().text != "public" return nil } names, err := p.symArgs() @@ -536,6 +562,9 @@ func (p *parser) providerCall(c *classCtx) error { if !hash || slices.ContainsFunc(args[0].keys, func(k rval) bool { return k.k != vSym && k.k != vStr }) || slices.ContainsFunc(args[0].arr, func(v rval) bool { return v.k != vStr }) { return fmt.Errorf("%s takes one hash of names to strings", name) } + for _, k := range args[0].keys { + c.opaque(k.s) + } case "has_feature", "has_features": if len(args) == 0 || slices.ContainsFunc(args, func(v rval) bool { return v.k != vSym && v.k != vStr }) { return fmt.Errorf("%s takes feature names", name) @@ -544,6 +573,7 @@ func (p *parser) providerCall(c *classCtx) error { if len(args) != 2 || args[0].k != vSym && args[0].k != vStr || args[1].k != vStr { return fmt.Errorf("has_command takes a name and a string") } + c.opaque(args[0].s) if p.is(tIdent, "do") || p.op("{") { closeTok, err := p.blockOpen() if err != nil { @@ -833,6 +863,10 @@ func providerFile(f libFile, typ string, rsapi bool, w *world) (name, parent str return true, fmt.Errorf("unsupported provider name %q", name) } kind := byte(kProv) + c := &classCtx{methods: map[string]bool{}, smethods: map[string]bool{}, parent: "Puppet::Provider", block: true} + if w.typ != nil && w.typ.name == typ { + c.typ = w.typ + } if len(args) == 2 { if err := symHash(args[1], "provide "+name); err != nil { return true, err @@ -841,10 +875,12 @@ func providerFile(f libFile, typ string, rsapi bool, w *world) (name, parent str switch v.k { case vSym, vStr: parent = v.s + c.parentUnknown = true case vConst: if kind = w.kind[v.s]; kind != kProv && kind != kParsed { return true, fmt.Errorf("parent %s is not a provider class", v.s) } + c.parent = v.s default: return true, fmt.Errorf("unsupported provider parent %s", v.kindName()) } @@ -854,7 +890,8 @@ func providerFile(f libFile, typ string, rsapi bool, w *world) (name, parent str if err != nil || closeTok == "" { return true, err } - return true, p.body(closeTok, p.classStmt("Puppet::Type::"+typ, &classCtx{kind: kind, methods: map[string]bool{}, smethods: map[string]bool{}})) + c.kind = kind + return true, p.body(closeTok, p.classStmt("Puppet::Type::"+typ, c)) } if err := p.body("", p.fileStmt(provide)); err != nil { return "", "", p.wrap(err) diff --git a/internal/gentypes/parse.go b/internal/gentypes/parse.go index 5047b11..579f25c 100644 --- a/internal/gentypes/parse.go +++ b/internal/gentypes/parse.go @@ -39,15 +39,16 @@ type pattern struct { } type rtype struct { - name string - doc string - props []*attr - params []*attr - patterns []pattern - custom bool - rsapi bool - methods map[string]bool - private bool + name string + doc string + props []*attr + validprops []string + params []*attr + patterns []pattern + custom bool + rsapi bool + methods map[string]bool + private bool } type vkind int @@ -64,6 +65,8 @@ const ( vHash vConst vBlock + vType + vUndet ) type rval struct { @@ -101,6 +104,14 @@ type parser struct { src string cref []string guarded bool + // evaluator state: block and method locals, self's class, inlined call depth, and conditional-assignment flags + locals map[string]rval + cls *classCtx + calls int + noDo bool + condAssign bool + undetermined bool + alloc int } var ( @@ -174,6 +185,11 @@ func (p *parser) cur() token { if p.steps++; p.steps > 256*len(p.toks)+4096 { panic(errBudget) } + if p.w != nil { + if p.w.steps++; p.w.steps > maxWorldSteps { + panic(errBudget) + } + } return p.toks[p.i] } @@ -390,15 +406,32 @@ func (p *parser) constAssign() (bool, error) { save := p.i name := p.take().text p.take() - v, err := p.expr() + v, err := p.eval() + assign := true + if err == nil && (p.is(tIdent, "if") || p.is(tIdent, "unless")) { + unless := p.take().text == "unless" + p.condAssign, p.undetermined = true, false + var c rval + c, err = p.eval() + p.condAssign = false + if assign = (c.k != vNil && c.k != vFalse) != unless; p.undetermined { + v = rval{k: vUndet} + } + } if err != nil || p.cur().kind != tNL && p.cur().kind != tEOF && !p.op(";") { p.i = save return false, nil } + if !assign { + return true, nil + } if p.scope != "" { name = p.scope + "::" + name } p.consts[name] = v + if v.k == vConst && p.w != nil { + p.w.define(name, p.w.kind[v.s]) + } return true, nil } @@ -410,6 +443,21 @@ func (p *parser) strictConstAssign() error { return nil } +// iniConsts are the Puppet::Util::IniConfig and FileType constants require 'puppet/util/inifile' defines. +var iniConsts = strings.Split(`Puppet::Util::IniConfig m +Puppet::Util::IniConfig::File c +Puppet::Util::IniConfig::FileCollection c +Puppet::Util::IniConfig::IniParseError c +Puppet::Util::IniConfig::PhysicalFile c +Puppet::Util::IniConfig::Section c +Puppet::Util::FileType c +Puppet::Util::FileType::FileReadError c +Puppet::Util::FileType::FileTypeAixtab c +Puppet::Util::FileType::FileTypeCrontab c +Puppet::Util::FileType::FileTypeFlat c +Puppet::Util::FileType::FileTypeRam c +Puppet::Util::FileType::FileTypeSuntab c`, "\n") + var fileConsts = []string{"Puppet::Parameter::Boolean c", "Puppet::Property::Boolean c", "Puppet::Type::File::Owner c", "Puppet::Type::File::Group c", "Puppet::Type::File::Mode c"} // Libraries a type file may require without changing its type, present in openvox 9.3.0 and its Ruby; @@ -426,7 +474,7 @@ var ( "puppet_x": {"PuppetX m"}, "puppet/util/suidmanager": {"Puppet::Util::SUIDManager m"}, "puppet/util/filetype": {"Puppet::Util::FileType c"}, - "puppet/util/inifile": {"Puppet::Util::IniConfig m"}, + "puppet/util/inifile": iniConsts, "puppet/network/http_pool": {"Puppet::Network m", "Puppet::Network::HttpPool m"}, "puppet/type/file": fileConsts, "puppet/type/file/owner": fileConsts, "puppet/type/file/group": fileConsts, "puppet/type/file/mode": fileConsts, } @@ -637,7 +685,7 @@ func symName(v rval) (string, error) { } func (v rval) kindName() string { - return [...]string{"string", "symbol", "regex", "number", "true", "false", "nil", "array", "hash", "constant " + v.s, "block argument"}[v.k] + return [...]string{"string", "symbol", "regex", "number", "true", "false", "nil", "array", "hash", "constant " + v.s, "block argument", "type " + v.s, "constant set only if undefined"}[v.k] } func (p *parser) newtype() error { @@ -975,9 +1023,11 @@ func (t *rtype) addProp(a *attr) error { } if a.name == "ensure" { t.props = append([]*attr{a}, t.props...) + t.validprops = append(t.validprops, a.name) return nil } t.props = append(t.props, a) + t.validprops = append(t.validprops, a.name) return nil } @@ -1431,6 +1481,7 @@ func (p *parser) expr() (rval, error) { if err != nil { return v, err } + p.charge(len(v.s) + len(w.s)) v.s += w.s case v.k == vStr && p.op("+"): p.take() @@ -1442,6 +1493,7 @@ func (p *parser) expr() (rval, error) { if w.k != vStr { return v, fmt.Errorf("string + %s", w.kindName()) } + p.charge(len(v.s) + len(w.s)) v.s += w.s default: return v, nil @@ -1460,13 +1512,15 @@ func (p *parser) interp(parts []part) (string, error) { if err != nil { return "", fmt.Errorf("unsupported interpolation #{%s}", pt.text) } - sub := &parser{toks: toks, consts: p.consts, used: map[int]bool{}, depth: p.depth, scope: p.scope} + sub := &parser{toks: toks, consts: p.consts, used: map[int]bool{}, depth: p.depth, scope: p.scope, w: p.w, locals: p.locals} c, err := sub.expr() sub.skipNL() - if err != nil || c.k != vStr || sub.cur().kind != tEOF { + s, ok := rubyToS(c) + if err != nil || !ok || sub.cur().kind != tEOF { return "", fmt.Errorf("unsupported interpolation #{%s}", pt.text) } - b.WriteString(c.s) + p.charge(len(s)) + b.WriteString(s) } return b.String(), nil } @@ -1556,8 +1610,12 @@ func (p *parser) primary() (rval, error) { case tWords: p.take() v := rval{k: vArray} + k := vStr + if t.flags == "i" || t.flags == "I" { + k = vSym + } for _, w := range t.words { - v.arr = append(v.arr, rval{k: vStr, s: w}) + v.arr = append(v.arr, rval{k: k, s: w}) } return v, nil case tNum: @@ -1565,6 +1623,10 @@ func (p *parser) primary() (rval, error) { s, err := rubyNum(false, t.text) return rval{k: vNum, s: s}, err case tIdent: + if v, ok := p.locals[t.text]; ok && isLocal(t) { + p.take() + return v, nil + } switch t.text { case "true": p.take() @@ -1606,16 +1668,20 @@ func (p *parser) primary() (rval, error) { p.take() path += "::" + p.take().text } - if c, ok := p.consts[p.scope+"::"+path]; ok && p.scope != "" && !strings.Contains(path, "::") { - return c, nil - } - if c, ok := p.consts[path]; ok { - if p.scope != "" && !strings.Contains(path, "::") { + c, ok := p.consts[p.scope+"::"+path] + if !ok || p.scope == "" || strings.Contains(path, "::") { + if c, ok = p.consts[path]; ok && p.scope != "" && !strings.Contains(path, "::") { return rval{}, fmt.Errorf("constant %s may resolve to %s::%s", path, p.scope, path) } - return c, nil } - if p.defined != nil && !p.defined[path] { + switch { + case ok && c.k == vUndet: + return rval{}, fmt.Errorf("constant %s keeps the value of whichever input defined it first", path) + case ok: + return c, nil + case p.defined != nil && !p.defined[path] && p.w != nil && p.crefConst(path) != "": + return rval{k: vConst, s: p.crefConst(path)}, nil + case p.defined != nil && !p.defined[path]: return rval{}, fmt.Errorf("uninitialized constant %s", path) } return rval{k: vConst, s: path}, nil diff --git a/internal/gentypes/testdata/env/external_modules/patroni/LICENSE b/internal/gentypes/testdata/env/external_modules/patroni/LICENSE new file mode 100644 index 0000000..c32c2c9 --- /dev/null +++ b/internal/gentypes/testdata/env/external_modules/patroni/LICENSE @@ -0,0 +1,14 @@ +Copyright (c) 2018-2020 Daniel Henninger +Copyright (C) 2020 Garrett Honeycutt + +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/patroni/lib/puppet/provider/patroni_dcs_config/patronictl.rb b/internal/gentypes/testdata/env/external_modules/patroni/lib/puppet/provider/patroni_dcs_config/patronictl.rb new file mode 100644 index 0000000..3ff5123 --- /dev/null +++ b/internal/gentypes/testdata/env/external_modules/patroni/lib/puppet/provider/patroni_dcs_config/patronictl.rb @@ -0,0 +1,62 @@ +require File.expand_path(File.join(File.dirname(__FILE__), '..', 'patronictl')) + +Puppet::Type.type(:patroni_dcs_config).provide(:patronictl, parent: Puppet::Provider::Patronictl) do + desc 'Provider for patroni_dcs_config using patronictl' + + mk_resource_methods + + defaultfor kernel: ['Linux'] + + def self.instances + configs = [] + begin + output = patronictl(['show-config']) + rescue Exception => e # rubocop:disable RescueException + Puppet.err('Failed to fetch patronictl configurations') + puts e.backtrace + end + Puppet.debug("show-config output: #{output}") + data = YAML.safe_load(output) + flatten_hash(data).each_pair do |key, value| + config = {} + config[:name] = key + config[:value] = value + configs << new(config) + end + configs + end + + def self.prefetch(resources) + configs = instances + resources.keys.each do |name| + if provider = configs.find { |c| c.name == name } # rubocop:disable AssignmentInCondition + resources[name].provider = provider + end + end + end + + def initialize(value = {}) + super(value) + @property_flush = {} + end + + type_properties.each do |prop| + define_method "#{prop}=".to_sym do |value| + @property_flush[prop] = value + end + end + + def edit_config(value) + patronictl(['edit-config', '--force', '--quiet', '-s', value]) + rescue Exception => e # rubocop:disable RescueException + raise Puppet::Error, "patronictl edit-config for #{resource[:name]} failed\nError message: #{e.message}" + end + + def create + edit_config("#{resource[:name]}=#{resource[:value]}") + end + + def flush + edit_config("#{resource[:name]}=#{@property_flush[:value]}") + end +end diff --git a/internal/gentypes/testdata/env/external_modules/patroni/lib/puppet/provider/patronictl.rb b/internal/gentypes/testdata/env/external_modules/patroni/lib/puppet/provider/patronictl.rb new file mode 100644 index 0000000..cfdea1b --- /dev/null +++ b/internal/gentypes/testdata/env/external_modules/patroni/lib/puppet/provider/patronictl.rb @@ -0,0 +1,40 @@ +# Parent class for patronictl providers +class Puppet::Provider::Patronictl < Puppet::Provider + initvars + + class << self + attr_accessor :path + attr_accessor :config + end + + def self.patronictl(args, options = {}) + cmd = [@path] + ['-c', @config] + args + default_options = { combine: true, override_locale: false, custom_environment: { 'LC_ALL' => 'en_US.utf8' } } + ret = execute(cmd, default_options.merge(options)) + ret + end + + def patronictl(*args) + self.class.patronictl(*args) + end + + def self.type_properties + resource_type.validproperties.reject { |p| p.to_sym == :ensure } + end + + def type_properties + self.class.type_properties + end + + def self.flatten_hash(hash) + hash.each_with_object({}) do |(k, v), h| + if v.is_a? Hash + flatten_hash(v).map do |h_k, h_v| + h["#{k}.#{h_k}"] = h_v + end + else + h[k] = v + end + end + end +end diff --git a/internal/gentypes/testdata/env/external_modules/patroni/lib/puppet/type/patroni_dcs_config.rb b/internal/gentypes/testdata/env/external_modules/patroni/lib/puppet/type/patroni_dcs_config.rb new file mode 100644 index 0000000..50c21ec --- /dev/null +++ b/internal/gentypes/testdata/env/external_modules/patroni/lib/puppet/type/patroni_dcs_config.rb @@ -0,0 +1,21 @@ +Puppet::Type.newtype(:patroni_dcs_config) do + desc <<-DESC +@summary Manages Patroni DCS configuration options +@example Set PostgreSQL max connections + patroni_dcs_config { 'postgresql.params.max_connections': + value => '200', + } +DESC + + newparam(:name, namevar: true) do + desc 'The DCS configuration option name' + end + + newproperty(:value) do + desc 'The value to assign the DCS configuration' + end + + autorequire(:service) do + ['patroni'] + end +end diff --git a/internal/gentypes/testdata/env/external_modules/yumrepo_core/lib/puppet/provider/yumrepo/inifile.rb b/internal/gentypes/testdata/env/external_modules/yumrepo_core/lib/puppet/provider/yumrepo/inifile.rb index e293313..026e562 100644 --- a/internal/gentypes/testdata/env/external_modules/yumrepo_core/lib/puppet/provider/yumrepo/inifile.rb +++ b/internal/gentypes/testdata/env/external_modules/yumrepo_core/lib/puppet/provider/yumrepo/inifile.rb @@ -1,2 +1,408 @@ -Puppet::Type.type(:yumrepo).provide(:inifile) do +require 'puppet/util/inifile' + +module Puppet::Provider::Yumrepo # rubocop:disable Style/ClassAndModuleChildren + module IniConfig + class Section < Puppet::Util::IniConfig::Section; end + + # Examines a file on disk and identifies whether a section exists. + class PhysicalFile < Puppet::Util::IniConfig::PhysicalFile + def store + unlinked = false + if @destroy_empty && (sections.empty? || sections.all?(&:destroy?)) + ::File.unlink(@file) + unlinked = true + elsif sections.any?(&:dirty?) + text = self.format + @filetype.write(text) + end + sections.each(&:mark_clean) + unlinked + end + + private + + def section_exists?(name) + section = @file_collection.get_section(name) if @file_collection + if get_section(name) + true + elsif section && !section.destroy? + true + else + false + end + end + end + + # Creates a collection of new files on disk. + class FileCollection < Puppet::Util::IniConfig::FileCollection + def store + @files.delete_if do |_, file| + file.store + end + end + + private + + # Create a new physical file and set required attributes on that file. + def new_physical_file(file) + @files[file] = PhysicalFile.new(file, destroy_empty: true) + @files[file].file_collection = self + @files[file] + end + end + File = FileCollection + end +end + +Puppet::Type.type(:yumrepo).provide(:inifile) do + desc <<-EOD + Manage yum repo configurations by parsing yum INI configuration files. + + ### Fetching instances + + When fetching repo instances, directory entries in '/etc/yum/repos.d', + '/etc/yum.repos.d', and the directory optionally specified by the reposdir + key in '/etc/yum.conf' will be checked. If a given directory does not exist it + will be ignored. In addition, all sections in '/etc/yum.conf' aside from + 'main' will be created as sections. + + ### Storing instances + + When creating a new repository, a new section will be added in the first + yum repo directory that exists. The custom directory specified by the + '/etc/yum.conf' reposdir property is checked first, followed by + '/etc/yum/repos.d', and then '/etc/yum.repos.d'. If none of these exist, the + section will be created in '/etc/yum.conf'. + EOD + + PROPERTIES = Puppet::Type.type(:yumrepo).validproperties + + # Retrieve all providers based on existing yum repositories + # + # @api public + # @return [Array] providers generated from existing yum + # repository definitions. + def self.instances + instances = [] + + virtual_inifile.each_section do |section| + # Ignore the 'main' section in yum.conf since it's not a repository. + next if section.name == 'main' + + attributes_hash = { name: section.name, target: section.file, ensure: :present, provider: :yumrepo } + + section.entries.each do |key, value| + key = key.to_sym + if valid_property?(key) + attributes_hash[key] = value + elsif key == :name + attributes_hash[:descr] = value + end + end + instances << new(attributes_hash) + end + + instances + end + + # Match catalog type instances to provider instances. + # + # @api public + # @param resources [Array] Resources to prefetch. + # @return [void] + def self.prefetch(resources) + repos = instances + resources.each_key do |name| + provider = repos.find { |repo| repo.name == name } + if provider + resources[name].provider = provider + end + end + end + + # Return a list of existing directories that could contain repo files. + # + # @api private + # @param conf [String] Configuration file to look for directories in. + # @param dirs [Array] Default locations for yum repos. + # @return [Array] All present directories that may contain yum repo configs. + def self.reposdir(conf = '/etc/yum.conf', dirs = ['/etc/yum.repos.d', '/etc/yum/repos.d']) + reposdir = find_conf_value('reposdir', conf) + # Use directories in reposdir if they are set instead of default + if reposdir + # Follow the code from the yum/config.py + reposdir.tr!("\n", ' ') + reposdir.tr!(',', ' ') + dirs = reposdir.split + end + dirs.select! { |dir| Puppet::FileSystem.exist?(dir) } + if dirs.empty? + Puppet.debug('No yum directories were found on the local filesystem') + end + + dirs + end + + # Used for testing only + # @api private + def self.clear + @virtual = nil + end + + # Helper method to look up specific values in ini style files. + # + # @api private + # @param value [String] Value to look for in the configuration file. + # @param conf [String] Configuration file to check for value. + # @return [String] The value of a looked up key from the configuration file. + def self.find_conf_value(value, conf = '/etc/yum.conf') + return unless Puppet::FileSystem.exist?(conf) + + file = Puppet::Provider::Yumrepo::IniConfig::PhysicalFile.new(conf) + file.read + main = file.get_section('main') + main ? main[value] : nil + end + + # Enumerate all files that may contain yum repository configs. + # '/etc/yum.conf' is always included. + # + # @api private + # @return [Array + def self.repofiles + files = ['/etc/yum.conf'] + reposdir.each do |dir| + Dir.glob("#{dir}/*.repo").each do |file| + files << file + end + end + + files + end + + # Build a virtual inifile by reading in numerous .repo files into a single + # virtual file to ease manipulation. + # @api private + # @return [Puppet::Provider::Yumrepo::IniConfig::File] The virtual inifile representing + # multiple real files. + def self.virtual_inifile + unless @virtual + @virtual = Puppet::Provider::Yumrepo::IniConfig::File.new + repofiles.each do |file| + @virtual.read(file) if Puppet::FileSystem.file?(file) + end + end + @virtual + end + + # Is the given key a valid type property? + # + # @api private + # @param key [String] The property to look up. + # @return [Boolean] Returns true if the property is defined in the type. + def self.valid_property?(key) + PROPERTIES.include?(key) + end + + # Return an existing INI section or create a new section in the default location + # + # The default location is determined based on what yum repo directories + # and files are present. If /etc/yum.conf has a value for 'reposdir' then that + # is preferred. If no such INI property is found then the first default yum + # repo directory that is present is used. If no default directories exist then + # /etc/yum.conf is used. + # + # @param name [String] Section name to lookup in the virtual inifile. + # @return [Puppet::Provider::Yumrepo::IniConfig::Section] The IniConfig section + def self.section(name, target) + path = repo_path(name, target) + result = nil + old_section = nil + virtual_inifile.each_section do |section| + if section.name.eql?(name) + if target.nil? || target.eql?(:absent) || section.file.eql?(path) + result = section + else + old_section = section + section.destroy = true + end + end + end + # Create a new section if not found. + unless result + result = virtual_inifile.add_section(name, path) + # Copy section from old target if found. + old_section&.entries&.each { |entry| result.add_line(entry) } + end + result + end + + # Save all yum repository files and force the mode to 0644 + # @api private + # @return [void] + def self.store(resource) + inifile = virtual_inifile + inifile.store + + target_mode = 0o644 + inifile.each_file do |file| + next unless Puppet::FileSystem.exist?(file) + current_mode = Puppet::FileSystem.stat(file).mode & 0o777 + next if current_mode == target_mode + resource.info _('changing mode of %{file} from %{current_mode} to %{target_mode}') % + { file: file, current_mode: '%03o' % current_mode, target_mode: '%03o' % target_mode } + Puppet::FileSystem.chmod(target_mode, file) + end + end + + def self.repo_path(name, target) + dirs = reposdir + path = if dirs.empty? + # If no repo directories are present, default to using yum.conf. + unless target.nil? || target.eql?(:absent) + Puppet.debug("Using /etc/yum.conf instead of target #{target}") + end + '/etc/yum.conf' + # The ordering of reposdir is [defaults, custom], and we want to use + # the custom directory if present.else + elsif target.nil? || target.eql?(:absent) + File.join(dirs.last, "#{name}.repo") + else + parent = Puppet::FileSystem.dir_string(target) + basename = Puppet::FileSystem.basename_string(target) + suffix = target.end_with?('.repo') ? '' : '.repo' + if parent == basename + File.join(dirs.last, "#{target}#{suffix}") + elsif dirs.include?(parent) + "#{target}#{suffix}" + else + Puppet.debug("Parent directory of #{target} not a valid yum directory.") + File.join(dirs.last, "#{basename}#{suffix}") + end + end + path + end + + # Create a new section for the given repository and set all the specified + # properties in the section. + # + # @api public + # @return [void] + def create + @property_hash[:ensure] = :present + self.target = self.class.repo_path(name, @resource[:target]) unless @resource[:target].eql?(:absent) + + # Check to see if the file that would be created in the + # default location for the yumrepo already exists on disk. + # If it does, read it in to the virtual inifile + path = self.class.repo_path(name, target) + self.class.virtual_inifile.read(path) if Puppet::FileSystem.file?(path) + + # We fetch a list of properties from the type, then iterate + # over them, avoiding ensure. We're relying on .should to + # check if the property has been set and should be modified, + # and if so we set it in the virtual inifile. + PROPERTIES.each do |property| + next if property == :ensure + + value = @resource.should(property) + send("#{property}=", value) if value + end + end + + # Does the given repository already exist? + # + # @api public + # @return [Boolean] + def exists? + @property_hash[:ensure] == :present and (@resource[:target].eql?(:absent) or @property_hash[:target] == self.class.repo_path(name, @resource[:target])) + end + + # Mark the given repository section for destruction. + # + # The actual removal of the section will be handled by {#flush} after the + # resource has been fully evaluated. + # + # @api public + # @return [void] + def destroy + # Flag file for deletion on flush. + current_section.destroy = true + + @property_hash.clear + end + + # Finalize the application of the given resource. + # + # @api public + # @return [void] + def flush + self.class.store(self) + end + + # Generate setters and getters for our INI properties. + PROPERTIES.each do |property| + # The ensure property uses #create, #exists, and #destroy we can't generate + # meaningful setters and getters for this + next if property == :ensure + + define_method(property) do + get_property(property) + end + + define_method("#{property}=") do |value| + set_property(property, value) + end + end + + # Map the yumrepo 'descr' type property to the 'name' INI property. + def descr + unless @property_hash.key?(:descr) + @property_hash[:descr] = current_section['name'] + end + value = @property_hash[:descr] + value.nil? ? :absent : value + end + + def descr=(value) + value = ((value == :absent) ? nil : value) + current_section['name'] = value + @property_hash[:descr] = value + end + + def target + unless @property_hash.key?(:target) + @property_hash[:target] = self.class.repo_path(name, nil) + end + value = @property_hash[:target] + value.nil? ? :absent : value + end + + def target=(value) + @property_hash[:target] = value + end + + private + + def get_property(property) + unless @property_hash.key?(property) + @property_hash[property] = current_section[property.to_s] + end + value = @property_hash[property] + value.nil? ? :absent : value + end + + def set_property(property, value) + value = ((value == :absent) ? nil : value) + current_section[property.to_s] = value + @property_hash[property] = value + end + + def section(name) + self.class.section(name, target) + end + + def current_section + self.class.section(name, target) + end end diff --git a/internal/gentypes/testdata/env/external_modules/zfs_core/LICENSE b/internal/gentypes/testdata/env/external_modules/zfs_core/LICENSE new file mode 100644 index 0000000..261eeb9 --- /dev/null +++ b/internal/gentypes/testdata/env/external_modules/zfs_core/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/zfs_core/lib/puppet/provider/zfs/zfs.rb b/internal/gentypes/testdata/env/external_modules/zfs_core/lib/puppet/provider/zfs/zfs.rb new file mode 100644 index 0000000..a9b0153 --- /dev/null +++ b/internal/gentypes/testdata/env/external_modules/zfs_core/lib/puppet/provider/zfs/zfs.rb @@ -0,0 +1,102 @@ +Puppet::Type.type(:zfs).provide(:zfs) do + desc 'Provider for zfs.' + + commands zfs: 'zfs' + + def self.instances + zfs(:list, '-H').split("\n").map do |line| + name, _used, _avail, _refer, _mountpoint = line.split(%r{\s+}) + new(name: name, ensure: :present) + end + end + + def add_properties + properties = [] + Puppet::Type.type(:zfs).validproperties.each do |property| + next if property == :ensure + if (value = @resource[property]) && value != '' + if property == :volsize + properties << '-V' << value.to_s + else + properties << '-o' << "#{property}=#{value}" + end + end + end + properties + end + + def create + zfs(*([:create] + add_properties + [@resource[:name]])) + end + + def destroy + zfs(:destroy, @resource[:name]) + end + + def exists? + zfs(:list, @resource[:name]) + true + rescue Puppet::ExecutionFailure + false + end + + # On FreeBSD zoned is called jailed + def container_property + case Facter.value('os.name') + when 'FreeBSD' + :jailed + else + :zoned + end + end + + PARAMETER_UNSET_OR_NOT_AVAILABLE = '-'.freeze unless defined? PARAMETER_UNSET_OR_NOT_AVAILABLE + + # https://docs.oracle.com/cd/E19963-01/html/821-1448/gbscy.html + # shareiscsi (added in build 120) was removed from S11 build 136 + # aclmode was removed from S11 in build 139 but it may have been added back + # acltype is for ZFS on Linux, and allows disabling or enabling POSIX ACLs + # http://webcache.googleusercontent.com/search?q=cache:-p74K0DVsdwJ:developers.slashdot.org/story/11/11/09/2343258/solaris-11-released+&cd=13 + # defaultuserquota is not supported in zfs filesystem versions older than 6 and will error on Solaris 10 machines + # relatime is only supported on ZFS on Linux + [:aclmode, :acltype, :shareiscsi, :overlay, :defaultuserquota, :relatime].each do |field| + # The zfs commands use the property value '-' to indicate that the + # property is not set. We make use of this value to indicate that the + # property is not set since it is not available. Conversely, if these + # properties are attempted to be unset, and resulted in an error, our + # best bet is to catch the exception and continue. + define_method(field) do + zfs(:get, '-H', '-o', 'value', field, @resource[:name]).strip + rescue + PARAMETER_UNSET_OR_NOT_AVAILABLE + end + define_method(field.to_s + '=') do |should| + zfs(:set, "#{field}=#{should}", @resource[:name]) + rescue + PARAMETER_UNSET_OR_NOT_AVAILABLE + end + end + + [:aclinherit, :atime, :canmount, :checksum, + :compression, :copies, :dedup, :devices, :exec, :logbias, + :mountpoint, :nbmand, :primarycache, :quota, :readonly, + :recordsize, :refquota, :refreservation, :reservation, + :secondarycache, :setuid, :sharenfs, :sharesmb, + :snapdir, :sync, :version, :volsize, :vscan, :xattr].each do |field| + define_method(field) do + zfs(:get, '-H', '-o', 'value', field, @resource[:name]).strip + end + + define_method(field.to_s + '=') do |should| + zfs(:set, "#{field}=#{should}", @resource[:name]) + end + end + + define_method(:zoned) do + zfs(:get, '-H', '-o', 'value', container_property, @resource[:name]).strip + end + + define_method('zoned=') do |should| + zfs(:set, "#{container_property}=#{should}", @resource[:name]) + end +end diff --git a/internal/gentypes/testdata/env/external_modules/zfs_core/lib/puppet/type/zfs.rb b/internal/gentypes/testdata/env/external_modules/zfs_core/lib/puppet/type/zfs.rb new file mode 100644 index 0000000..3642433 --- /dev/null +++ b/internal/gentypes/testdata/env/external_modules/zfs_core/lib/puppet/type/zfs.rb @@ -0,0 +1,192 @@ +# Manage zfs. Create destroy and set properties on zfs instances. +module Puppet + Type.newtype(:zfs) do + desc <<-DESC + @summary Manage zfs. Create destroy and set properties on zfs instances. + + **Autorequires:** If Puppet is managing the zpool at the root of this zfs + instance, the zfs resource will autorequire it. If Puppet is managing any + parent zfs instances, the zfs resource will autorequire them. + + @example Using zfs. + zfs { 'tstpool': + ensure => present, + } + DESC + + ensurable + + newparam(:name) do + desc 'The full name for this filesystem (including the zpool).' + end + + newproperty(:aclinherit) do + desc 'The aclinherit property. Valid values are `discard`, `noallow`, `restricted`, `passthrough`, `passthrough-x`.' + end + + newproperty(:aclmode) do + desc 'The aclmode property. Valid values are `discard`, `groupmask`, `passthrough`.' + end + + newproperty(:acltype) do + desc "The acltype propery. Valid values are 'noacl' and 'posixacl'. Only supported on Linux." + end + + newproperty(:atime) do + desc 'The atime property. Valid values are `on`, `off`.' + end + + newproperty(:canmount) do + desc 'The canmount property. Valid values are `on`, `off`, `noauto`.' + end + + newproperty(:checksum) do + desc 'The checksum property. Valid values are `on`, `off`, `fletcher2`, `fletcher4`, `sha256`.' + end + + newproperty(:compression) do + desc 'The compression property. Valid values are `on`, `off`, `lzjb`, `gzip`, `gzip-[1-9]`, `zle`.' + end + + newproperty(:copies) do + desc 'The copies property. Valid values are `1`, `2`, `3`.' + end + + newproperty(:dedup) do + desc 'The dedup property. Valid values are `on`, `off`.' + end + + newproperty(:defaultuserquota) do + desc 'The defaultuserquota property. Valid values are ``, `none`.' + + # Solaris 10 uses zfs filesystem version 5 which doesn't support defaultuserquota + validate do |_value| + raise Puppet::Error _('This property is only supported on zfs filestystem version >= 6') if Facter.value(:kernel) == 'SunOS' && Puppet::Util::Package.versioncmp(Facter.value(:kernelrelease), +'11') < 0 + end + end + + newproperty(:devices) do + desc 'The devices property. Valid values are `on`, `off`.' + end + + newproperty(:exec) do + desc 'The exec property. Valid values are `on`, `off`.' + end + + newproperty(:logbias) do + desc 'The logbias property. Valid values are `latency`, `throughput`.' + end + + newproperty(:mountpoint) do + desc 'The mountpoint property. Valid values are ``, `legacy`, `none`.' + end + + newproperty(:nbmand) do + desc 'The nbmand property. Valid values are `on`, `off`.' + end + + newproperty(:overlay) do + desc 'The overlay property. Valid values are `on`, `off`.' + + validate do |_value| + raise Puppet::Error _('This property is only supported on Linux') unless Facter.value(:kernel) == 'Linux' + end + end + + newproperty(:primarycache) do + desc 'The primarycache property. Valid values are `all`, `none`, `metadata`.' + end + + newproperty(:quota) do + desc 'The quota property. Valid values are ``, `none`.' + end + + newproperty(:readonly) do + desc 'The readonly property. Valid values are `on`, `off`.' + end + + newproperty(:recordsize) do + desc 'The recordsize property. Valid values are powers of two between 512 and 128k.' + end + + newproperty(:refquota) do + desc 'The refquota property. Valid values are ``, `none`.' + end + + newproperty(:refreservation) do + desc 'The refreservation property. Valid values are ``, `none`.' + end + + newproperty(:relatime) do + desc 'The relatime property. Valid values are `on`, `off`. Only supported on Linux' + + validate do |_value| + raise Puppet::Error _('This property is only supported on Linux') unless Facter.value(:kernel) == 'Linux' + end + end + + newproperty(:reservation) do + desc 'The reservation property. Valid values are ``, `none`.' + end + + newproperty(:secondarycache) do + desc 'The secondarycache property. Valid values are `all`, `none`, `metadata`.' + end + + newproperty(:setuid) do + desc 'The setuid property. Valid values are `on`, `off`.' + end + + newproperty(:shareiscsi) do + desc 'The shareiscsi property. Valid values are `on`, `off`, `type=`.' + end + + newproperty(:sharenfs) do + desc 'The sharenfs property. Valid values are `on`, `off`, share(1M) options' + end + + newproperty(:sharesmb) do + desc 'The sharesmb property. Valid values are `on`, `off`, sharemgr(1M) options' + end + + newproperty(:snapdir) do + desc 'The snapdir property. Valid values are `hidden`, `visible`.' + end + + newproperty(:sync) do + desc 'The sync property. Valid values are `standard`, `always`, `disabled`.' + end + + newproperty(:version) do + desc 'The version property. Valid values are `1`, `2`, `3`, `4`, `current`.' + end + + newproperty(:volsize) do + desc 'The volsize property. Valid values are ``' + end + + newproperty(:vscan) do + desc 'The vscan property. Valid values are `on`, `off`.' + end + + newproperty(:xattr) do + desc 'The xattr property. Valid values are `on`, `off`.' + end + + newproperty(:zoned) do + desc 'The zoned property. Valid values are `on`, `off`.' + end + + autorequire(:zpool) do + # strip the zpool off the zfs name and autorequire it + [@parameters[:name].value.split('/')[0]] + end + + autorequire(:zfs) do + # slice and dice, we want all the zfs before this one + names = @parameters[:name].value.split('/') + names.slice(1..-2).reduce([]) { |a, v| a << "#{a.last}/#{v}" }.map { |fs| names[0] + fs } + end + end +end diff --git a/internal/gentypes/testdata/golden/patroni_dcs_config.pp b/internal/gentypes/testdata/golden/patroni_dcs_config.pp new file mode 100644 index 0000000..b559239 --- /dev/null +++ b/internal/gentypes/testdata/golden/patroni_dcs_config.pp @@ -0,0 +1,31 @@ +# This file was automatically generated on 2026-11-08 23:47:59 +1100. +# Use the 'puppet generate types' command to regenerate this file. + +# @summary Manages Patroni DCS configuration options +# @example Set PostgreSQL max connections +# patroni_dcs_config { 'postgresql.params.max_connections': +# value => '200', +# } +Puppet::Resource::ResourceType3.new( + 'patroni_dcs_config', + [ + # The value to assign the DCS configuration + Puppet::Resource::Param(Any, 'value') + ], + [ + # The DCS configuration option name + Puppet::Resource::Param(Any, 'name', true), + + # The specific backend to use for this `patroni_dcs_config` + # resource. You will seldom need to specify this --- OpenVox will usually + # discover the appropriate provider for your platform.Available providers are: + # + # patronictl + # : + Puppet::Resource::Param(Any, 'provider') + ], + { + /(?m-ix:(.*))/ => ['name'] + }, + true, + false) diff --git a/internal/gentypes/testdata/golden/zfs.pp b/internal/gentypes/testdata/golden/zfs.pp new file mode 100644 index 0000000..824a4c3 --- /dev/null +++ b/internal/gentypes/testdata/golden/zfs.pp @@ -0,0 +1,146 @@ +# This file was automatically generated on 2026-11-08 23:47:59 +1100. +# Use the 'puppet generate types' command to regenerate this file. + +# @summary Manage zfs. Create destroy and set properties on zfs instances. +# +# **Autorequires:** If Puppet is managing the zpool at the root of this zfs +# instance, the zfs resource will autorequire it. If Puppet is managing any +# parent zfs instances, the zfs resource will autorequire them. +# +# @example Using zfs. +# zfs { 'tstpool': +# ensure => present, +# } +Puppet::Resource::ResourceType3.new( + 'zfs', + [ + # The basic property that the resource should be in. + # + # Valid values are `present`, `absent`. + Puppet::Resource::Param(Enum['present', 'absent'], 'ensure'), + + # The aclinherit property. Valid values are `discard`, `noallow`, `restricted`, `passthrough`, `passthrough-x`. + Puppet::Resource::Param(Any, 'aclinherit'), + + # The aclmode property. Valid values are `discard`, `groupmask`, `passthrough`. + Puppet::Resource::Param(Any, 'aclmode'), + + # The acltype propery. Valid values are 'noacl' and 'posixacl'. Only supported on Linux. + Puppet::Resource::Param(Any, 'acltype'), + + # The atime property. Valid values are `on`, `off`. + Puppet::Resource::Param(Any, 'atime'), + + # The canmount property. Valid values are `on`, `off`, `noauto`. + Puppet::Resource::Param(Any, 'canmount'), + + # The checksum property. Valid values are `on`, `off`, `fletcher2`, `fletcher4`, `sha256`. + Puppet::Resource::Param(Any, 'checksum'), + + # The compression property. Valid values are `on`, `off`, `lzjb`, `gzip`, `gzip-[1-9]`, `zle`. + Puppet::Resource::Param(Any, 'compression'), + + # The copies property. Valid values are `1`, `2`, `3`. + Puppet::Resource::Param(Any, 'copies'), + + # The dedup property. Valid values are `on`, `off`. + Puppet::Resource::Param(Any, 'dedup'), + + # The defaultuserquota property. Valid values are ``, `none`. + Puppet::Resource::Param(Any, 'defaultuserquota'), + + # The devices property. Valid values are `on`, `off`. + Puppet::Resource::Param(Any, 'devices'), + + # The exec property. Valid values are `on`, `off`. + Puppet::Resource::Param(Any, 'exec'), + + # The logbias property. Valid values are `latency`, `throughput`. + Puppet::Resource::Param(Any, 'logbias'), + + # The mountpoint property. Valid values are ``, `legacy`, `none`. + Puppet::Resource::Param(Any, 'mountpoint'), + + # The nbmand property. Valid values are `on`, `off`. + Puppet::Resource::Param(Any, 'nbmand'), + + # The overlay property. Valid values are `on`, `off`. + Puppet::Resource::Param(Any, 'overlay'), + + # The primarycache property. Valid values are `all`, `none`, `metadata`. + Puppet::Resource::Param(Any, 'primarycache'), + + # The quota property. Valid values are ``, `none`. + Puppet::Resource::Param(Any, 'quota'), + + # The readonly property. Valid values are `on`, `off`. + Puppet::Resource::Param(Any, 'readonly'), + + # The recordsize property. Valid values are powers of two between 512 and 128k. + Puppet::Resource::Param(Any, 'recordsize'), + + # The refquota property. Valid values are ``, `none`. + Puppet::Resource::Param(Any, 'refquota'), + + # The refreservation property. Valid values are ``, `none`. + Puppet::Resource::Param(Any, 'refreservation'), + + # The relatime property. Valid values are `on`, `off`. Only supported on Linux + Puppet::Resource::Param(Any, 'relatime'), + + # The reservation property. Valid values are ``, `none`. + Puppet::Resource::Param(Any, 'reservation'), + + # The secondarycache property. Valid values are `all`, `none`, `metadata`. + Puppet::Resource::Param(Any, 'secondarycache'), + + # The setuid property. Valid values are `on`, `off`. + Puppet::Resource::Param(Any, 'setuid'), + + # The shareiscsi property. Valid values are `on`, `off`, `type=`. + Puppet::Resource::Param(Any, 'shareiscsi'), + + # The sharenfs property. Valid values are `on`, `off`, share(1M) options + Puppet::Resource::Param(Any, 'sharenfs'), + + # The sharesmb property. Valid values are `on`, `off`, sharemgr(1M) options + Puppet::Resource::Param(Any, 'sharesmb'), + + # The snapdir property. Valid values are `hidden`, `visible`. + Puppet::Resource::Param(Any, 'snapdir'), + + # The sync property. Valid values are `standard`, `always`, `disabled`. + Puppet::Resource::Param(Any, 'sync'), + + # The version property. Valid values are `1`, `2`, `3`, `4`, `current`. + Puppet::Resource::Param(Any, 'version'), + + # The volsize property. Valid values are `` + Puppet::Resource::Param(Any, 'volsize'), + + # The vscan property. Valid values are `on`, `off`. + Puppet::Resource::Param(Any, 'vscan'), + + # The xattr property. Valid values are `on`, `off`. + Puppet::Resource::Param(Any, 'xattr'), + + # The zoned property. Valid values are `on`, `off`. + Puppet::Resource::Param(Any, 'zoned') + ], + [ + # The full name for this filesystem (including the zpool). + Puppet::Resource::Param(Any, 'name'), + + # The specific backend to use for this `zfs` + # resource. You will seldom need to specify this --- OpenVox will usually + # discover the appropriate provider for your platform.Available providers are: + # + # zfs + # : + Puppet::Resource::Param(Any, 'provider') + ], + { + /(?m-ix:(.*))/ => ['name'] + }, + true, + false)