Evaluate mixin included hooks and interpolated regexes
Run a module's self.included on the including provider: extend adds singleton methods, a super-wrapping initvars resets defaults and commands where called, and inlined define loops add property methods. Compose interpolated regex literals and accept them only when an Onigmo subset check passes. Generates network_config and network_route.
This commit is contained in:
+649
-20
@@ -3,8 +3,12 @@ package gentypes
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"maps"
|
||||
"slices"
|
||||
"strconv"
|
||||
"strings"
|
||||
"unicode"
|
||||
"unicode/utf8"
|
||||
)
|
||||
|
||||
// Evaluator budgets: inlined singleton-method depth, and the tokens and bytes one world may spend.
|
||||
@@ -22,6 +26,7 @@ type sdef struct {
|
||||
cref []string
|
||||
mod, dir string
|
||||
file, src string
|
||||
param string
|
||||
}
|
||||
|
||||
var errNext = errors.New("next")
|
||||
@@ -49,21 +54,29 @@ func (p *parser) charge(n int) {
|
||||
|
||||
// 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 {
|
||||
sd := p.newSdef(off)
|
||||
if sd == nil {
|
||||
c.opaque(name)
|
||||
return nil
|
||||
}
|
||||
if c.sdefs == nil {
|
||||
c.sdefs = map[string]*sdef{}
|
||||
}
|
||||
c.sdefs[name] = sd
|
||||
return sd
|
||||
}
|
||||
|
||||
// newSdef starts the body of the method whose name is at p.i+off, or returns nil when the method takes parameters.
|
||||
func (p *parser) newSdef(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
|
||||
return &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}
|
||||
}
|
||||
|
||||
// opaque marks singleton methods w10k does not evaluate, such as accessors and command methods.
|
||||
@@ -114,13 +127,9 @@ func (p *parser) call(name string) (rval, error) {
|
||||
|
||||
// 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]
|
||||
q, err := p.sub(sd, name)
|
||||
if err != nil {
|
||||
return rval{}, err
|
||||
}
|
||||
last := rval{k: vNil}
|
||||
for {
|
||||
@@ -150,13 +159,54 @@ func (p *parser) inline(sd *sdef, name string) (rval, error) {
|
||||
}
|
||||
}
|
||||
|
||||
// eval evaluates an expression: literals, locals, constants, defined?, calls on self, allowlisted methods, String#+
|
||||
// and ==/!=. It stops before .each, which only a statement takes.
|
||||
// sub returns a parser at the start of method body sd, in the lexical scope of the file defining it.
|
||||
func (p *parser) sub(sd *sdef, name string) (*parser, error) {
|
||||
if p.calls >= maxCalls {
|
||||
return nil, fmt.Errorf("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]
|
||||
}
|
||||
return q, nil
|
||||
}
|
||||
|
||||
func truthy(v rval) bool { return v.k != vNil && v.k != vFalse }
|
||||
|
||||
// eval evaluates an expression: literals, locals, constants, defined?, calls on self, allowlisted methods, String#+,
|
||||
// ==/!=, ! and &&/||, whose right operand it always evaluates. 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.and()
|
||||
for err == nil && p.op("||") {
|
||||
p.take()
|
||||
p.skipNL()
|
||||
var w rval
|
||||
if w, err = p.and(); err == nil && !truthy(v) {
|
||||
v = w
|
||||
}
|
||||
}
|
||||
return v, err
|
||||
}
|
||||
|
||||
func (p *parser) and() (rval, error) {
|
||||
v, err := p.equality()
|
||||
for err == nil && p.op("&&") {
|
||||
p.take()
|
||||
p.skipNL()
|
||||
var w rval
|
||||
if w, err = p.equality(); err == nil && truthy(v) {
|
||||
v = w
|
||||
}
|
||||
}
|
||||
return v, err
|
||||
}
|
||||
|
||||
func (p *parser) equality() (rval, error) {
|
||||
v, err := p.sum()
|
||||
if err != nil || !p.op("==") && !p.op("!=") {
|
||||
return v, err
|
||||
@@ -218,6 +268,9 @@ func (p *parser) method(v rval, m string) (rval, error) {
|
||||
if m == "reject" && v.k == vArray {
|
||||
return p.reject(v)
|
||||
}
|
||||
if m == "respond_to?" || m == "is_a?" || m == "kind_of?" {
|
||||
return p.typeQuery(v, m)
|
||||
}
|
||||
if p.op("(") && !p.cur().space || p.op("{") {
|
||||
return v, fmt.Errorf("unsupported arguments or block for %s", m)
|
||||
}
|
||||
@@ -226,7 +279,7 @@ func (p *parser) method(v rval, m string) (rval, error) {
|
||||
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):
|
||||
case (m == "to_sym" || m == "intern") && (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)
|
||||
@@ -234,6 +287,59 @@ func (p *parser) method(v rval, m string) (rval, error) {
|
||||
return v, fmt.Errorf("unsupported %s#%s", v.kindName(), m)
|
||||
}
|
||||
|
||||
// responds are methods every String and Symbol has; respond_to? of any other name is not decided.
|
||||
var responds = set("to_s to_sym intern downcase upcase freeze")
|
||||
|
||||
// coreClasses are the classes is_a? decides, by the value kinds that are instances of each.
|
||||
var coreClasses = map[string][]vkind{
|
||||
"Symbol": {vSym}, "String": {vStr}, "Array": {vArray}, "Hash": {vHash}, "Regexp": {vRegex},
|
||||
"NilClass": {vNil}, "TrueClass": {vTrue}, "FalseClass": {vFalse},
|
||||
"Object": {vStr, vSym, vRegex, vNum, vTrue, vFalse, vNil, vArray, vHash, vConst, vBlock, vType},
|
||||
}
|
||||
|
||||
// typeQuery evaluates v.respond_to?(:name) for a String or Symbol, and v.is_a?(Class) for a core class.
|
||||
func (p *parser) typeQuery(v rval, m string) (rval, error) {
|
||||
if !p.op("(") || p.cur().space {
|
||||
return v, fmt.Errorf("unsupported %s without parentheses", m)
|
||||
}
|
||||
p.take()
|
||||
ok := false
|
||||
if m == "respond_to?" {
|
||||
a, err := p.eval()
|
||||
if err != nil {
|
||||
return v, err
|
||||
}
|
||||
if a.k != vSym && a.k != vStr || v.k != vStr && v.k != vSym || !responds[a.s] {
|
||||
return v, fmt.Errorf("respond_to? %s on a %s is not decided", a.s, v.kindName())
|
||||
}
|
||||
ok = true
|
||||
} else {
|
||||
name, err := p.constPath()
|
||||
if err != nil {
|
||||
return v, err
|
||||
}
|
||||
kinds, known := coreClasses[name]
|
||||
if !known || !p.coreConst(name) || v.k == vUndet {
|
||||
return v, fmt.Errorf("unsupported %s(%s)", m, name)
|
||||
}
|
||||
ok = slices.Contains(kinds, v.k)
|
||||
}
|
||||
if err := p.expect(")"); err != nil {
|
||||
return v, err
|
||||
}
|
||||
if ok {
|
||||
return rval{k: vTrue}, nil
|
||||
}
|
||||
return rval{k: vFalse}, nil
|
||||
}
|
||||
|
||||
// coreConst reports whether constant name resolves to Ruby's top-level constant from here.
|
||||
func (p *parser) coreConst(name string) bool {
|
||||
_, own := p.consts[name]
|
||||
_, scoped := p.consts[p.scope+"::"+name]
|
||||
return p.w != nil && p.lexical(name) == name && !own && !scoped
|
||||
}
|
||||
|
||||
// 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 {
|
||||
@@ -293,8 +399,9 @@ func (p *parser) block(elems []rval, body func(e rval, closeTok string) error) e
|
||||
}
|
||||
param := p.at(1).text
|
||||
start := p.i + 3
|
||||
saved := p.locals
|
||||
defer func() { p.locals = saved }()
|
||||
saved, savedParam := p.locals, p.bparam
|
||||
p.bparam = param
|
||||
defer func() { p.locals, p.bparam = saved, savedParam }()
|
||||
for _, e := range elems {
|
||||
p.locals = make(map[string]rval, len(saved)+1)
|
||||
for k, x := range saved {
|
||||
@@ -313,6 +420,22 @@ func (p *parser) block(elems []rval, body func(e rval, closeTok string) error) e
|
||||
func (p *parser) atom() (rval, error) {
|
||||
t := p.cur()
|
||||
switch {
|
||||
case t.kind == tOp && t.text == "!":
|
||||
p.take()
|
||||
v, err := p.postfix()
|
||||
if truthy(v) {
|
||||
return rval{k: vFalse}, err
|
||||
}
|
||||
return rval{k: vTrue}, err
|
||||
case t.kind == tConst && t.text == "Hash" && p.at(1).text == "." && p.at(2).text == "new" && p.coreConst("Hash"):
|
||||
p.i += 3
|
||||
if p.op("(") && !p.cur().space && p.at(1).text == ")" {
|
||||
p.i += 2
|
||||
}
|
||||
if p.op("{") || p.is(tIdent, "do") && !p.noDo {
|
||||
return rval{k: vHash}, p.skipBlock()
|
||||
}
|
||||
return rval{k: vHash}, nil
|
||||
case t.kind == tIdent && t.text == "defined?":
|
||||
return p.definedExpr()
|
||||
case isLocal(t) && (p.locals != nil || p.cls != nil):
|
||||
@@ -456,11 +579,25 @@ func (p *parser) eachAhead() bool {
|
||||
return false
|
||||
}
|
||||
|
||||
// loopStmt allows define_method and next, optionally under an if or unless modifier, in a define loop.
|
||||
// loopStmt allows define_method, next and reassigning the block parameter, optionally under an if or unless modifier,
|
||||
// in a define loop; the assigned value is evaluated even when the modifier skips it.
|
||||
func (p *parser) loopStmt(c *classCtx) (bool, error) {
|
||||
switch {
|
||||
case p.is(tIdent, "define_method"):
|
||||
return true, p.defineMethod(c)
|
||||
case isLocal(p.cur()) && p.assigns() && p.cur().text == p.bparam:
|
||||
name := p.take().text
|
||||
p.take()
|
||||
v, err := p.eval()
|
||||
if err == nil && (p.is(tIdent, "if") || p.is(tIdent, "unless")) {
|
||||
unless := p.take().text == "unless"
|
||||
var cond rval
|
||||
if cond, err = p.eval(); truthy(cond) == unless {
|
||||
return true, err
|
||||
}
|
||||
}
|
||||
p.locals[name] = v
|
||||
return true, err
|
||||
case p.is(tIdent, "next"):
|
||||
p.take()
|
||||
next := true
|
||||
@@ -510,3 +647,495 @@ func (p *parser) defineMethod(c *classCtx) error {
|
||||
c.methods[v.s], c.hidden[v.s] = true, c.priv
|
||||
return p.skipBlock()
|
||||
}
|
||||
|
||||
// includedHook records a module's def self.included(klass); including the module runs it on the including class.
|
||||
func (p *parser) includedHook(c *classCtx) error {
|
||||
if t := p.at(4); t.text != "(" || t.space || !isLocal(p.at(5)) || p.at(6).text != ")" {
|
||||
return fmt.Errorf("unsupported def self.included parameters")
|
||||
}
|
||||
sd := &sdef{toks: p.toks, start: p.i + 7, consts: p.consts, cref: slices.Clone(p.cref), mod: p.mod, dir: p.dir, file: p.file, src: p.src, param: p.at(5).text}
|
||||
err := p.skipStatement()
|
||||
sd.end = p.i - 1
|
||||
c.included = sd
|
||||
return err
|
||||
}
|
||||
|
||||
// runIncluded runs module mod's included hook on class c: klass.extend Module and klass.method calls without arguments.
|
||||
func (p *parser) runIncluded(c *classCtx, mod string) error {
|
||||
mc := p.w.classes[mod]
|
||||
if mc == nil || mc.included == nil {
|
||||
return nil
|
||||
}
|
||||
sd := mc.included
|
||||
q, err := p.sub(sd, "included")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
err = q.body("end", func() (bool, error) {
|
||||
if !q.is(tIdent, sd.param) || q.at(1).text != "." || q.at(2).kind != tIdent {
|
||||
return true, fmt.Errorf("unsupported %s", q.construct())
|
||||
}
|
||||
q.i += 2
|
||||
name := q.take().text
|
||||
if name == "extend" {
|
||||
return true, q.extend(c)
|
||||
}
|
||||
if t := q.cur(); t.kind != tNL && t.text != ";" && !q.is(tIdent, "end") {
|
||||
return true, fmt.Errorf("unsupported arguments to %s.%s", sd.param, name)
|
||||
}
|
||||
return true, q.callStmt(c, name)
|
||||
})
|
||||
if err == nil && q.i-1 != sd.end {
|
||||
err = fmt.Errorf("unsupported end")
|
||||
}
|
||||
if err != nil {
|
||||
return fmt.Errorf("%s.included: %w", mod, q.wrap(err))
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// extend adds the instance methods of one loaded module as singleton methods of c, behind c's own. A method that
|
||||
// shadows a provider DSL method must be a super wrapper, which then stands in for it; one shadowing a hook, doc or
|
||||
// dochook_ is an error.
|
||||
func (p *parser) extend(c *classCtx) error {
|
||||
path, err := p.constPath()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
r := p.lexical(path)
|
||||
mc := p.w.classes[r]
|
||||
switch {
|
||||
case r == "" || p.w.kind[r] != kMod || mc == nil:
|
||||
return fmt.Errorf("extend %s: no loaded file defines it as a module", path)
|
||||
case len(p.w.mods[r]) != 1:
|
||||
return fmt.Errorf("extend %s: more than one loaded file opens it", path)
|
||||
case len(mc.mixed) > 0:
|
||||
return fmt.Errorf("extend %s: it includes other modules", path)
|
||||
}
|
||||
if c.sdefs == nil {
|
||||
c.sdefs = map[string]*sdef{}
|
||||
}
|
||||
for _, n := range slices.Sorted(maps.Keys(mc.methods)) {
|
||||
sd := mc.idefs[n]
|
||||
switch {
|
||||
case mc.hidden[n]:
|
||||
return fmt.Errorf("extend %s: non-public method %s", path, n)
|
||||
case providerDSL[n]:
|
||||
if err := p.superWrapper(c, sd); err != nil {
|
||||
return fmt.Errorf("extend %s: %s shadows a provider method: %w", path, n, err)
|
||||
}
|
||||
case hooks[n] || n == "doc" || strings.HasPrefix(n, "dochook_"):
|
||||
return fmt.Errorf("extend %s: %s shadows a class method puppet calls", path, n)
|
||||
}
|
||||
if _, own := c.sdefs[n]; own {
|
||||
continue
|
||||
}
|
||||
c.sdefs[n], c.smethods[n], c.supers[n] = sd, true, providerDSL[n]
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// superWrapper checks that provider method body sd calls super first and then only sets ivars puppet never reads, so
|
||||
// calling it does what the method it shadows does.
|
||||
func (p *parser) superWrapper(c *classCtx, sd *sdef) error {
|
||||
if sd == nil || c.kind != kProv && c.kind != kParsed {
|
||||
return fmt.Errorf("not a super wrapper")
|
||||
}
|
||||
q, err := p.sub(sd, "super wrapper")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
q.skipNL()
|
||||
if !q.is(tIdent, "super") || q.at(1).kind != tNL && q.at(1).text != ";" {
|
||||
return fmt.Errorf("it does not start with super")
|
||||
}
|
||||
q.take()
|
||||
err = q.body("end", func() (bool, error) {
|
||||
t := q.cur()
|
||||
if t.kind != tIVar || strings.HasPrefix(t.text, "@@") || !q.assigns() || puppetReads(c.kind, t.text[1:]) {
|
||||
return true, fmt.Errorf("unsupported %s after super", q.construct())
|
||||
}
|
||||
q.i += 2
|
||||
_, err := q.eval()
|
||||
return true, err
|
||||
})
|
||||
if err == nil && q.i-1 != sd.end {
|
||||
err = fmt.Errorf("unsupported end")
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
// parsedIvars are the providerIvars only Puppet::Provider::ParsedFile and Puppet::Util::FileParsing read.
|
||||
var parsedIvars = set("backup_stats failed_prefetch_targets filetype line_separator raise_prefetch_errors record_order records record_types target target_objects trailing_separator")
|
||||
|
||||
func puppetReads(kind byte, ivar string) bool {
|
||||
return providerIvars[ivar] && (kind != kProv || !parsedIvars[ivar])
|
||||
}
|
||||
|
||||
// callStmt runs c.name with no arguments as a statement: a super wrapper or an unshadowed provider DSL method, or an
|
||||
// inlined singleton method body.
|
||||
func (p *parser) callStmt(c *classCtx, name string) error {
|
||||
sd, found, err := p.singleton(c, name)
|
||||
switch {
|
||||
case err != nil:
|
||||
return err
|
||||
case found && c.supers[name], !found && (c.kind == kProv || c.kind == kParsed) && providerDSL[name]:
|
||||
return c.dslNoArgs(name)
|
||||
case found && sd == nil:
|
||||
return fmt.Errorf("singleton method %s is not evaluable", name)
|
||||
case found:
|
||||
return p.inlineStmt(c, sd, name)
|
||||
}
|
||||
return fmt.Errorf("undefined method %s", name)
|
||||
}
|
||||
|
||||
// dslNoArgs applies a provider DSL call without arguments.
|
||||
func (c *classCtx) dslNoArgs(name string) error {
|
||||
switch name {
|
||||
case "initvars":
|
||||
c.inited, c.defaults, c.commands = true, nil, map[string]string{}
|
||||
case "mk_resource_methods":
|
||||
c.mkres = true
|
||||
default:
|
||||
return fmt.Errorf("%s takes arguments", name)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// inlineStmt runs singleton method body sd on c as class-level define loops and define_method calls, which define
|
||||
// public methods whatever visibility c's body has set.
|
||||
func (p *parser) inlineStmt(c *classCtx, sd *sdef, name string) error {
|
||||
q, err := p.sub(sd, name)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
saved := c.priv
|
||||
c.priv = false
|
||||
defer func() { c.priv = saved }()
|
||||
err = q.body("end", func() (bool, error) {
|
||||
if ok, err := q.evalStmt(c); ok {
|
||||
return true, err
|
||||
}
|
||||
return true, fmt.Errorf("unsupported %s", q.construct())
|
||||
})
|
||||
if err == nil && q.i-1 != sd.end {
|
||||
err = fmt.Errorf("unsupported end")
|
||||
}
|
||||
if err != nil {
|
||||
return fmt.Errorf("%s: %w", name, err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// regexInterp composes an interpolated regex literal as Ruby does, each value by its to_s, and compiles it only when
|
||||
// onigCheck proves Onigmo accepts the result.
|
||||
func (p *parser) regexInterp(t token) (rval, error) {
|
||||
if strings.Trim(t.flags, "mi") != "" {
|
||||
return rval{}, fmt.Errorf("unsupported interpolated regex flags %q", t.flags)
|
||||
}
|
||||
var parts []part
|
||||
var b strings.Builder
|
||||
flush := func() {
|
||||
if b.Len() > 0 {
|
||||
parts = append(parts, part{text: b.String()})
|
||||
b.Reset()
|
||||
}
|
||||
}
|
||||
s := t.text
|
||||
for i := 0; i < len(s); i++ {
|
||||
switch {
|
||||
case s[i] == '\\' && i+1 < len(s):
|
||||
b.WriteString(s[i : i+2])
|
||||
i++
|
||||
case s[i] == '#' && i+1 < len(s) && s[i+1] == '{':
|
||||
depth, j := 0, i+1
|
||||
for ; j < len(s); j++ {
|
||||
if s[j] == '{' {
|
||||
depth++
|
||||
} else if s[j] == '}' {
|
||||
if depth--; depth == 0 {
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
if j >= len(s) {
|
||||
return rval{}, fmt.Errorf("unterminated interpolation in regex")
|
||||
}
|
||||
flush()
|
||||
parts = append(parts, part{text: strings.TrimSpace(s[i+2 : j]), code: true})
|
||||
i = j
|
||||
case s[i] == '#' && i+1 < len(s) && (s[i+1] == '@' || s[i+1] == '$'):
|
||||
return rval{}, fmt.Errorf("unsupported interpolation in regex")
|
||||
default:
|
||||
b.WriteByte(s[i])
|
||||
}
|
||||
}
|
||||
flush()
|
||||
src, err := p.interp(parts)
|
||||
if err != nil {
|
||||
return rval{}, err
|
||||
}
|
||||
if err := onigCheck(src, strings.Contains(t.flags, "i")); err != nil {
|
||||
return rval{}, err
|
||||
}
|
||||
return rval{k: vRegex, re: regex{src, t.flags}}, nil
|
||||
}
|
||||
|
||||
// onig checks a regex source against a subset of Onigmo's Ruby syntax that Ruby 3.3 compiles without error: literals,
|
||||
// punctuation and class escapes, anchors, simple character classes, groups, lookarounds, alternation and
|
||||
// quantifiers. A look-behind holds alternatives of fixed-length atoms only, with case folding off.
|
||||
type onig struct {
|
||||
s string
|
||||
i int
|
||||
depth int
|
||||
}
|
||||
|
||||
func onigCheck(src string, icase bool) error {
|
||||
o := &onig{s: src}
|
||||
err := o.alt(icase, false)
|
||||
if err == nil && o.i < len(o.s) {
|
||||
err = fmt.Errorf("unmatched close parenthesis")
|
||||
}
|
||||
if err != nil {
|
||||
return fmt.Errorf("regex %q: %w", src, err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (o *onig) peek(off int) byte {
|
||||
if o.i+off < len(o.s) {
|
||||
return o.s[o.i+off]
|
||||
}
|
||||
return 0
|
||||
}
|
||||
|
||||
func (o *onig) alt(icase, behind bool) error {
|
||||
for {
|
||||
n, err := o.seq(icase, behind)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if behind && n <= 0 {
|
||||
return fmt.Errorf("look-behind alternative without a fixed length")
|
||||
}
|
||||
if o.peek(0) != '|' {
|
||||
return nil
|
||||
}
|
||||
o.i++
|
||||
}
|
||||
}
|
||||
|
||||
// seq parses one alternative and returns its length in characters.
|
||||
func (o *onig) seq(icase, behind bool) (int, error) {
|
||||
n := 0
|
||||
for o.i < len(o.s) && o.s[o.i] != '|' && o.s[o.i] != ')' {
|
||||
w, repeatable, err := o.atom(icase, behind)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
if c := o.peek(0); c == '*' || c == '+' || c == '?' || c == '{' {
|
||||
if !repeatable {
|
||||
return 0, fmt.Errorf("invalid target of repeat operator")
|
||||
}
|
||||
exact, err := o.quantifier()
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
if behind && exact < 0 {
|
||||
return 0, fmt.Errorf("variable repeat in look-behind")
|
||||
}
|
||||
w *= exact
|
||||
}
|
||||
n += w
|
||||
}
|
||||
return n, nil
|
||||
}
|
||||
|
||||
// quantifier consumes one quantifier with an optional lazy or possessive suffix, returning its exact count or -1.
|
||||
func (o *onig) quantifier() (int, error) {
|
||||
exact := -1
|
||||
if c := o.s[o.i]; c != '{' {
|
||||
o.i++
|
||||
if s := o.peek(0); s == '?' || s == '+' {
|
||||
o.i++
|
||||
}
|
||||
} else {
|
||||
end := strings.IndexByte(o.s[o.i:], '}')
|
||||
if end < 0 {
|
||||
return 0, fmt.Errorf("unsupported literal {")
|
||||
}
|
||||
lo, hi, comma := strings.Cut(o.s[o.i+1:o.i+end], ",")
|
||||
num := func(s string) (int, bool) {
|
||||
n, err := strconv.Atoi(s)
|
||||
return n, err == nil && s == strconv.Itoa(n) && n <= 100000
|
||||
}
|
||||
l, lok := num(lo)
|
||||
h, hok := num(hi)
|
||||
switch {
|
||||
case !comma && lok:
|
||||
exact = l
|
||||
case comma && lok && hi == "", comma && lo == "" && hok:
|
||||
case comma && lok && hok && l <= h:
|
||||
default:
|
||||
return 0, fmt.Errorf("unsupported interval {%s}", o.s[o.i+1:o.i+end])
|
||||
}
|
||||
o.i += end + 1
|
||||
if o.peek(0) == '?' {
|
||||
o.i++
|
||||
}
|
||||
}
|
||||
if c := o.peek(0); c == '*' || c == '+' || c == '?' || c == '{' {
|
||||
return 0, fmt.Errorf("nested repeat operator")
|
||||
}
|
||||
return exact, nil
|
||||
}
|
||||
|
||||
// atom consumes one atom and returns its length in characters and whether a quantifier may follow it.
|
||||
func (o *onig) atom(icase, behind bool) (int, bool, error) {
|
||||
switch c := o.s[o.i]; c {
|
||||
case '(':
|
||||
if behind {
|
||||
return 0, false, fmt.Errorf("group in look-behind")
|
||||
}
|
||||
if o.depth++; o.depth > 64 {
|
||||
return 0, false, fmt.Errorf("groups nested too deep")
|
||||
}
|
||||
defer func() { o.depth-- }()
|
||||
o.i++
|
||||
repeatable, lookbehind := true, false
|
||||
if o.peek(0) == '?' {
|
||||
switch {
|
||||
case o.peek(1) == ':':
|
||||
o.i += 2
|
||||
case o.peek(1) == '=' || o.peek(1) == '!':
|
||||
o.i += 2
|
||||
repeatable = false
|
||||
case o.peek(1) == '<' && (o.peek(2) == '=' || o.peek(2) == '!'):
|
||||
if icase {
|
||||
return 0, false, fmt.Errorf("look-behind with case folding")
|
||||
}
|
||||
o.i += 3
|
||||
repeatable, lookbehind = false, true
|
||||
default:
|
||||
o.i++
|
||||
on := true
|
||||
for ; o.peek(0) != ':'; o.i++ {
|
||||
switch f := o.peek(0); {
|
||||
case f == '-' && on:
|
||||
on = false
|
||||
case f == 'i':
|
||||
icase = on
|
||||
case f == 'm' || f == 'x' && !on:
|
||||
default:
|
||||
return 0, false, fmt.Errorf("unsupported group option")
|
||||
}
|
||||
}
|
||||
o.i++
|
||||
}
|
||||
}
|
||||
if err := o.alt(icase, lookbehind); err != nil {
|
||||
return 0, false, err
|
||||
}
|
||||
if o.peek(0) != ')' {
|
||||
return 0, false, fmt.Errorf("end pattern with unmatched parenthesis")
|
||||
}
|
||||
o.i++
|
||||
return 0, repeatable, nil
|
||||
case '[':
|
||||
return 1, true, o.class()
|
||||
case '\\':
|
||||
w, err := o.escape(false)
|
||||
if w == 0 && behind {
|
||||
return 0, false, fmt.Errorf("anchor in look-behind")
|
||||
}
|
||||
return w, w > 0, err
|
||||
case '.':
|
||||
o.i++
|
||||
return 1, true, nil
|
||||
case '^', '$':
|
||||
if behind {
|
||||
return 0, false, fmt.Errorf("anchor in look-behind")
|
||||
}
|
||||
o.i++
|
||||
return 0, false, nil
|
||||
case '*', '+', '?', '{', ']':
|
||||
return 0, false, fmt.Errorf("unsupported %q here", c)
|
||||
}
|
||||
r, n := utf8.DecodeRuneInString(o.s[o.i:])
|
||||
if r == utf8.RuneError {
|
||||
return 0, false, fmt.Errorf("invalid multibyte character")
|
||||
}
|
||||
o.i += n
|
||||
return 1, true, nil
|
||||
}
|
||||
|
||||
// escape consumes a backslash escape, returning 1 for a character or class and 0 for an anchor, which a character
|
||||
// class does not allow.
|
||||
func (o *onig) escape(inClass bool) (int, error) {
|
||||
c := o.peek(1)
|
||||
o.i += 2
|
||||
switch {
|
||||
case strings.IndexByte("dDwWsShHntrfvea", c) >= 0:
|
||||
return 1, nil
|
||||
case !inClass && strings.IndexByte("AzZbB", c) >= 0:
|
||||
return 0, nil
|
||||
case c > 0x20 && c < 0x7f && !unicode.IsLetter(rune(c)) && !unicode.IsDigit(rune(c)):
|
||||
return 1, nil
|
||||
}
|
||||
return 0, fmt.Errorf("unsupported escape")
|
||||
}
|
||||
|
||||
// class consumes a bracket expression of characters, ranges in order and class escapes.
|
||||
func (o *onig) class() error {
|
||||
o.i++
|
||||
if o.peek(0) == '^' {
|
||||
o.i++
|
||||
}
|
||||
n, prev := 0, -1
|
||||
for {
|
||||
c := o.peek(0)
|
||||
switch {
|
||||
case o.i >= len(o.s):
|
||||
return fmt.Errorf("premature end of char-class")
|
||||
case c == ']' && n > 0:
|
||||
o.i++
|
||||
return nil
|
||||
case c == ']', c == '[', c == '&' && o.peek(1) == '&', c >= 0x80:
|
||||
return fmt.Errorf("unsupported character class")
|
||||
case c == '\\':
|
||||
e := o.peek(1)
|
||||
if _, err := o.escape(true); err != nil {
|
||||
return err
|
||||
}
|
||||
prev = -1
|
||||
if strings.IndexByte("dDwWsShHntrfvea", e) < 0 {
|
||||
prev = int(e)
|
||||
}
|
||||
case c == '-' && n > 0 && o.peek(1) != ']':
|
||||
o.i++
|
||||
hi := int(o.peek(0))
|
||||
if o.peek(0) == '\\' {
|
||||
if e := o.peek(1); strings.IndexByte("dDwWsShHntrfvea", e) >= 0 {
|
||||
return fmt.Errorf("unsupported range end")
|
||||
}
|
||||
hi = int(o.peek(1))
|
||||
if _, err := o.escape(true); err != nil {
|
||||
return err
|
||||
}
|
||||
} else {
|
||||
if hi == '[' || hi == ']' || hi >= 0x80 || o.i >= len(o.s) {
|
||||
return fmt.Errorf("unsupported range end")
|
||||
}
|
||||
o.i++
|
||||
}
|
||||
if prev < 0 || hi < prev {
|
||||
return fmt.Errorf("bad range in char-class")
|
||||
}
|
||||
prev = -1
|
||||
default:
|
||||
prev = int(c)
|
||||
o.i++
|
||||
}
|
||||
n++
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2,6 +2,8 @@ package gentypes
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"slices"
|
||||
"strconv"
|
||||
"strings"
|
||||
@@ -50,6 +52,8 @@ func inspect(v rval) string {
|
||||
return "[" + strings.Join(parts, ", ") + "]"
|
||||
case vNum:
|
||||
return v.s
|
||||
case vNil:
|
||||
return "nil"
|
||||
}
|
||||
s, _ := rubyToS(v)
|
||||
return s
|
||||
@@ -105,6 +109,28 @@ var evalCases = []struct{ name, src, ruby, want string }{
|
||||
{"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=[]"},
|
||||
{"and", "X = 1 && 2\n", "2 pub=[] priv=[]", "2 pub=[]"},
|
||||
{"and nil", "X = nil && 1\n", "nil pub=[] priv=[]", "nil pub=[]"},
|
||||
{"or", "X = false || :b\n", ":b pub=[] priv=[]", ":b pub=[]"},
|
||||
{"or first", "X = 1 || nil\n", "1 pub=[] priv=[]", "1 pub=[]"},
|
||||
{"or and precedence", "X = 1 || nil && 2\n", "1 pub=[] priv=[]", "1 pub=[]"},
|
||||
{"not", "X = !nil\n", "true pub=[] priv=[]", "true pub=[]"},
|
||||
{"not binds tight", "X = !1 == false\n", "true pub=[] priv=[]", "true pub=[]"},
|
||||
{"respond_to", "X = :a.respond_to?(:intern)\n", "true pub=[] priv=[]", "true pub=[]"},
|
||||
{"respond_to unknown", "X = 'a'.respond_to?(:nope)\n", "false pub=[] priv=[]", "skip"},
|
||||
{"is_a", "X = :a.is_a?(Symbol) && !'a'.is_a?(Symbol)\n", "true pub=[] priv=[]", "true pub=[]"},
|
||||
{"kind_of Object", "X = [].kind_of?(Object)\n", "true pub=[] priv=[]", "true pub=[]"},
|
||||
{"is_a unmodelled", "X = nil.is_a?(Comparable)\n", "false pub=[] priv=[]", "skip"},
|
||||
{"intern", "X = 'a'.intern\n", ":a pub=[] priv=[]", ":a pub=[]"},
|
||||
{"hash new", "X = Hash.new { |h, k| h[k] = [] }\n", "{} pub=[] priv=[]", "{} pub=[]"},
|
||||
{"loop reassign param", "%w[a].each do |p|\n p = 'z' if p == 'a'\n define_method(p) {}\nend\n", "- pub=[:z] priv=[]", "- pub=[:z]"},
|
||||
{"loop reassign skipped", "%i[a b].each do |p|\n p = p.intern if p.respond_to?(:intern) && !p.is_a?(Symbol)\n define_method(p) {}\n define_method(\"#{p}=\") {}\nend\n", "- pub=[:a, :a=, :b, :b=] priv=[]", "- pub=[:a, :a=, :b, :b=]"},
|
||||
{"loop assign other", "[:a].each do |p|\n q = p\n define_method(q) {}\nend\n", "- pub=[:a] priv=[]", "skip"},
|
||||
{"regex interp", "R = %r{b}\nX = \"#{%r{a#{R}c}}\"\n", "\"(?-mix:a(?-mix:b)c)\" pub=[] priv=[]", "\"(?-mix:a(?-mix:b)c)\" pub=[]"},
|
||||
{"regex interp look-behind", "R = %r{.{1,3}(?<!~|bak)}\nX = \"#{%r{^if[a-z_]+(?::#{R})?$}}\"\n", "\"(?-mix:^if[a-z_]+(?::(?-mix:.{1,3}(?<!~|bak)))?$)\" pub=[] priv=[]", "\"(?-mix:^if[a-z_]+(?::(?-mix:.{1,3}(?<!~|bak)))?$)\" pub=[]"},
|
||||
{"regex interp invalid", "P = '+'\nX = %r{(?<!a#{P})}\n", "raise RegexpError", "skip"},
|
||||
{"regex interp x flag", "X = %r{a#{'b'}}x\n", "/ab/x pub=[] priv=[]", "skip"},
|
||||
{"regex interp string", "X = \"#{%r{a#{'[b-c]'}}}\"\n", "\"(?-mix:a[b-c])\" pub=[] priv=[]", "\"(?-mix:a[b-c])\" pub=[]"},
|
||||
}
|
||||
|
||||
func TestEvaluator(t *testing.T) {
|
||||
@@ -185,3 +211,107 @@ func TestEvaluatorBudgets(t *testing.T) {
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
const (
|
||||
fmInitvars = " super\n @mapped = Hash.new { |h, k| h[k] = {} }\n @filetype = :flat\n"
|
||||
fmHook = " klass.extend PuppetX::Fm::ClassMethods\n klass.mk_property_methods\n klass.initvars\n"
|
||||
)
|
||||
|
||||
// fmModule is a filemapper 4.0.0-style mixin whose included hook extends ClassMethods, defines property methods and
|
||||
// runs initvars; extra adds ClassMethods methods.
|
||||
func fmModule(extra, initvars, hook string) string {
|
||||
return "module PuppetX; end\nmodule PuppetX::Fm\n def create; end\n def flush; end\n def self.included(klass)\n" + hook +
|
||||
" end\n module ClassMethods\n attr_accessor :filetype\n def initvars\n" + initvars + " end\n" + extra +
|
||||
" def mk_property_methods\n resource_type.validproperties.each do |attr|\n" +
|
||||
" attr = attr.intern if attr.respond_to?(:intern) && !attr.is_a?(Symbol)\n define_method(attr) do\n end\n" +
|
||||
" define_method(\"#{attr}=\") do |val|\n end\n end\n end\n end\nend\n"
|
||||
}
|
||||
|
||||
// Each env includes fmModule or a variant. openvox 9.3.0 writes the provider doc in want; w10k must write the same,
|
||||
// or skip where want is "".
|
||||
func TestIncludedHook(t *testing.T) {
|
||||
const typ = "Puppet::Type.newtype(:t) do\n feature :fprop, 'p', methods: [:a, :a=]\n feature :fmix, 'm', methods: [:flush]\n" +
|
||||
" newparam(:name)\n newproperty(:a)\n newproperty(:b)\nend\n"
|
||||
iv, hook, mixin := fmInitvars, fmHook, fmModule
|
||||
prov := func(pre, opts, body string) string {
|
||||
return "require 'puppet_x/m/fm'\n" + pre + "Puppet::Type.type(:t).provide(:x" + opts + ") do\n" + body + "end\n"
|
||||
}
|
||||
const feats = " # * Supported features: `fmix`, `fprop`.\n"
|
||||
for name, c := range map[string]struct{ mixin, typ, prov, want string }{
|
||||
"wipes earlier DSL": {mixin("", iv, hook), typ, prov("", "", " defaultfor osfamily: :x\n commands zz: 'zz'\n include PuppetX::Fm\n desc 'd'\n defaultfor osfamily: :y\n"),
|
||||
" # : d\n # \n # * Default for `osfamily` == `y`.\n" + feats},
|
||||
"private before include": {mixin("", iv, hook), typ, prov("", "", " private\n include PuppetX::Fm\n"), " # : * Supported features: `fmix`, `fprop`.\n"},
|
||||
"initvars after include": {mixin("", iv, hook), typ, prov("", "", " include PuppetX::Fm\n defaultfor osfamily: :x\n initvars\n defaultfor osfamily: :y\n"),
|
||||
" # : * Default for `osfamily` == `y`.\n" + feats},
|
||||
"own singleton wins": {mixin("", iv, hook), typ, prov("", "", " def self.mk_property_methods\n end\n include PuppetX::Fm\n"), " # : * Supported features: `fmix`.\n"},
|
||||
"commands after include": {mixin("", iv, hook), typ, prov("", "", " include PuppetX::Fm\n commands zz: 'zz'\n"), " # : * Required binaries: `zz`.\n" + feats},
|
||||
"hook shadowed": {mixin(" def postinit\n end\n", iv, hook), typ, prov("", "", " include PuppetX::Fm\n"), ""},
|
||||
"initvars without super": {mixin("", " @defaults = [{ osfamily: :q }]\n", hook), typ, prov("", "", " include PuppetX::Fm\n"), ""},
|
||||
"initvars sets doc": {mixin("", " super\n @doc = 'z'\n", hook), typ, prov("", "", " include PuppetX::Fm\n"), ""},
|
||||
"hook sends": {mixin("", iv, " klass.send(:initvars)\n"), typ, prov("", "", " include PuppetX::Fm\n"), ""},
|
||||
"parsedfile filetype": {mixin("", iv, hook), typ, prov("require 'puppet/provider/parsedfile'\n", ", parent: Puppet::Provider::ParsedFile", " include PuppetX::Fm\n"), ""},
|
||||
"type includes hook": {mixin("", iv, hook), "require 'puppet_x/m/fm'\n" + strings.Replace(typ, " newparam(:name)\n", " include PuppetX::Fm\n newparam(:name)\n", 1),
|
||||
prov("", "", ""), ""},
|
||||
} {
|
||||
t.Run(name, func(t *testing.T) {
|
||||
env := fidelityEnv(t, map[string]string{"m/lib/puppet_x/m/fm.rb": c.mixin, "m/lib/puppet/type/t.rb": c.typ, "m/lib/puppet/provider/t/x.rb": c.prov})
|
||||
b, err := os.ReadFile(filepath.Join(env, OutDir, "t.pp"))
|
||||
want := " # x\n" + c.want + " Puppet::Resource::Param(Any, 'provider')"
|
||||
switch {
|
||||
case c.want == "" && err == nil:
|
||||
t.Fatalf("t.pp written; w10k cannot prove it:\n%s", b)
|
||||
case c.want != "" && !strings.Contains(string(b), want):
|
||||
t.Fatalf("t.pp lacks %q: %v\n%s", want, err, b)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// Ruby 3.3's Regexp.new compiles each source when ruby is true; onigCheck may accept only those, and declines the
|
||||
// forms it does not model.
|
||||
func TestOnigCheck(t *testing.T) {
|
||||
for _, c := range []struct {
|
||||
src string
|
||||
ruby, want bool
|
||||
}{
|
||||
{`\Aifcfg-[a-z]+[a-z_\d]+(?::(?-mix:.{1,12}(?<!~|\.bak|\.old|\.orig|\.rpmnew|\.rpmorig|\.rpmsave))|\.(?-mix:[1-3]?\d{1,3}|40[0-8]\d|409[0-5]))?\Z`, true, true},
|
||||
{`a|`, true, true},
|
||||
{`()(?:)`, true, true},
|
||||
{`[-a][a-]`, true, true},
|
||||
{`x{2}?y*+z??`, true, true},
|
||||
{`(?i:a)(?m-i:b)`, true, true},
|
||||
{`(?<=ab|c)(?<!\d{2}x)`, true, true},
|
||||
{`[^\]a\d]`, true, true},
|
||||
{`a{,3}b{2,}`, true, true},
|
||||
{`é.`, true, true},
|
||||
{`(?=a)(?!b)`, true, true},
|
||||
{`^\bx\B$`, true, true},
|
||||
{`(?<!a+)`, false, false},
|
||||
{`(?<=a|b*)`, false, false},
|
||||
{`[z-a]`, false, false},
|
||||
{`a{3,2}`, false, false},
|
||||
{`(a`, false, false},
|
||||
{`a)`, false, false},
|
||||
{`*a`, false, false},
|
||||
{`a{2}{3}`, true, false},
|
||||
{`[]`, false, false},
|
||||
{`a\`, false, false},
|
||||
{`(?<=(a))`, true, false},
|
||||
{`(?<=^a)`, true, false},
|
||||
{`(?<n>a)`, true, false},
|
||||
{`\x41`, true, false},
|
||||
{`(?i:(?<=ss))`, true, false},
|
||||
{`a{1,2}+`, true, false},
|
||||
{`[[:alpha:]]`, true, false},
|
||||
{`(?x:a b)`, true, false},
|
||||
{`a{`, true, false},
|
||||
{`a]`, true, false},
|
||||
{`(?#c)`, true, false},
|
||||
{`[a-\d]`, false, false},
|
||||
{`[\d-z]`, false, false},
|
||||
} {
|
||||
if err := onigCheck(c.src, false); (err == nil) != c.want || err == nil && !c.ruby {
|
||||
t.Errorf("%s: got %v, want accepted=%v (ruby compiles it: %v)", c.src, err, c.want, c.ruby)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -48,10 +48,15 @@ func FuzzEval(f *testing.F) {
|
||||
for _, c := range evalCases {
|
||||
f.Add(c.src)
|
||||
}
|
||||
f.Add("include PuppetX::Fm\ndefaultfor a: :b\n")
|
||||
fm := fmModule("", fmInitvars, fmHook)
|
||||
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"}}
|
||||
if err := (&parser{w: w}).load(libFile{mod: "m", rel: "puppet_x/m/fm.rb", src: fm}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
_, _ = 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)
|
||||
})
|
||||
}
|
||||
|
||||
@@ -18,7 +18,7 @@ import (
|
||||
const OutDir = ".resource_types"
|
||||
|
||||
// Version changes whenever generated output can change, so deploys rebuild typed environments.
|
||||
const Version = "7"
|
||||
const Version = "8"
|
||||
|
||||
var moduleName = regexp.MustCompile(`^[a-z][a-z0-9_]*$`)
|
||||
|
||||
|
||||
@@ -696,7 +696,9 @@ func TestMixinMethods(t *testing.T) {
|
||||
for src, want := range map[string]string{
|
||||
"module PuppetX\n module M\n module Mix\n X = 1\n def self.try; end\n def create; end\n private\n def destroy; end\n end\n end\nend\n": "create",
|
||||
"require 'x'\nmodule Other\n def destroy; end\nend\nmodule PuppetX::M\n module Mix\n def exists?; end\n end\nend\n": "exists?",
|
||||
"module PuppetX::M::Mix\n def self.included(base); base.newparam(:x); end\nend\n": "def self.included hook",
|
||||
"module PuppetX::M::Mix\n def self.included(base); base.newparam(:x); end\n def create; end\nend\n": "create",
|
||||
"module PuppetX::M::Mix\n def self.append_features(base); end\nend\n": "def self.append_features hook",
|
||||
"module PuppetX::M::Mix\n module ClassMethods\n def x; end\n end\n def flush; end\nend\n": "flush",
|
||||
"module PuppetX::M::Mix\n include Other\nend\n": "unsupported include Other in mixin",
|
||||
"module PuppetX::M::Mix\n extend ActiveSupport::Concern\nend\n": "unsupported extend",
|
||||
"module PuppetX::M\nend\n": "not defined",
|
||||
|
||||
@@ -352,10 +352,14 @@ type classCtx struct {
|
||||
parentUnknown bool
|
||||
typ *rtype
|
||||
block bool
|
||||
// a module's instance method bodies and included hook; extended methods that stand in for the ones they shadow
|
||||
idefs map[string]*sdef
|
||||
included *sdef
|
||||
supers map[string]bool
|
||||
}
|
||||
|
||||
func newClass(kind byte, gen bool) *classCtx {
|
||||
return &classCtx{kind: kind, gen: gen, methods: map[string]bool{}, smethods: map[string]bool{}, hidden: map[string]bool{}, cmds: map[string]bool{}, commands: map[string]string{}}
|
||||
return &classCtx{kind: kind, gen: gen, methods: map[string]bool{}, smethods: map[string]bool{}, hidden: map[string]bool{}, cmds: map[string]bool{}, commands: map[string]string{}, idefs: map[string]*sdef{}, supers: map[string]bool{}}
|
||||
}
|
||||
|
||||
// Hooks Ruby or Puppet::Provider call on a class or module while loading it; defining one runs code w10k cannot see.
|
||||
@@ -379,6 +383,8 @@ func (p *parser) classStmt(name string, c *classCtx) func() (bool, error) {
|
||||
switch {
|
||||
case t.kind == tIdent && (t.text == "require" || t.text == "require_relative"):
|
||||
return true, p.require()
|
||||
case t.kind == tIdent && t.text == "def" && c.kind == kMod && p.at(1).text == "self" && p.at(2).text == "." && p.at(3).text == "included":
|
||||
return true, p.includedHook(c)
|
||||
case t.kind == tIdent && t.text == "def":
|
||||
return true, p.defMethod(c, false)
|
||||
case t.kind == tIdent && t.text == "class" && p.at(1).text == "<<" && p.at(2).text == "self":
|
||||
@@ -423,8 +429,11 @@ func (p *parser) classStmt(name string, c *classCtx) func() (bool, error) {
|
||||
}
|
||||
names, err := p.mixin(m)
|
||||
c.mixed = append(c.mixed, names...)
|
||||
if err == nil {
|
||||
err = p.runIncluded(c, p.lexical(m))
|
||||
}
|
||||
return true, err
|
||||
case t.kind == tIdent && (c.kind == kProv || c.kind == kParsed) && providerDSL[t.text] && !c.smethods[t.text]:
|
||||
case t.kind == tIdent && (c.kind == kProv || c.kind == kParsed) && providerDSL[t.text] && (!c.smethods[t.text] || c.supers[t.text]):
|
||||
return true, p.providerCall(c)
|
||||
}
|
||||
if ok, err := p.evalStmt(c); ok {
|
||||
@@ -441,7 +450,16 @@ func (p *parser) defMethod(c *classCtx, single bool) error {
|
||||
}
|
||||
if !single {
|
||||
c.methods[n], c.hidden[n] = true, c.priv
|
||||
return p.skipStatement()
|
||||
if c.kind != kMod {
|
||||
return p.skipStatement()
|
||||
}
|
||||
sd := p.newSdef(off)
|
||||
c.idefs[n] = sd
|
||||
err := p.skipStatement()
|
||||
if sd != nil {
|
||||
sd.end = p.i - 1
|
||||
}
|
||||
return err
|
||||
}
|
||||
if hooks[n] || providerDSL[n] || strings.HasPrefix(n, "dochook_") {
|
||||
return fmt.Errorf("def self.%s runs while loading", n)
|
||||
|
||||
@@ -115,6 +115,7 @@ type parser struct {
|
||||
// evaluator state: block and method locals, self's class, inlined call depth, and conditional-assignment flags
|
||||
locals map[string]rval
|
||||
cls *classCtx
|
||||
bparam string
|
||||
calls int
|
||||
noDo bool
|
||||
condAssign bool
|
||||
@@ -1004,10 +1005,14 @@ func (p *parser) include(t *rtype) error {
|
||||
for _, n := range names {
|
||||
t.methods[n] = true
|
||||
}
|
||||
if mc := p.w.classes[p.lexical(m)]; err == nil && mc != nil && mc.included != nil {
|
||||
return fmt.Errorf("include %s: its included hook runs on the type", m)
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
// mixinMethods returns the public instance methods module path defines in src, failing on anything include could act on.
|
||||
// mixinMethods returns the public instance methods module path defines in src, failing on anything include could act on
|
||||
// other than an included hook, which loading the module records.
|
||||
func mixinMethods(src, path string) (methods []string, err error) {
|
||||
defer guard(&err)
|
||||
toks, err := lex(src)
|
||||
@@ -1021,10 +1026,12 @@ func mixinMethods(src, path string) (methods []string, err error) {
|
||||
c := p.cur()
|
||||
switch {
|
||||
case c.kind == tIdent && c.text == "def" && p.at(1).kind == tIdent && p.at(1).text == "self" && p.at(2).text == ".":
|
||||
if n := p.at(3).text; n == "included" || n == "append_features" {
|
||||
if n := p.at(3).text; n == "append_features" {
|
||||
return true, fmt.Errorf("def self.%s hook", n)
|
||||
}
|
||||
return true, p.skipStatement()
|
||||
case c.kind == tIdent && (c.text == "module" || c.text == "class") && p.at(1).kind == tConst:
|
||||
return true, p.skipStatement()
|
||||
case c.kind == tIdent && c.text == "def":
|
||||
if !private {
|
||||
methods = append(methods, p.at(1).text)
|
||||
@@ -1658,7 +1665,7 @@ func (p *parser) primary() (rval, error) {
|
||||
case tRegex:
|
||||
p.take()
|
||||
if strings.Contains(t.text, "#{") {
|
||||
return rval{}, fmt.Errorf("unsupported interpolation in regex")
|
||||
return p.regexInterp(t)
|
||||
}
|
||||
return rval{k: vRegex, re: regex{t.text, t.flags}}, nil
|
||||
case tWords:
|
||||
|
||||
@@ -0,0 +1,178 @@
|
||||
Copyright 2012 Adrien Thebo
|
||||
|
||||
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
|
||||
+315
@@ -0,0 +1,315 @@
|
||||
# frozen_string_literal: true
|
||||
|
||||
require 'puppet/util/filetype'
|
||||
|
||||
# Forward declaration
|
||||
module PuppetX; end
|
||||
|
||||
module PuppetX::FileMapper
|
||||
# Copy all desired resource properties into this resource for generation upon flush
|
||||
#
|
||||
# This method is necessary for the provider to be ensurable
|
||||
def create
|
||||
raise Puppet::Error, "#{self.class} is in an error state" if self.class.failed?
|
||||
|
||||
@resource.class.validproperties.each do |property|
|
||||
@property_hash[property] = @resource.should(property) if @resource.should(property)
|
||||
end
|
||||
dirty!
|
||||
end
|
||||
|
||||
# Use the prefetched status to determine of the resource exists.
|
||||
#
|
||||
# This method is necessary for the provider to be ensurable
|
||||
#
|
||||
# @return [TrueClass || FalseClass]
|
||||
def exists?
|
||||
@property_hash[:ensure] && @property_hash[:ensure] == :present
|
||||
end
|
||||
|
||||
# Update the property hash to mark this resource as absent for flushing
|
||||
#
|
||||
# This method is necessary for the provider to be ensurable
|
||||
def destroy
|
||||
@property_hash[:ensure] = :absent
|
||||
dirty!
|
||||
end
|
||||
|
||||
# Mark the file associated with this resource as dirty
|
||||
def dirty!
|
||||
file = select_file
|
||||
self.class.dirty_file!(file)
|
||||
end
|
||||
|
||||
# When processing on this resource is complete, trigger a flush on the file
|
||||
# that this resource belongs to.
|
||||
def flush
|
||||
self.class.flush_file(select_file)
|
||||
end
|
||||
|
||||
def self.included(klass)
|
||||
klass.extend PuppetX::FileMapper::ClassMethods
|
||||
klass.mk_property_methods
|
||||
klass.initvars
|
||||
end
|
||||
|
||||
module ClassMethods
|
||||
# @!attribute [rw] unlink_empty_files
|
||||
# @return [TrueClass || FalseClass] Whether empty files will be removed
|
||||
attr_accessor :unlink_empty_files
|
||||
|
||||
# @!attribute [rw] filetype
|
||||
# @return [Symbol] The FileType to use when interacting with target files
|
||||
attr_accessor :filetype
|
||||
|
||||
# @!attribute [r] mapped_files
|
||||
# @return [Hash<filepath => Hash<:dirty => Bool, :filetype => Filetype>>]
|
||||
# A data structure representing the file paths and filetypes backing this
|
||||
# provider.
|
||||
attr_reader :mapped_files
|
||||
|
||||
def initvars
|
||||
super
|
||||
@mapped_files = Hash.new { |h, k| h[k] = {} }
|
||||
@unlink_empty_files = false
|
||||
@filetype = :flat
|
||||
@failed = false
|
||||
@all_providers = []
|
||||
end
|
||||
|
||||
def failed?
|
||||
@failed
|
||||
end
|
||||
|
||||
def failed!
|
||||
@failed = true
|
||||
end
|
||||
|
||||
# Register all provider instances with the class
|
||||
#
|
||||
# In order to flush all provider instances to a given file, we need to be
|
||||
# able to track them all. When provider#flush is called and the file
|
||||
# associated with that provider instance is dirty, the file needs to be
|
||||
# flushed and all provider instances associated with that file will be
|
||||
# passed to self.flush_file
|
||||
def new(*args)
|
||||
obj = super
|
||||
@all_providers << obj
|
||||
obj
|
||||
end
|
||||
|
||||
# Returns all instances of the provider using this mixin.
|
||||
#
|
||||
# @return [Array<Puppet::Provider>]
|
||||
def instances
|
||||
provider_hashes = load_all_providers_from_disk
|
||||
|
||||
provider_hashes.map do |h|
|
||||
h[:provider] = name
|
||||
h[:ensure] = :present
|
||||
new(h)
|
||||
end
|
||||
rescue StandardError
|
||||
# If something failed while loading instances, mark the provider class
|
||||
# as failed and pass the exception along
|
||||
failed!
|
||||
raise
|
||||
end
|
||||
|
||||
# Validate that the required methods are available.
|
||||
#
|
||||
# @raise Puppet::DevError if an expected method is unavailable
|
||||
def validate_class!
|
||||
required_class_hooks = %i[target_files parse_file format_file]
|
||||
required_instance_hooks = [:select_file]
|
||||
|
||||
required_class_hooks.each do |method|
|
||||
raise Puppet::DevError, "#{self} has not implemented `self.#{method}`" unless respond_to? method
|
||||
end
|
||||
|
||||
required_instance_hooks.each do |method|
|
||||
raise Puppet::DevError, "#{self} has not implemented `##{method}`" unless method_defined? method
|
||||
end
|
||||
end
|
||||
|
||||
# Reads all files from disk and returns an array of hashes representing
|
||||
# provider instances.
|
||||
#
|
||||
# @return [Array<Hash<String, Hash<Symbol, Object>>>]
|
||||
# An array containing a set of hashes, keyed with a file path and values
|
||||
# being a hash containing the state of the file and the filetype associated
|
||||
# with it.
|
||||
#
|
||||
# @example
|
||||
# IncludingProvider.load_all_providers_from_disk
|
||||
# # => [
|
||||
# # { "/path/to/file" => {
|
||||
# # :dirty => false,
|
||||
# # :filetype => #<Puppet::Util::FileTypeFlat:0x007fbf5b05ff10>,
|
||||
# # },
|
||||
# # { "/path/to/another/file" => {
|
||||
# # :dirty => false,
|
||||
# # :filetype => #<Puppet::Util::FileTypeFlat:0x007fbf5b05c108,
|
||||
# # },
|
||||
# #
|
||||
#
|
||||
def load_all_providers_from_disk
|
||||
validate_class!
|
||||
|
||||
# Retrieve a list of files to fetch, and cache a copy of a filetype
|
||||
# for each one
|
||||
target_files.each do |file|
|
||||
@mapped_files[file][:filetype] = Puppet::Util::FileType.filetype(filetype).new(file)
|
||||
@mapped_files[file][:dirty] = false
|
||||
end
|
||||
|
||||
# Read and parse each file.
|
||||
provider_hashes = []
|
||||
@mapped_files.each_pair do |filename, file_attrs|
|
||||
# The filetype path must be a type pathname, or it must respond to to_str
|
||||
# If it doesn't meet these criteria go to next file
|
||||
path = file_attrs[:filetype].path
|
||||
|
||||
next unless path.is_a?(Pathname) || path.respond_to?(:to_str)
|
||||
|
||||
arr = parse_file(filename, file_attrs[:filetype].read)
|
||||
raise Puppet::DevError, "expected #{self}.parse_file to return an Array, got a #{arr.class}" unless arr.is_a? Array
|
||||
|
||||
provider_hashes.concat arr
|
||||
end
|
||||
provider_hashes
|
||||
end
|
||||
|
||||
# Match up all resources that have existing providers.
|
||||
#
|
||||
# Pass over all provider instances, and see if there is a resource with the
|
||||
# same namevar as a provider instance. If such a resource exists, set the
|
||||
# provider field of that resource to the existing provider.
|
||||
#
|
||||
# This is a hook method that will be called by Puppet::Transaction#prefetch
|
||||
#
|
||||
# @param [Hash<String, Puppet::Resource>] resources
|
||||
def prefetch(resources = {})
|
||||
# generate hash of {provider_name => provider}
|
||||
providers = instances.each_with_object({}) do |instance, hash|
|
||||
# name is not necessarily the name_var.
|
||||
# n.b. the following will fall flat for composite namevars.
|
||||
namevar = resource_type.key_attributes.first
|
||||
hash[instance.send(namevar)] = instance
|
||||
end
|
||||
|
||||
# For each prefetched resource, try to match it to a provider
|
||||
resources.each_pair do |resource_name, resource|
|
||||
resource.provider = providers[resource_name] if providers[resource_name]
|
||||
end
|
||||
end
|
||||
|
||||
# Create attr_accessors for properties and mark the provider as dirty on change.
|
||||
def mk_property_methods
|
||||
resource_type.validproperties.each do |attr|
|
||||
attr = attr.intern if attr.respond_to?(:intern) && !attr.is_a?(Symbol)
|
||||
|
||||
# Generate the attr_reader method
|
||||
define_method(attr) do
|
||||
if @property_hash[attr].nil?
|
||||
:absent
|
||||
else
|
||||
@property_hash[attr]
|
||||
end
|
||||
end
|
||||
|
||||
# Generate the attr_writer and have it mark the resource as dirty when called
|
||||
define_method("#{attr}=") do |val|
|
||||
@property_hash[attr] = val
|
||||
dirty!
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
# Generate an array of providers that should be flushed to a specific file
|
||||
#
|
||||
# Only providers that should be present will be returned regardless of
|
||||
# the containing file.
|
||||
#
|
||||
# @param [String] filename The name of the file to find providers for
|
||||
#
|
||||
# @return [Array<Puppet::Provider>]
|
||||
def collect_providers_for_file(filename)
|
||||
@all_providers.select do |provider|
|
||||
provider.select_file == filename && provider.ensure == :present
|
||||
end
|
||||
end
|
||||
|
||||
def dirty_file!(filename)
|
||||
@mapped_files[filename][:dirty] = true
|
||||
end
|
||||
|
||||
# Flush provider instances associated with the given file and call any defined hooks
|
||||
#
|
||||
# If the provider is in a failure state, the provider class will refuse to
|
||||
# flush any file, since we're in an unknown state.
|
||||
#
|
||||
# This method respects two method hooks: `pre_flush_hook` and `post_flush_hook`.
|
||||
# These methods must accept one argument, the path of the file being flushed.
|
||||
# `post_flush_hook` is guaranteed to be called after the flush has occurred.
|
||||
#
|
||||
# @param [String] filename The path of the file to be flushed
|
||||
def flush_file(filename)
|
||||
if failed?
|
||||
err "#{name} is in an error state, refusing to flush file #{filename}"
|
||||
return
|
||||
end
|
||||
|
||||
if @mapped_files[filename][:dirty]
|
||||
# Collect all providers that should be present and pass them to the
|
||||
# including class for formatting.
|
||||
target_providers = collect_providers_for_file(filename)
|
||||
file_contents = format_file(filename, target_providers)
|
||||
|
||||
raise Puppet::DevError, "expected #{self}.format_file to return a String, got a #{file_contents.class}" unless file_contents.is_a? String
|
||||
|
||||
# Call the `pre_flush_hook` method if it's defined
|
||||
pre_flush_hook(filename) if respond_to? :pre_flush_hook
|
||||
|
||||
begin
|
||||
file_contents.empty? && unlink_empty_files ? remove_empty_file(filename) : perform_write(filename, file_contents)
|
||||
ensure
|
||||
post_flush_hook(filename) if respond_to? :post_flush_hook
|
||||
end
|
||||
else
|
||||
Puppet.debug "#{name} was requested to flush the file #{filename}, but it was not marked as dirty - doing nothing."
|
||||
end
|
||||
rescue StandardError
|
||||
# If something failed during the flush process, mark the provider as failed. There's not
|
||||
# much we can do about any file that's already been flushed but we can stop smashing things.
|
||||
@failed = true
|
||||
raise
|
||||
end
|
||||
|
||||
# We have a dirty file and the new contents ready, back up the file and perform the flush.
|
||||
#
|
||||
# @param [String] filename The destination filename
|
||||
# @param [String] contents The new file contents
|
||||
def perform_write(filename, contents)
|
||||
@mapped_files[filename][:filetype] ||= Puppet::Util::FileType.filetype(filetype).new(filename)
|
||||
filetype = @mapped_files[filename][:filetype]
|
||||
|
||||
filetype.backup if filetype.respond_to? :backup
|
||||
filetype.write(contents)
|
||||
end
|
||||
|
||||
# Back up and remove a file, if it exists
|
||||
#
|
||||
# @param [String] filename The file to remove
|
||||
def remove_empty_file(filename)
|
||||
return unless File.exist? filename
|
||||
|
||||
@mapped_files[filename][:filetype] ||= Puppet::Util::FileType.filetype(filetype).new(filename)
|
||||
filetype = @mapped_files[filename][:filetype]
|
||||
|
||||
filetype.backup if filetype.respond_to? :backup
|
||||
|
||||
File.unlink(filename)
|
||||
end
|
||||
end
|
||||
end
|
||||
+318
@@ -1,2 +1,320 @@
|
||||
require 'puppetx/filemapper'
|
||||
|
||||
Puppet::Type.type(:network_config).provide(:interfaces) do
|
||||
# Debian network_config interfaces provider.
|
||||
#
|
||||
# This provider uses the filemapper mixin to map the interfaces file to a
|
||||
# collection of network_config providers, and back.
|
||||
#
|
||||
# @see http://wiki.debian.org/NetworkConfiguration
|
||||
# @see http://packages.debian.org/squeeze/ifupdown
|
||||
|
||||
include PuppetX::FileMapper
|
||||
|
||||
desc 'Debian interfaces style provider'
|
||||
|
||||
confine osfamily: :debian
|
||||
defaultfor osfamily: :debian
|
||||
|
||||
has_feature :provider_options
|
||||
has_feature :hotpluggable
|
||||
|
||||
def select_file
|
||||
'/etc/network/interfaces'
|
||||
end
|
||||
|
||||
def self.target_files
|
||||
['/etc/network/interfaces']
|
||||
end
|
||||
|
||||
class MalformedInterfacesError < Puppet::Error
|
||||
def initialize(msg = nil)
|
||||
msg ||= 'Malformed debian interfaces file; cannot instantiate network_config resources'
|
||||
super
|
||||
end
|
||||
end
|
||||
|
||||
def self.raise_malformed
|
||||
@failed = true
|
||||
raise MalformedInterfacesError
|
||||
end
|
||||
|
||||
class Instance
|
||||
attr_reader :name
|
||||
|
||||
# Booleans
|
||||
attr_accessor :onboot, :hotplug
|
||||
|
||||
# These fields are going to get rearranged to resolve issue 16
|
||||
# https://github.com/adrienthebo/puppet-network/issues/16
|
||||
attr_accessor :ipaddress, :netmask, :family, :method, :mtu, :mode
|
||||
|
||||
# Options hash
|
||||
attr_reader :options
|
||||
|
||||
def initialize(name)
|
||||
@name = name
|
||||
|
||||
@options = Hash.new { |hash, key| hash[key] = [] }
|
||||
end
|
||||
|
||||
def to_hash
|
||||
h = {
|
||||
name: @name,
|
||||
onboot: @onboot,
|
||||
hotplug: @hotplug,
|
||||
ipaddress: @ipaddress,
|
||||
netmask: @netmask,
|
||||
family: @family,
|
||||
method: @method,
|
||||
mtu: @mtu,
|
||||
mode: @mode,
|
||||
options: squeeze_options
|
||||
}
|
||||
|
||||
h.each_with_object({}) do |(key, val), hash|
|
||||
hash[key] = val if val
|
||||
end
|
||||
end
|
||||
|
||||
def squeeze_options
|
||||
@options.each_with_object({}) do |(key, value), hash|
|
||||
hash[key] = if value.size <= 1
|
||||
value.pop
|
||||
else
|
||||
value
|
||||
end
|
||||
hash
|
||||
end
|
||||
end
|
||||
|
||||
class << self
|
||||
def reset!
|
||||
@interfaces = {}
|
||||
end
|
||||
|
||||
# @return [Array<Instance>] All class instances
|
||||
def all_instances
|
||||
@interfaces ||= {}
|
||||
@interfaces
|
||||
end
|
||||
|
||||
def [](name)
|
||||
if all_instances[name]
|
||||
obj = all_instances[name]
|
||||
else
|
||||
obj = new(name)
|
||||
all_instances[name] = obj
|
||||
end
|
||||
|
||||
obj
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
def self.parse_file(_filename, contents)
|
||||
# Debian has a very irregular format for the interfaces file. The
|
||||
# parse_file method is somewhat derived from the ifup executable
|
||||
# supplied in the debian ifupdown package. The source can be found at
|
||||
# http://packages.debian.org/squeeze/ifupdown
|
||||
|
||||
# The debian interfaces implementation requires global state while parsing
|
||||
# the file; namely, the stanza being parsed as well as the interface being
|
||||
# parsed.
|
||||
status = :none
|
||||
current_interface = nil
|
||||
lines = contents.split("\n")
|
||||
# TODO: Join lines that end with a backslash
|
||||
|
||||
# Iterate over all lines and determine what attributes they create
|
||||
lines.each do |line|
|
||||
# Strip off any trailing comments
|
||||
line.sub!(%r{#.*$}, '')
|
||||
|
||||
case line
|
||||
when %r{^\s*#|^\s*$}
|
||||
# Ignore comments and blank lines
|
||||
next
|
||||
|
||||
when %r{^source|^source-directory}
|
||||
# ignore source|source-directory sections, it makes this provider basically useless
|
||||
# with Debian Jessie. Please refer to man 5 interfaces
|
||||
next
|
||||
|
||||
when %r{^auto|^allow-auto}
|
||||
# Parse out any auto sections
|
||||
interfaces = line.split(' ')
|
||||
interfaces.delete_at(0)
|
||||
|
||||
interfaces.each do |name|
|
||||
Instance[name].onboot = true
|
||||
end
|
||||
|
||||
# Reset the current parse state
|
||||
current_interface = nil
|
||||
|
||||
when %r{^allow-hotplug}
|
||||
# parse out allow-hotplug lines
|
||||
|
||||
interfaces = line.split(' ')
|
||||
interfaces.delete_at(0)
|
||||
|
||||
interfaces.each do |name|
|
||||
Instance[name].hotplug = true
|
||||
end
|
||||
|
||||
# Don't reset Reset the current parse state
|
||||
when %r{^iface}
|
||||
|
||||
# Format of the iface line:
|
||||
#
|
||||
# iface <iface> <family> <method>
|
||||
# zero or more options for <iface>
|
||||
|
||||
raise_malformed unless line.match(%r{^iface\s+(\S+)\s+(\S+)\s+(\S+)}) do |matched|
|
||||
name = matched[1]
|
||||
family = matched[2]
|
||||
method = matched[3]
|
||||
|
||||
# If an iface block for this interface has been seen, the file is
|
||||
# malformed.
|
||||
raise_malformed if Instance[name] && Instance[name].family
|
||||
|
||||
status = :iface
|
||||
current_interface = name
|
||||
|
||||
# This is done automatically
|
||||
# Instance[name].name = name
|
||||
Instance[name].family = family
|
||||
Instance[name].method = method
|
||||
# for the vlan naming conventions (a mess), see
|
||||
# man 5 vlan-interfaces
|
||||
Instance[name].mode = case name
|
||||
# 'vlan22'
|
||||
when %r{^vlan}
|
||||
:vlan
|
||||
# 'eth2.0003' or 'br1.2'
|
||||
when %r{^[a-z]{1,}[0-9]{1,}\.[0-9]{1,4}}
|
||||
:vlan
|
||||
else
|
||||
:raw
|
||||
end
|
||||
end
|
||||
|
||||
when %r{^mapping}
|
||||
# XXX dox
|
||||
status = :mapping
|
||||
raise Puppet::DevError, 'Debian interfaces mapping parsing not implemented.'
|
||||
|
||||
else
|
||||
# We're currently examining a line that is within a mapping or iface
|
||||
# stanza, so we need to validate the line and add the options it
|
||||
# specifies to the known state of the interface.
|
||||
|
||||
case status
|
||||
when :iface
|
||||
raise_malformed unless line.match(%r{(\S+)\s+(\S.*)}) do |matched|
|
||||
# If we're parsing an iface stanza, then we should receive a set of
|
||||
# lines that contain two or more space delimited strings. Append
|
||||
# them as options to the iface in an array.
|
||||
|
||||
key = matched[1]
|
||||
val = matched[2]
|
||||
|
||||
name = current_interface
|
||||
|
||||
case key # rubocop:disable Metrics/BlockNesting
|
||||
when 'address' then Instance[name].ipaddress = val
|
||||
when 'netmask' then Instance[name].netmask = val
|
||||
when 'mtu' then Instance[name].mtu = val
|
||||
else Instance[name].options[key] << val
|
||||
end
|
||||
end
|
||||
when :mapping
|
||||
raise Puppet::DevError, 'Debian interfaces mapping parsing not implemented.'
|
||||
when :none
|
||||
raise_malformed
|
||||
end
|
||||
end
|
||||
end
|
||||
Instance.all_instances.map { |_name, instance| instance.to_hash }
|
||||
end
|
||||
|
||||
# Generate an array of sections
|
||||
def self.format_file(_filename, providers)
|
||||
contents = []
|
||||
contents << header
|
||||
|
||||
# Add onboot interfaces
|
||||
auto_interfaces = providers.select { |provider| provider.onboot == true }
|
||||
unless auto_interfaces.empty?
|
||||
stanza = []
|
||||
stanza << ('auto ' + auto_interfaces.map(&:name).sort.join(' '))
|
||||
contents << stanza.join("\n")
|
||||
end
|
||||
|
||||
# Add hotpluggable interfaces
|
||||
hotplug_interfaces = providers.select { |provider| provider.hotplug == true }
|
||||
unless hotplug_interfaces.empty?
|
||||
stanza = []
|
||||
stanza << ('allow-hotplug ' + hotplug_interfaces.map(&:name).sort.join(' '))
|
||||
contents << stanza.join("\n")
|
||||
end
|
||||
|
||||
# Build iface stanzas
|
||||
providers.sort_by(&:name).each do |provider|
|
||||
# TODO: add validation method
|
||||
raise Puppet::Error, "#{provider.name} does not have a method." if provider.method.nil?
|
||||
raise Puppet::Error, "#{provider.name} does not have a family." if provider.family.nil?
|
||||
|
||||
stanza = []
|
||||
stanza << %(iface #{provider.name} #{provider.family} #{provider.method})
|
||||
|
||||
# add the vlan-raw-device only when explicitely set in interfaces(5) stanza
|
||||
# otherwise it's already assumed given the stanza name (ethX.NN)
|
||||
if provider.mode == :vlan
|
||||
if provider.options['vlan-raw-device']
|
||||
stanza << "vlan-raw-device #{provider.options['vlan-raw-device']}"
|
||||
else
|
||||
vlan_range_regex = %r{[1-3]?\d{1,3}|40[0-8]\d|409[0-5]}
|
||||
raise Puppet::Error, "Interface #{provider.name}: missing vlan-raw-device or wrong VLAN ID in the iface name " unless provider.name =~ %r{\A([a-z]+\d+)(?::\d+|\.#{vlan_range_regex})\Z}
|
||||
end
|
||||
end
|
||||
|
||||
[
|
||||
[:ipaddress, 'address'],
|
||||
[:netmask, 'netmask'],
|
||||
[:mtu, 'mtu']
|
||||
].each do |(property, section)|
|
||||
stanza << "#{section} #{provider.send property}" if provider.send(property) && provider.send(property) != :absent
|
||||
end
|
||||
|
||||
if provider.options && provider.options != :absent
|
||||
provider.options.each_pair do |key, val|
|
||||
if val.is_a? String
|
||||
# dont print property because we've already added it to the stanza
|
||||
stanza << " #{key} #{val}" if key != 'vlan-raw-device'
|
||||
elsif val.is_a? Array
|
||||
val.each { |entry| stanza << " #{key} #{entry}" }
|
||||
else
|
||||
raise Puppet::Error, "#{self} options key #{key} expects a String or Array, got #{val.class}"
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
contents << stanza.join("\n")
|
||||
end
|
||||
|
||||
contents.map { |line| line + "\n\n" }.join
|
||||
end
|
||||
|
||||
def self.header
|
||||
<<~HEADER
|
||||
# HEADER: This file is being managed by puppet. Changes to
|
||||
# HEADER: interfaces that are not being managed by puppet will persist;
|
||||
# HEADER: however changes to interfaces that are being managed by puppet will
|
||||
# HEADER: be overwritten. In addition, file order is NOT guaranteed.
|
||||
# HEADER: Last generated at: #{Time.now}
|
||||
HEADER
|
||||
end
|
||||
end
|
||||
|
||||
internal/gentypes/testdata/env/external_modules/network/lib/puppet/provider/network_config/redhat.rb
Vendored
+240
@@ -1,2 +1,242 @@
|
||||
require 'puppetx/filemapper'
|
||||
|
||||
Puppet::Type.type(:network_config).provide(:redhat) do
|
||||
# Red Hat network_config network scripts provider.
|
||||
#
|
||||
# This provider manages the contents of /etc/networks-scripts/ifcfg-* to
|
||||
# manage non-volatile network configuration.
|
||||
#
|
||||
# @see https://access.redhat.com/knowledge/docs/en-US/Red_Hat_Enterprise_Linux/6/html/Deployment_Guide/s1-networkscripts-interfaces.html "Red Hat Interface Configuration Files"
|
||||
|
||||
include PuppetX::FileMapper
|
||||
|
||||
desc 'Redhat network-scripts provider'
|
||||
|
||||
confine osfamily: :redhat
|
||||
defaultfor osfamily: :redhat
|
||||
|
||||
has_feature :hotpluggable
|
||||
has_feature :provider_options
|
||||
|
||||
# @return [String] The path to network-script directory on redhat systems
|
||||
SCRIPT_DIRECTORY = '/etc/sysconfig/network-scripts'.freeze
|
||||
|
||||
# The valid vlan ID range is 0-4095; 4096 is out of range
|
||||
VLAN_RANGE_REGEX = %r{[1-3]?\d{1,3}|40[0-8]\d|409[0-5]}
|
||||
|
||||
# aliases are almost free game, redhat rejects some, and max total length is 15 characters
|
||||
# 15 minus at least 2 for the interface name, and a colon leaves 12 characters for the alias
|
||||
ALIAS_REGEX = %r{.{1,12}(?<!~|\.bak|\.old|\.orig|\.rpmnew|\.rpmorig|\.rpmsave)}
|
||||
|
||||
# @return [Regexp] The regular expression for interface scripts on redhat systems
|
||||
SCRIPT_REGEX = %r{\Aifcfg-[a-z]+[a-z_\d]+(?::#{ALIAS_REGEX}|\.#{VLAN_RANGE_REGEX})?\Z}
|
||||
|
||||
NAME_MAPPINGS = {
|
||||
ipaddress: 'IPADDR',
|
||||
netmask: 'NETMASK',
|
||||
method: 'BOOTPROTO',
|
||||
onboot: 'ONBOOT',
|
||||
name: 'DEVICE',
|
||||
hotplug: 'HOTPLUG',
|
||||
mtu: 'MTU'
|
||||
}.freeze
|
||||
|
||||
# Map provider instances to files based on their name
|
||||
#
|
||||
# @return [String] The path of the file for the given interface resource
|
||||
#
|
||||
# @example
|
||||
# prov = RedhatProvider.new(:name => 'eth1')
|
||||
# prov.select_file # => '/etc/sysconfig/network-scripts/ifcfg-eth1'
|
||||
#
|
||||
def select_file
|
||||
"#{SCRIPT_DIRECTORY}/ifcfg-#{name}"
|
||||
end
|
||||
|
||||
# Scan all files in the networking directory for interfaces
|
||||
#
|
||||
# @param script_dir [String] The path to the networking scripts, defaults to
|
||||
# {#SCRIPT_DIRECTORY}
|
||||
#
|
||||
# @return [Array<String>] All network-script config files on this machine.
|
||||
#
|
||||
# @example
|
||||
# RedhatProvider.target_files
|
||||
# # => ['/etc/sysconfig/network-scripts/ifcfg-eth0', '/etc/sysconfig/network-scripts/ifcfg-eth1']
|
||||
def self.target_files(script_dir = SCRIPT_DIRECTORY)
|
||||
entries = Dir.entries(script_dir).select { |entry| entry.match SCRIPT_REGEX }
|
||||
entries.map { |entry| File.join(SCRIPT_DIRECTORY, entry) }
|
||||
end
|
||||
|
||||
# Convert a redhat network script into a hash
|
||||
#
|
||||
# This is a hook method that will be called by PuppetX::Filemapper
|
||||
#
|
||||
# @param [String] filename The path of the interfaces file being parsed
|
||||
# @param [String] contents The contents of the given file
|
||||
#
|
||||
# @return [Array<Hash<Symbol, String>>] A single element array containing
|
||||
# the key/value pairs of properties parsed from the file.
|
||||
#
|
||||
# @example
|
||||
# RedhatProvider.parse_file('/etc/sysconfig/network-scripts/ifcfg-eth0', #<String:0xdeadbeef>)
|
||||
# # => [
|
||||
# # {
|
||||
# # :name => 'eth0',
|
||||
# # :ipaddress => '169.254.0.1',
|
||||
# # :netmask => '255.255.0.0',
|
||||
# # },
|
||||
# # ]
|
||||
def self.parse_file(filename, contents)
|
||||
# Split up the file into lines
|
||||
lines = contents.split("\n")
|
||||
# Strip out all comments
|
||||
lines.map! { |line| line.sub(%r{#.*$}, '') }
|
||||
# Remove all blank lines
|
||||
lines.reject! { |line| line =~ %r{^\s*$} }
|
||||
|
||||
pair_regex = %r{^\s*(.+?)\s*=\s*(.*)\s*$}
|
||||
|
||||
# INFO: It is valid ifcfg format to include certain functions and strings these should not be reported as errors, but silently removed before parsing
|
||||
# https://bugs.centos.org/bug_view_page.php?bug_id=475
|
||||
# Remove lines with no = sign
|
||||
lines.select! { |line| line =~ %r{^.*=.*$} }
|
||||
|
||||
# Convert the data into key/value pairs
|
||||
pairs = lines.each_with_object({}) do |line, hash|
|
||||
raise Puppet::Error, %(#{filename} is malformed; "#{line}" did not match "#{pair_regex}") unless line.match(pair_regex) do |m|
|
||||
key = m[1].strip
|
||||
val = m[2].strip
|
||||
hash[key] = val
|
||||
end
|
||||
|
||||
hash
|
||||
end
|
||||
|
||||
props = munge(pairs)
|
||||
|
||||
# TODO: remove duct tape for #13
|
||||
#
|
||||
# The :family property is making less and less sense because it seems that
|
||||
# ipv6 configuration should add new properties instead of trying to collide
|
||||
# with the ipv4 addresses. But right now, the :inet property is never used
|
||||
# and it's creating a change on each resource update. This is a patch until
|
||||
# the :family property is ripped out.
|
||||
#
|
||||
# See https://github.com/adrienthebo/puppet-network/issues/13 for the full
|
||||
# issue that caused this, and https://github.com/adrienthebo/puppet-network/issues/16
|
||||
# for the resolution.
|
||||
#
|
||||
props[:family] = :inet
|
||||
|
||||
# If there is no DEVICE property in the interface configuration we retrieve
|
||||
# the interface name from the file name itself
|
||||
props[:name] = filename.split('ifcfg-')[1] unless props.key?(:name)
|
||||
|
||||
# The FileMapper mixin expects an array of providers, so we return the
|
||||
# single interface wrapped in an array
|
||||
[props]
|
||||
end
|
||||
|
||||
# @api private
|
||||
def self.munge(pairs)
|
||||
props = {}
|
||||
|
||||
# Unquote all values
|
||||
pairs.each_pair do |key, val|
|
||||
if (munged = val.gsub(%r{['"]}, ''))
|
||||
pairs[key] = munged
|
||||
end
|
||||
end
|
||||
|
||||
# For each interface attribute that we recognize it, add the value to the
|
||||
# hash with our expected label
|
||||
NAME_MAPPINGS.each_pair do |type_name, redhat_name|
|
||||
next unless (val = pairs[redhat_name])
|
||||
|
||||
pairs.delete(redhat_name)
|
||||
props[type_name] = val
|
||||
end
|
||||
|
||||
# if we encounter VLAN=yes set the interface mode to :vlan
|
||||
pairs.each_pair do |key, val|
|
||||
props[:mode] = :vlan if key == 'VLAN' && val == 'yes'
|
||||
end
|
||||
pairs.delete('VLAN')
|
||||
|
||||
# mode is a property so it should always have a value
|
||||
props[:mode] ||= :raw
|
||||
|
||||
# For all of the remaining values, blindly toss them into the options hash.
|
||||
props[:options] = pairs
|
||||
|
||||
%i[onboot hotplug].each do |bool_property|
|
||||
props[bool_property] = (props[bool_property] == 'yes') unless props[bool_property].nil?
|
||||
end
|
||||
|
||||
props[:method] = 'static' unless %w[bootp dhcp].include? props[:method]
|
||||
|
||||
props
|
||||
end
|
||||
|
||||
def self.format_file(filename, providers)
|
||||
return '' if providers.empty?
|
||||
|
||||
if providers.length > 1
|
||||
raise Puppet::DevError,
|
||||
"Unable to support multiple interfaces [#{providers.map(&:name).join(',')}] in a single file #{filename}"
|
||||
end
|
||||
|
||||
provider = providers[0]
|
||||
props = {}
|
||||
|
||||
props = provider.options if provider.options && provider.options != :absent
|
||||
|
||||
# Map everything to a flat hash
|
||||
NAME_MAPPINGS.keys.each do |type_name|
|
||||
if (val = provider.send(type_name)) && val != :absent
|
||||
props[type_name] = val
|
||||
end
|
||||
end
|
||||
|
||||
# :mode does not exist in NAME_MAPPINGS so we have to fetch it manually
|
||||
# note that the inverse operation is in .munge instead of parse_file
|
||||
val = provider.send(:mode)
|
||||
props['VLAN'] = 'yes' if val == :vlan
|
||||
|
||||
pairs = unmunge props
|
||||
|
||||
pairs.each_with_object('') do |(key, value), str|
|
||||
str << %(#{key}=#{value}\n)
|
||||
end
|
||||
end
|
||||
|
||||
def self.unmunge(props)
|
||||
pairs = {}
|
||||
|
||||
%i[onboot hotplug].each do |bool_property|
|
||||
unless props[bool_property].nil?
|
||||
props[bool_property] = (props[bool_property] == true ? 'yes' : 'no')
|
||||
end
|
||||
end
|
||||
|
||||
NAME_MAPPINGS.each_pair do |type_name, redhat_name|
|
||||
if (val = props[type_name])
|
||||
props.delete(type_name)
|
||||
pairs[redhat_name] = val
|
||||
end
|
||||
end
|
||||
|
||||
pairs.merge! props
|
||||
|
||||
pairs.each_pair do |key, val|
|
||||
pairs[key] = %("#{val}") if val.is_a?(String) && val.match(%r{\s+})
|
||||
end
|
||||
|
||||
pairs
|
||||
end
|
||||
|
||||
def self.post_flush_hook(filename)
|
||||
File.chmod(0o644, filename)
|
||||
end
|
||||
end
|
||||
|
||||
Vendored
+233
@@ -1,2 +1,235 @@
|
||||
require 'puppetx/filemapper'
|
||||
|
||||
Puppet::Type.type(:network_config).provide(:sles) do
|
||||
# SLES network_config network scripts provider.
|
||||
#
|
||||
# This provider manages the contents of /etc/networks/ifcfg-* to
|
||||
# manage non-volatile network configuration.
|
||||
#
|
||||
# @see https://documentation.suse.com/sles/15-SP1/html/SLES-all/cha-network.html#sec-network-manconf-files-ifcfg
|
||||
|
||||
include PuppetX::FileMapper
|
||||
|
||||
desc 'SLES network-scripts provider'
|
||||
|
||||
confine osfamily: :suse
|
||||
defaultfor osfamily: :suse
|
||||
|
||||
has_feature :startmode
|
||||
has_feature :provider_options
|
||||
|
||||
# @return [String] The path to network-script directory on sles systems
|
||||
SLES_SCRIPT_DIRECTORY = '/etc/sysconfig/network'.freeze # rubocop:disable Lint/ConstantDefinitionInBlock
|
||||
|
||||
# The valid vlan ID range is 0-4095; 4096 is out of range
|
||||
SLES_VLAN_RANGE_REGEX = %r{[1-3]?\d{1,3}|40[0-8]\d|409[0-5]}.freeze # rubocop:disable Lint/ConstantDefinitionInBlock
|
||||
|
||||
# aliases are almost free game, sles rejects some, and max total length is 15 characters
|
||||
# 15 minus at least 2 for the interface name, and a colon leaves 12 characters for the alias
|
||||
SLES_ALIAS_REGEX = %r{.{1,12}(?<!~|\.bak|\.old|\.orig|\.rpmnew|\.rpmorig|\.rpmsave|\.scpmbackup)}.freeze # rubocop:disable Lint/ConstantDefinitionInBlock
|
||||
|
||||
# @return [Regexp] The regular expression for interface scripts on sles systems
|
||||
SLES_SCRIPT_REGEX = %r{\Aifcfg-[a-z]+[a-z\d]+(?::#{SLES_ALIAS_REGEX}|\.#{SLES_VLAN_RANGE_REGEX})?\Z}.freeze # rubocop:disable Lint/ConstantDefinitionInBlock
|
||||
|
||||
# rubocop:disable Lint/ConstantDefinitionInBlock
|
||||
SLES_NAME_MAPPINGS = {
|
||||
ipaddress: 'IPADDR',
|
||||
netmask: 'NETMASK',
|
||||
method: 'BOOTPROTO',
|
||||
mtu: 'MTU',
|
||||
startmode: 'STARTMODE',
|
||||
}.freeze
|
||||
# rubocop:enable Lint/ConstantDefinitionInBlock
|
||||
|
||||
# Map provider instances to files based on their name
|
||||
#
|
||||
# @return [String] The path of the file for the given interface resource
|
||||
#
|
||||
# @example
|
||||
# prov = SLESProvider.new(:name => 'eth1')
|
||||
# prov.select_file # => '/etc/sysconfig/network/ifcfg-eth1'
|
||||
#
|
||||
def select_file
|
||||
"#{SLES_SCRIPT_DIRECTORY}/ifcfg-#{name}"
|
||||
end
|
||||
|
||||
# Scan all files in the networking directory for interfaces
|
||||
#
|
||||
# @param script_dir [String] The path to the networking scripts, defaults to
|
||||
# {#SLES_SCRIPT_DIRECTORY}
|
||||
#
|
||||
# @return [Array<String>] All network-script config files on this machine.
|
||||
#
|
||||
# @example
|
||||
# SLESProvider.target_files
|
||||
# # => ['/etc/sysconfig/network/ifcfg-eth0', '/etc/sysconfig/network/ifcfg-eth1']
|
||||
def self.target_files(script_dir = SLES_SCRIPT_DIRECTORY)
|
||||
entries = Dir.entries(script_dir).select { |entry| entry.match SCRIPT_REGEX }
|
||||
entries.map { |entry| File.join(SLES_SCRIPT_DIRECTORY, entry) }
|
||||
end
|
||||
|
||||
# Convert a SLES network script into a hash
|
||||
#
|
||||
# This is a hook method that will be called by PuppetX::Filemapper
|
||||
#
|
||||
# @param [String] filename The path of the interfaces file being parsed
|
||||
# @param [String] contents The contents of the given file
|
||||
#
|
||||
# @return [Array<Hash<Symbol, String>>] A single element array containing
|
||||
# the key/value pairs of properties parsed from the file.
|
||||
#
|
||||
# @example
|
||||
# SLESProvider.parse_file('/etc/sysconfig/network/ifcfg-eth0', #<String:0xdeadbeef>)
|
||||
# # => [
|
||||
# # {
|
||||
# # :name => 'eth0',
|
||||
# # :ipaddress => '169.254.0.1',
|
||||
# # :netmask => '255.255.0.0',
|
||||
# # },
|
||||
# # ]
|
||||
def self.parse_file(filename, contents)
|
||||
# Split up the file into lines
|
||||
lines = contents.split("\n")
|
||||
# Strip out all comments
|
||||
lines.map! { |line| line.sub(%r{#.*$}, '') }
|
||||
# Remove all blank lines
|
||||
lines.reject! { |line| line =~ %r{^\s*$} }
|
||||
|
||||
pair_regex = %r{^\s*(.+?)\s*=\s*(.*)\s*$}
|
||||
|
||||
# INFO: It is valid ifcfg format to include certain functions and strings these should not be reported as errors, but silently removed before parsing
|
||||
# https://bugs.centos.org/bug_view_page.php?bug_id=475
|
||||
# Remove lines with no = sign
|
||||
lines.select! { |line| line =~ %r{^.*=.*$} }
|
||||
|
||||
# Convert the data into key/value pairs
|
||||
pairs = lines.each_with_object({}) do |line, hash|
|
||||
raise Puppet::Error, %(#{filename} is malformed; "#{line}" did not match "#{pair_regex}") unless line.match(pair_regex) do |m|
|
||||
key = m[1].strip
|
||||
val = m[2].strip
|
||||
hash[key] = val
|
||||
end
|
||||
|
||||
hash
|
||||
end
|
||||
|
||||
props = munge(pairs)
|
||||
|
||||
# TODO: remove duct tape for #13
|
||||
#
|
||||
# The :family property is making less and less sense because it seems that
|
||||
# ipv6 configuration should add new properties instead of trying to collide
|
||||
# with the ipv4 addresses. But right now, the :inet property is never used
|
||||
# and it's creating a change on each resource update. This is a patch until
|
||||
# the :family property is ripped out.
|
||||
#
|
||||
# See https://github.com/adrienthebo/puppet-network/issues/13 for the full
|
||||
# issue that caused this, and https://github.com/adrienthebo/puppet-network/issues/16
|
||||
# for the resolution.
|
||||
#
|
||||
props[:family] = :inet
|
||||
|
||||
# If there is no DEVICE property in the interface configuration we retrieve
|
||||
# the interface name from the file name itself
|
||||
props[:name] = filename.split('ifcfg-')[1] unless props.key?(:name)
|
||||
|
||||
# Set the field to the default to prevent changes to the resource
|
||||
props[:onboot] = true
|
||||
|
||||
# The FileMapper mixin expects an array of providers, so we return the
|
||||
# single interface wrapped in an array
|
||||
[props]
|
||||
end
|
||||
|
||||
# @api private
|
||||
def self.munge(pairs)
|
||||
props = {}
|
||||
|
||||
# Unquote all values
|
||||
pairs.each_pair do |key, val|
|
||||
if (munged = val.gsub(%r{['"]}, ''))
|
||||
pairs[key] = munged
|
||||
end
|
||||
end
|
||||
|
||||
# For each interface attribute that we recognize it, add the value to the
|
||||
# hash with our expected label
|
||||
SLES_NAME_MAPPINGS.each_pair do |type_name, sles_name|
|
||||
next unless (val = pairs[sles_name])
|
||||
|
||||
pairs.delete(sles_name)
|
||||
props[type_name] = val
|
||||
end
|
||||
|
||||
# if we encounter VLAN_ID parameter, set the interface mode to :vlan
|
||||
pairs.each_pair do |key, _val|
|
||||
props[:mode] = :vlan if key == 'VLAN_ID'
|
||||
end
|
||||
pairs.delete('VLAN_ID')
|
||||
|
||||
# mode is a property so it should always have a value
|
||||
props[:mode] ||= :raw
|
||||
|
||||
# For all of the remaining values, blindly toss them into the options hash.
|
||||
props[:options] = pairs
|
||||
|
||||
props[:method] = 'static' unless %w[none bootp dhcp].include? props[:method]
|
||||
|
||||
props
|
||||
end
|
||||
|
||||
def self.format_file(filename, providers)
|
||||
return '' if providers.empty?
|
||||
|
||||
if providers.length > 1
|
||||
raise Puppet::DevError,
|
||||
"Unable to support multiple interfaces [#{providers.map(&:name).join(',')}] in a single file #{filename}"
|
||||
end
|
||||
|
||||
provider = providers[0]
|
||||
props = {}
|
||||
|
||||
props = provider.options if provider.options && provider.options != :absent
|
||||
|
||||
# Map everything to a flat hash
|
||||
SLES_NAME_MAPPINGS.each_key do |type_name|
|
||||
if (val = provider.send(type_name)) && val != :absent
|
||||
props[type_name] = val
|
||||
end
|
||||
end
|
||||
|
||||
# :mode does not exist in SLES_NAME_MAPPINGS so we have to fetch it manually
|
||||
# note that the inverse operation is in .munge instead of parse_file
|
||||
val = provider.send(:mode)
|
||||
props['VLAN_ID'] = provider.options['VLAN_ID'] if val == :vlan
|
||||
|
||||
pairs = unmunge props
|
||||
|
||||
pairs.each_with_object('') do |(key, value), str|
|
||||
str << %(#{key}=#{value}\n)
|
||||
end
|
||||
end
|
||||
|
||||
def self.unmunge(props)
|
||||
pairs = {}
|
||||
|
||||
SLES_NAME_MAPPINGS.each_pair do |type_name, sles_name|
|
||||
if (val = props[type_name])
|
||||
props.delete(type_name)
|
||||
pairs[sles_name] = val
|
||||
end
|
||||
end
|
||||
|
||||
pairs.merge! props
|
||||
|
||||
pairs.each_pair do |key, val|
|
||||
pairs[key] = %("#{val}") if val.is_a?(String) && val.match(%r{\s+})
|
||||
end
|
||||
|
||||
pairs
|
||||
end
|
||||
|
||||
def self.post_flush_hook(filename)
|
||||
File.chmod(0o644, filename)
|
||||
end
|
||||
end
|
||||
|
||||
Vendored
+117
@@ -0,0 +1,117 @@
|
||||
require 'ipaddr'
|
||||
require 'puppetx/filemapper'
|
||||
|
||||
Puppet::Type.type(:network_route).provide(:redhat) do
|
||||
# RHEL network_route routes provider.
|
||||
#
|
||||
# This provider uses the filemapper mixin to map the routes file to a
|
||||
# collection of network_route providers, and back.
|
||||
#
|
||||
# @see https://access.redhat.com/knowledge/docs/en-US/Red_Hat_Enterprise_Linux/6/html/Deployment_Guide/s1-networkscripts-static-routes.html
|
||||
|
||||
include PuppetX::FileMapper
|
||||
|
||||
desc 'RHEL style routes provider'
|
||||
|
||||
confine osfamily: :redhat
|
||||
defaultfor osfamily: :redhat
|
||||
|
||||
has_feature :provider_options
|
||||
|
||||
def select_file
|
||||
"/etc/sysconfig/network-scripts/route-#{interface}"
|
||||
end
|
||||
|
||||
def self.target_files(script_dir = '/etc/sysconfig/network-scripts')
|
||||
entries = Dir.entries(script_dir).select { |entry| entry.match %r{route-.*} }
|
||||
entries.map { |entry| File.join(script_dir, entry) }
|
||||
end
|
||||
|
||||
def self.parse_file(_filename, contents)
|
||||
routes = []
|
||||
lines = contents.split("\n")
|
||||
lines.each do |line|
|
||||
# Strip off any trailing comments
|
||||
line.sub!(%r{#.*$}, '')
|
||||
|
||||
if line =~ %r{^\s*#|^\s*$}
|
||||
# Ignore comments and blank lines
|
||||
next
|
||||
end
|
||||
|
||||
route = line.split(' ', 6)
|
||||
raise Puppet::Error, 'Malformed redhat route file, cannot instantiate network_route resources' if route.length < 4
|
||||
|
||||
route = line.split(' ', 5) if route[0] == 'local'
|
||||
|
||||
new_route = {}
|
||||
|
||||
if route[0] == 'local'
|
||||
new_route[:interface] = route[3]
|
||||
new_route[:options] = route[4] if route[4]
|
||||
else
|
||||
new_route[:gateway] = route[2]
|
||||
new_route[:interface] = route[4]
|
||||
new_route[:options] = route[5] if route[5]
|
||||
end
|
||||
|
||||
if route[0] == 'local'
|
||||
new_route[:name] = route[1]
|
||||
new_route[:network] = 'local'
|
||||
elsif ['default', '0.0.0.0'].include? route[0]
|
||||
new_route[:name] = 'default' # FIXME: Must match :name in order for changes to be detected
|
||||
new_route[:network] = 'default'
|
||||
new_route[:netmask] = '0.0.0.0'
|
||||
else
|
||||
ip = IPAddr.new(route[0])
|
||||
netmask_addr = ip.prefix <= 32 ? '255.255.255.255' : 'ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff'
|
||||
netmask = IPAddr.new("#{netmask_addr}/#{ip.prefix}")
|
||||
new_route[:name] = "#{ip}/#{ip.prefix}" # FIXME: Must match :name in order for changes to be detected
|
||||
new_route[:network] = ip.to_s
|
||||
new_route[:netmask] = netmask.to_s
|
||||
end
|
||||
routes << new_route
|
||||
end
|
||||
|
||||
routes
|
||||
end
|
||||
|
||||
# Generate an array of sections
|
||||
def self.format_file(_filename, providers)
|
||||
contents = []
|
||||
contents << header
|
||||
# Build routes
|
||||
providers.sort_by(&:name).each do |provider|
|
||||
%w[network interface].each do |prop|
|
||||
raise Puppet::Error, "#{provider.name} is missing the required parameter '#{prop}'." if provider.send(prop).nil?
|
||||
end
|
||||
%w[netmask gateway].each do |prop|
|
||||
raise Puppet::Error, "#{provider.name} is missing the required parameter '#{prop}'." if provider.send(prop).nil? && provider.send('network').to_s != 'local'
|
||||
end
|
||||
contents << if provider.network == 'default'
|
||||
"#{provider.network} via #{provider.gateway} dev #{provider.interface}"
|
||||
elsif provider.network == 'local'
|
||||
"#{provider.network} #{provider.name} dev #{provider.interface}"
|
||||
else
|
||||
ip = IPAddr.new("#{provider.network}/#{provider.netmask}")
|
||||
"#{ip}/#{ip.prefix} via #{provider.gateway} dev #{provider.interface}"
|
||||
end
|
||||
contents << (provider.options == :absent ? "\n" : " #{provider.options}\n")
|
||||
end
|
||||
contents.join
|
||||
end
|
||||
|
||||
def self.header
|
||||
<<~HEADER
|
||||
# HEADER: This file is being managed by puppet. Changes to
|
||||
# HEADER: routes that are not being managed by puppet will persist;
|
||||
# HEADER: however changes to routes that are being managed by puppet will
|
||||
# HEADER: be overwritten. In addition, file order is NOT guaranteed.
|
||||
# HEADER: Last generated at: #{Time.now}
|
||||
HEADER
|
||||
end
|
||||
|
||||
def self.post_flush_hook(filename)
|
||||
File.chmod(0o644, filename)
|
||||
end
|
||||
end
|
||||
Vendored
+117
@@ -0,0 +1,117 @@
|
||||
require 'ipaddr'
|
||||
require 'puppetx/filemapper'
|
||||
|
||||
Puppet::Type.type(:network_route).provide(:routes) do
|
||||
# Debian network_route routes provider.
|
||||
#
|
||||
# This provider uses the filemapper mixin to map the routes file to a
|
||||
# collection of network_route providers, and back.
|
||||
#
|
||||
# @see http://wiki.debian.org/NetworkConfiguration
|
||||
# @see http://packages.debian.org/squeeze/ifupdown-extras
|
||||
|
||||
include PuppetX::FileMapper
|
||||
|
||||
desc 'Debian routes style provider'
|
||||
|
||||
confine osfamily: :debian
|
||||
|
||||
# $ dpkg -S /etc/network/if-up.d/20static-routes
|
||||
# ifupdown-extra: /etc/network/if-up.d/20static-routes
|
||||
confine exists: '/etc/network/if-up.d/20static-routes'
|
||||
|
||||
defaultfor osfamily: :debian
|
||||
|
||||
has_feature :provider_options
|
||||
|
||||
def select_file
|
||||
'/etc/network/routes'
|
||||
end
|
||||
|
||||
def self.target_files
|
||||
['/etc/network/routes']
|
||||
end
|
||||
|
||||
class MalformedRoutesError < Puppet::Error
|
||||
def initialize(msg = nil)
|
||||
msg = 'Malformed debian routes file; cannot instantiate network_route resources' if msg.nil?
|
||||
super
|
||||
end
|
||||
end
|
||||
|
||||
def self.raise_malformed
|
||||
@failed = true
|
||||
raise MalformedRoutesError
|
||||
end
|
||||
|
||||
def self.parse_file(_filename, contents)
|
||||
# Build out an empty hash for new routes for storing their configs.
|
||||
route_hash = Hash.new do |hash, key|
|
||||
hash[key] = {}
|
||||
hash[key][:name] = key
|
||||
hash[key]
|
||||
end
|
||||
|
||||
lines = contents.split("\n")
|
||||
lines.each do |line|
|
||||
# Strip off any trailing comments
|
||||
line.sub!(%r{#.*$}, '')
|
||||
|
||||
if line =~ %r{^\s*#|^\s*$}
|
||||
# Ignore comments and blank lines
|
||||
next
|
||||
end
|
||||
|
||||
route = line.split(' ', 5)
|
||||
|
||||
raise_malformed if route.length < 4
|
||||
|
||||
if route[0] == 'default'
|
||||
name = 'default'
|
||||
route_hash[name][:network] = 'default'
|
||||
route_hash[name][:netmask] = '0.0.0.0'
|
||||
else
|
||||
# use the CIDR version of the target as :name
|
||||
name = "#{route[0]}/#{IPAddr.new(route[1]).to_i.to_s(2).count('1')}"
|
||||
route_hash[name][:network] = route[0]
|
||||
route_hash[name][:netmask] = route[1]
|
||||
end
|
||||
route_hash[name][:gateway] = route[2]
|
||||
route_hash[name][:interface] = route[3]
|
||||
route_hash[name][:options] = route[4] if route[4]
|
||||
end
|
||||
|
||||
route_hash.values
|
||||
end
|
||||
|
||||
# Generate an array of sections
|
||||
def self.format_file(_filename, providers)
|
||||
contents = []
|
||||
contents << header
|
||||
|
||||
# Build routes
|
||||
providers.sort_by(&:name).each do |provider|
|
||||
raise Puppet::Error, "#{provider.name} is missing the required parameter 'network'." if provider.network.nil?
|
||||
raise Puppet::Error, "#{provider.name} is missing the required parameter 'netmask'." if provider.netmask.nil?
|
||||
raise Puppet::Error, "#{provider.name} is missing the required parameter 'gateway'." if provider.gateway.nil?
|
||||
raise Puppet::Error, "#{provider.name} is missing the required parameter 'interface'." if provider.interface.nil?
|
||||
|
||||
netmask = (provider.name == 'default' ? '0.0.0.0' : provider.netmask)
|
||||
|
||||
contents << "#{provider.network} #{netmask} #{provider.gateway} #{provider.interface}"
|
||||
contents << (provider.options == :absent ? "\n" : " #{provider.options}\n")
|
||||
end
|
||||
|
||||
contents.join
|
||||
end
|
||||
|
||||
def self.header
|
||||
<<~HEADER
|
||||
# HEADER: This file is being managed by puppet. Changes to
|
||||
# HEADER: routes that are not being managed by puppet will persist;
|
||||
# HEADER: however changes to routes that are being managed by puppet will
|
||||
# HEADER: be overwritten. In addition, file order is NOT guaranteed.
|
||||
# HEADER: Last generated at: #{Time.now}
|
||||
HEADER
|
||||
end
|
||||
end
|
||||
Vendored
+102
@@ -0,0 +1,102 @@
|
||||
require 'ipaddr'
|
||||
require 'puppetx/filemapper'
|
||||
|
||||
Puppet::Type.type(:network_route).provide(:sles) do
|
||||
# SLES network_route routes provider.
|
||||
#
|
||||
# This provider uses the filemapper mixin to map the routes file to a
|
||||
# collection of network_route providers, and back.
|
||||
#
|
||||
# @see https://documentation.suse.com/sles/15-SP4/html/SLES-all/cha-network.html#sec-network-manconf-files-routes
|
||||
|
||||
include PuppetX::FileMapper
|
||||
|
||||
desc 'SLES style routes provider'
|
||||
|
||||
confine osfamily: :suse
|
||||
defaultfor osfamily: :suse
|
||||
|
||||
has_feature :provider_options
|
||||
|
||||
def select_file
|
||||
"/etc/sysconfig/network/ifroute-#{interface}"
|
||||
end
|
||||
|
||||
def self.target_files(script_dir = '/etc/sysconfig/network')
|
||||
entries = Dir.entries(script_dir).select { |entry| entry.match %r{ifroute-.*} }
|
||||
entries.map { |entry| File.join(script_dir, entry) }
|
||||
end
|
||||
|
||||
def self.parse_file(_filename, contents)
|
||||
routes = []
|
||||
lines = contents.split("\n")
|
||||
lines.each do |line|
|
||||
# Strip off any trailing comments
|
||||
line.sub!(%r{#.*$}, '')
|
||||
|
||||
if line =~ %r{^\s*#|^\s*$}
|
||||
# Ignore comments and blank lines
|
||||
next
|
||||
end
|
||||
|
||||
route = line.split(' ', 5)
|
||||
raise Puppet::Error, 'Malformed SLES route file, cannot instantiate network_route resources' if route.length < 4
|
||||
|
||||
new_route = {}
|
||||
|
||||
new_route[:gateway] = route[1]
|
||||
new_route[:interface] = route[3]
|
||||
new_route[:options] = route[4] if route[4]
|
||||
|
||||
if ['default', '0.0.0.0'].include? route[0]
|
||||
new_route[:name] = 'default' # FIXME: Must match :name in order for changes to be detected
|
||||
new_route[:network] = 'default'
|
||||
new_route[:netmask] = '0.0.0.0'
|
||||
else
|
||||
ip = IPAddr.new(route[0])
|
||||
netmask_addr = ip.prefix <= 32 ? '255.255.255.255' : 'ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff'
|
||||
netmask = IPAddr.new("#{netmask_addr}/#{ip.prefix}")
|
||||
new_route[:name] = "#{ip}/#{ip.prefix}" # FIXME: Must match :name in order for changes to be detected
|
||||
new_route[:network] = ip.to_s
|
||||
new_route[:netmask] = netmask.to_s
|
||||
end
|
||||
routes << new_route
|
||||
end
|
||||
|
||||
routes
|
||||
end
|
||||
|
||||
# Generate an array of sections
|
||||
def self.format_file(_filename, providers)
|
||||
contents = []
|
||||
contents << header
|
||||
# Build routes
|
||||
providers.sort_by(&:name).each do |provider|
|
||||
%w[network netmask gateway interface].each do |prop|
|
||||
raise Puppet::Error, "#{provider.name} is missing the required parameter '#{prop}'." if provider.send(prop).nil?
|
||||
end
|
||||
contents << if provider.network == 'default'
|
||||
"#{provider.network} #{provider.gateway} - #{provider.interface}"
|
||||
else
|
||||
ip = IPAddr.new("#{provider.network}/#{provider.netmask}")
|
||||
"#{ip}/#{ip.prefix} #{provider.gateway} - #{provider.interface}"
|
||||
end
|
||||
contents << (provider.options == :absent ? "\n" : " #{provider.options}\n")
|
||||
end
|
||||
contents.join
|
||||
end
|
||||
|
||||
def self.header
|
||||
<<~HEADER
|
||||
# HEADER: This file is being managed by puppet. Changes to
|
||||
# HEADER: routes that are not being managed by puppet will persist;
|
||||
# HEADER: however changes to routes that are being managed by puppet will
|
||||
# HEADER: be overwritten. In addition, file order is NOT guaranteed.
|
||||
# HEADER: Last generated at: #{Time.now}
|
||||
HEADER
|
||||
end
|
||||
|
||||
def self.post_flush_hook(filename)
|
||||
File.chmod(0o644, filename)
|
||||
end
|
||||
end
|
||||
+85
@@ -0,0 +1,85 @@
|
||||
require 'ipaddr'
|
||||
require_relative '../../puppet_x/voxpupuli/utils'
|
||||
|
||||
Puppet::Type.newtype(:network_route) do
|
||||
@doc = 'Manage non-volatile route configuration information'
|
||||
|
||||
feature :provider_options, <<-EOD
|
||||
The provider can accept a hash of arbitrary options. The semantics of
|
||||
these options will depend on the provider.
|
||||
EOD
|
||||
|
||||
include PuppetX::Voxpupuli::Utils
|
||||
|
||||
ensurable
|
||||
|
||||
newparam(:name) do
|
||||
isnamevar
|
||||
desc 'The name of the network route'
|
||||
end
|
||||
|
||||
newproperty(:network) do
|
||||
isrequired
|
||||
desc 'The target network address'
|
||||
validate do |value|
|
||||
unless %w[default local].include?(value)
|
||||
a = PuppetX::Voxpupuli::Utils.try { IPAddr.new(value) }
|
||||
raise("Invalid value for parameter 'network': #{value}") unless a
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
newproperty(:netmask) do
|
||||
desc 'The subnet mask to apply to the route'
|
||||
|
||||
validate do |value|
|
||||
raise("Invalid value for parameter 'netmask': #{value}") unless value.length <= 3 || PuppetX::Voxpupuli::Utils.try { IPAddr.new(value) }
|
||||
end
|
||||
|
||||
munge do |value|
|
||||
# '255.255.255.255'.to_i will return 255, so we try to convert it back:
|
||||
if value.to_i.to_s == value
|
||||
# what are the chances someone is using /16 for their IPv6 network?
|
||||
addr = value.to_i <= 32 ? '255.255.255.255' : 'ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff'
|
||||
IPAddr.new(addr).mask(value.strip.to_i).to_s
|
||||
elsif PuppetX::Voxpupuli::Utils.try { IPAddr.new(value).ipv6? }
|
||||
IPAddr.new('ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff').mask(value).to_s
|
||||
elsif PuppetX::Voxpupuli::Utils.try { IPAddr.new(value).ipv4? }
|
||||
IPAddr.new('255.255.255.255').mask(value).to_s
|
||||
else
|
||||
raise("Invalid value for parameter 'netmask': #{value}")
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
newproperty(:gateway) do
|
||||
desc 'The gateway to use for the route'
|
||||
|
||||
validate do |value|
|
||||
IPAddr.new(value)
|
||||
rescue ArgumentError
|
||||
raise("Invalid value for parameter 'gateway': #{value}")
|
||||
end
|
||||
end
|
||||
|
||||
newproperty(:interface) do
|
||||
isrequired
|
||||
desc 'The interface to use for the route'
|
||||
end
|
||||
|
||||
# `:options` provides an arbitrary passthrough for provider properties, so
|
||||
# that provider specific behavior doesn't clutter up the main type but still
|
||||
# allows for more powerful actions to be taken.
|
||||
newproperty(:options, required_features: :provider_options) do
|
||||
desc 'Provider specific options to be passed to the provider'
|
||||
|
||||
validate do |value|
|
||||
raise ArgumentError, "#{self.class} requires a string for the options property" unless value.is_a?(String)
|
||||
end
|
||||
end
|
||||
|
||||
validate do
|
||||
raise "Network_route[#{self[:name]}] must have netmask defined" if self[:network] != 'local' && self[:netmask].nil?
|
||||
raise "Network_route[#{self[:name]}] must have gateway defined" if self[:network] != 'local' && self[:gateway].nil?
|
||||
end
|
||||
end
|
||||
+11
@@ -0,0 +1,11 @@
|
||||
module PuppetX
|
||||
module Voxpupuli
|
||||
module Utils
|
||||
def self.try(catch = ArgumentError, nope = false)
|
||||
yield
|
||||
rescue catch
|
||||
nope
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
+13
-4
@@ -1,4 +1,4 @@
|
||||
# This file was automatically generated on 2026-11-08 18:46:53 +1100.
|
||||
# This file was automatically generated on 2026-11-09 00:40:30 +1100.
|
||||
# Use the 'puppet generate types' command to regenerate this file.
|
||||
|
||||
# Manage non-volatile network configuration information
|
||||
@@ -74,13 +74,22 @@ Puppet::Resource::ResourceType3.new(
|
||||
# discover the appropriate provider for your platform.Available providers are:
|
||||
#
|
||||
# interfaces
|
||||
# :
|
||||
# : Debian interfaces style provider
|
||||
#
|
||||
# * Default for `osfamily` == `debian`.
|
||||
# * Supported features: `hotpluggable`, `provider_options`.
|
||||
#
|
||||
# redhat
|
||||
# :
|
||||
# : Redhat network-scripts provider
|
||||
#
|
||||
# * Default for `osfamily` == `redhat`.
|
||||
# * Supported features: `hotpluggable`, `provider_options`.
|
||||
#
|
||||
# sles
|
||||
# :
|
||||
# : SLES network-scripts provider
|
||||
#
|
||||
# * Default for `osfamily` == `suse`.
|
||||
# * Supported features: `provider_options`, `startmode`.
|
||||
Puppet::Resource::Param(Any, 'provider')
|
||||
],
|
||||
{
|
||||
|
||||
@@ -0,0 +1,63 @@
|
||||
# This file was automatically generated on 2026-11-09 00:40:30 +1100.
|
||||
# Use the 'puppet generate types' command to regenerate this file.
|
||||
|
||||
# Manage non-volatile route configuration information
|
||||
Puppet::Resource::ResourceType3.new(
|
||||
'network_route',
|
||||
[
|
||||
# The basic property that the resource should be in.
|
||||
#
|
||||
# Valid values are `present`, `absent`.
|
||||
Puppet::Resource::Param(Enum['present', 'absent'], 'ensure'),
|
||||
|
||||
# The target network address
|
||||
Puppet::Resource::Param(Any, 'network'),
|
||||
|
||||
# The subnet mask to apply to the route
|
||||
Puppet::Resource::Param(Any, 'netmask'),
|
||||
|
||||
# The gateway to use for the route
|
||||
Puppet::Resource::Param(Any, 'gateway'),
|
||||
|
||||
# The interface to use for the route
|
||||
Puppet::Resource::Param(Any, 'interface'),
|
||||
|
||||
# Provider specific options to be passed to the provider
|
||||
#
|
||||
#
|
||||
#
|
||||
# Requires features provider_options.
|
||||
Puppet::Resource::Param(Any, 'options')
|
||||
],
|
||||
[
|
||||
# The name of the network route
|
||||
Puppet::Resource::Param(Any, 'name', true),
|
||||
|
||||
# The specific backend to use for this `network_route`
|
||||
# resource. You will seldom need to specify this --- OpenVox will usually
|
||||
# discover the appropriate provider for your platform.Available providers are:
|
||||
#
|
||||
# redhat
|
||||
# : RHEL style routes provider
|
||||
#
|
||||
# * Default for `osfamily` == `redhat`.
|
||||
# * Supported features: `provider_options`.
|
||||
#
|
||||
# routes
|
||||
# : Debian routes style provider
|
||||
#
|
||||
# * Default for `osfamily` == `debian`.
|
||||
# * Supported features: `provider_options`.
|
||||
#
|
||||
# sles
|
||||
# : SLES style routes provider
|
||||
#
|
||||
# * Default for `osfamily` == `suse`.
|
||||
# * Supported features: `provider_options`.
|
||||
Puppet::Resource::Param(Any, 'provider')
|
||||
],
|
||||
{
|
||||
/(?m-ix:(.*))/ => ['name']
|
||||
},
|
||||
true,
|
||||
false)
|
||||
Reference in New Issue
Block a user