Generate Puppet resource types natively before the env swap #2
@@ -1,3 +1,4 @@
|
||||
exclude: ^internal/gentypes/testdata/
|
||||
repos:
|
||||
- repo: https://github.com/pre-commit/pre-commit-hooks
|
||||
rev: v4.6.0
|
||||
|
||||
@@ -15,8 +15,9 @@ type Config struct {
|
||||
Cachedir string `yaml:"cachedir"`
|
||||
Sources map[string]*Source `yaml:"sources"`
|
||||
W10k struct {
|
||||
GCGrace *time.Duration `yaml:"gc_grace"`
|
||||
GitTimeout *time.Duration `yaml:"git_timeout"`
|
||||
GCGrace *time.Duration `yaml:"gc_grace"`
|
||||
GitTimeout *time.Duration `yaml:"git_timeout"`
|
||||
GenerateTypes bool `yaml:"generate_types"`
|
||||
} `yaml:"w10k"`
|
||||
}
|
||||
|
||||
|
||||
@@ -107,3 +107,16 @@ func TestIgnored(t *testing.T) {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestParseConfigGenerateTypes(t *testing.T) {
|
||||
base := "cachedir: /c\nsources:\n a:\n remote: r\n basedir: /a\n"
|
||||
for cfg, want := range map[string]bool{base: false, base + "w10k:\n generate_types: true\n": true, base + ":w10k:\n :generate_types: true\n": true} {
|
||||
c, err := ParseConfig([]byte(cfg))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if c.W10k.GenerateTypes != want {
|
||||
t.Errorf("%q: generate_types = %v", cfg, c.W10k.GenerateTypes)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+47
-10
@@ -16,10 +16,13 @@ import (
|
||||
"runtime/debug"
|
||||
"slices"
|
||||
"sort"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
"syscall"
|
||||
"time"
|
||||
|
||||
"git.unkin.net/unkin/w10k/internal/gentypes"
|
||||
)
|
||||
|
||||
const (
|
||||
@@ -46,6 +49,7 @@ type Deployer struct {
|
||||
sem chan struct{}
|
||||
mu sync.Mutex
|
||||
flights map[string]*flight
|
||||
skips map[string]int
|
||||
wtLocks sync.Map
|
||||
}
|
||||
|
||||
@@ -81,7 +85,7 @@ func New(cfg *Config, jobs int, grace time.Duration) *Deployer {
|
||||
if cfg.W10k.GitTimeout != nil {
|
||||
gt = *cfg.W10k.GitTimeout
|
||||
}
|
||||
return &Deployer{runGit: runGit, cfg: cfg, grace: grace, gitTimeout: gt, now: time.Now, sem: make(chan struct{}, jobs), flights: map[string]*flight{}}
|
||||
return &Deployer{runGit: runGit, cfg: cfg, grace: grace, gitTimeout: gt, now: time.Now, sem: make(chan struct{}, jobs), flights: map[string]*flight{}, skips: map[string]int{}}
|
||||
}
|
||||
|
||||
func (d *Deployer) once(key string, fn func() (string, error)) (string, error) {
|
||||
@@ -206,6 +210,9 @@ func (d *Deployer) Deploy(ctx context.Context, only []string, modules bool) erro
|
||||
for _, e := range only {
|
||||
want[e] = true
|
||||
}
|
||||
d.mu.Lock()
|
||||
clear(d.skips)
|
||||
d.mu.Unlock()
|
||||
found := map[string]bool{}
|
||||
var errs []error
|
||||
for _, s := range d.Sources() {
|
||||
@@ -219,6 +226,11 @@ func (d *Deployer) Deploy(ctx context.Context, only []string, modules bool) erro
|
||||
}
|
||||
}
|
||||
errs = append(errs, d.gc(ctx, len(only) == 0))
|
||||
d.mu.Lock()
|
||||
for _, e := range slices.Sorted(maps.Keys(d.skips)) {
|
||||
log.Printf("environment %s: %d types skipped", e, d.skips[e])
|
||||
}
|
||||
d.mu.Unlock()
|
||||
return errors.Join(errs...)
|
||||
}
|
||||
|
||||
@@ -333,11 +345,20 @@ func (d *Deployer) owned(s *Source, link string) string {
|
||||
return ""
|
||||
}
|
||||
|
||||
// worktreePrefix keys worktrees on everything besides modules that changes their content.
|
||||
func (d *Deployer) worktreePrefix(sha string) string {
|
||||
if d.cfg.W10k.GenerateTypes {
|
||||
return sha + "-types" + gentypes.Version + "-"
|
||||
}
|
||||
return sha + "-"
|
||||
}
|
||||
|
||||
func (d *Deployer) deployEnv(ctx context.Context, s *Source, name string, ref envRef, modules bool) error {
|
||||
sha := ref.sha
|
||||
link := filepath.Join(s.Basedir, name)
|
||||
cur := d.owned(s, link)
|
||||
if cur != "" && !modules && strings.HasPrefix(filepath.Base(cur), sha+"-") && d.complete(cur) {
|
||||
prefix := d.worktreePrefix(sha)
|
||||
if base := filepath.Base(cur); cur != "" && !modules && strings.HasPrefix(base, prefix) && len(base) == len(prefix)+12 && d.complete(cur) {
|
||||
return nil
|
||||
}
|
||||
pf, checksum, err := d.puppetfile(ctx, d.srcMirror(s), sha)
|
||||
@@ -352,11 +373,11 @@ func (d *Deployer) deployEnv(ctx context.Context, s *Source, name string, ref en
|
||||
for _, m := range mods {
|
||||
_, _ = fmt.Fprintf(h, "%s %s\n", m.path, m.key)
|
||||
}
|
||||
target := filepath.Join(d.srcWorktrees(s), sha+"-"+hex.EncodeToString(h.Sum(nil))[:12])
|
||||
target := filepath.Join(d.srcWorktrees(s), prefix+hex.EncodeToString(h.Sum(nil))[:12])
|
||||
if cur == target && d.complete(cur) {
|
||||
return nil
|
||||
}
|
||||
if _, err := d.once("env:"+target, func() (string, error) {
|
||||
skipped, err := d.once("env:"+target, func() (string, error) {
|
||||
if d.complete(target) {
|
||||
return "", nil
|
||||
}
|
||||
@@ -364,13 +385,19 @@ func (d *Deployer) deployEnv(ctx context.Context, s *Source, name string, ref en
|
||||
if err := d.checkout(ctx, s, sha, target, mods); err != nil {
|
||||
return "", err
|
||||
}
|
||||
return "", d.prepare(s, ref, checksum, target, mods, started)
|
||||
}); err != nil {
|
||||
return d.prepare(s, name, ref, checksum, target, mods, started)
|
||||
})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if err := Swap(target, link); err != nil {
|
||||
return err
|
||||
}
|
||||
if n, _ := strconv.Atoi(skipped); n > 0 {
|
||||
d.mu.Lock()
|
||||
d.skips[name] = n
|
||||
d.mu.Unlock()
|
||||
}
|
||||
log.Printf("environment %s -> %s", name, filepath.Base(target))
|
||||
return nil
|
||||
}
|
||||
@@ -539,7 +566,17 @@ func linkModule(root *os.Root, rel, dir string) error {
|
||||
}
|
||||
|
||||
// prepare runs last before a worktree can be swapped in; its out-of-tree done file marks the worktree complete.
|
||||
func (d *Deployer) prepare(s *Source, ref envRef, checksum, target string, mods []resolved, started time.Time) error {
|
||||
func (d *Deployer) prepare(s *Source, name string, ref envRef, checksum, target string, mods []resolved, started time.Time) (string, error) {
|
||||
var skipped []error
|
||||
if d.cfg.W10k.GenerateTypes {
|
||||
var err error
|
||||
if skipped, err = gentypes.Generate(target, d.path("modules"), d.path("forge")); err != nil {
|
||||
return "", fmt.Errorf("generate types: %w", err)
|
||||
}
|
||||
for _, e := range skipped {
|
||||
log.Printf("error: environment %s: generate types: skipped %v", name, e)
|
||||
}
|
||||
}
|
||||
r := deployResult{
|
||||
Name: ref.branch,
|
||||
Signature: ref.sha,
|
||||
@@ -556,13 +593,13 @@ func (d *Deployer) prepare(s *Source, ref envRef, checksum, target string, mods
|
||||
}
|
||||
b, err := json.MarshalIndent(r, "", " ")
|
||||
if err != nil {
|
||||
return err
|
||||
return "", err
|
||||
}
|
||||
b = append(b, '\n')
|
||||
if err := writeMarker(target, b); err != nil {
|
||||
return err
|
||||
return "", err
|
||||
}
|
||||
return d.markDone(target, b)
|
||||
return strconv.Itoa(len(skipped)), d.markDone(target, b)
|
||||
}
|
||||
|
||||
// writeMarker replaces whatever the branch committed at the marker paths without following it.
|
||||
|
||||
@@ -1,9 +1,11 @@
|
||||
package deploy
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"log"
|
||||
"net"
|
||||
"net/http"
|
||||
"net/http/cgi"
|
||||
@@ -617,6 +619,102 @@ func TestJobsBoundGitProcesses(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestGenerateTypesBeforeSwap(t *testing.T) {
|
||||
f := newFixture(t)
|
||||
f.cfg.W10k.GenerateTypes = true
|
||||
typed := filepath.Join(f.root, "typed")
|
||||
newRepo(t, typed)
|
||||
commit(t, typed, map[string]string{
|
||||
"lib/puppet/type/typed.rb": "Puppet::Type.newtype(:typed) do\n newparam(:name, namevar: true)\nend\n",
|
||||
"lib/puppet/provider/typed/posix.rb": "Puppet::Type.type(:typed).provide(:posix) do\nend\n",
|
||||
})
|
||||
commit(t, f.control, map[string]string{
|
||||
"Puppetfile": fmt.Sprintf("moduledir 'external_modules'\nmod 'typed', :git => '%s'\n", f.url(typed)),
|
||||
"environment.conf": "modulepath = site:external_modules:$basemodulepath\n",
|
||||
"site/local/lib/puppet/type/local.rb": "Puppet::Type.newtype(:local) do\n ensurable\n newparam(:name)\nend\n",
|
||||
})
|
||||
f.mustDeploy(false)
|
||||
live := f.env("main")
|
||||
pp := readFileT(t, filepath.Join(f.basedir, "main", ".resource_types", "typed.pp"))
|
||||
if !strings.Contains(pp, "Puppet::Resource::Param(Any, 'provider')") || !exists(filepath.Join(live, ".resource_types", "local.pp")) {
|
||||
t.Fatalf("types not generated:\n%s", pp)
|
||||
}
|
||||
|
||||
commit(t, f.control, map[string]string{"site/local/lib/puppet/type/local.rb": "Puppet::Type.newtype(:local) do\n newparam(dynamic)\nend\n"})
|
||||
var logs bytes.Buffer
|
||||
log.SetOutput(&logs)
|
||||
defer log.SetOutput(os.Stderr)
|
||||
f.mustDeploy(false)
|
||||
skipped := f.env("main")
|
||||
if skipped == live || !exists(filepath.Join(skipped, ".resource_types", "typed.pp")) || exists(filepath.Join(skipped, ".resource_types", "local.pp")) {
|
||||
t.Fatal("an unparseable type is skipped while the env still deploys its other types")
|
||||
}
|
||||
for _, want := range []string{"environment main: generate types: skipped site/local/lib/puppet/type/local.rb: line 2:", "environment main: 1 types skipped"} {
|
||||
if !strings.Contains(logs.String(), want) {
|
||||
t.Fatalf("log lacks %q:\n%s", want, logs.String())
|
||||
}
|
||||
}
|
||||
live = skipped
|
||||
|
||||
commit(t, f.control, map[string]string{"site/local/lib/puppet/type/local.rb": "Puppet::Type.newtype(:local) do\n newparam(:name) do\n newvalues(" + strings.Repeat("[", 300) + strings.Repeat("]", 300) + ")\n end\nend\n"})
|
||||
if err := f.deploy(false); err == nil || !strings.Contains(err.Error(), "deeper than") || !strings.Contains(err.Error(), "site/local/lib/puppet/type/local.rb") {
|
||||
t.Fatalf("a parser limit must fail the deploy naming the file: %v", err)
|
||||
}
|
||||
if f.env("main") != live {
|
||||
t.Fatal("failed generation must leave the live env untouched")
|
||||
}
|
||||
|
||||
commit(t, f.control, map[string]string{"site/local/lib/puppet/type/local.rb": "Puppet::Type.newtype(:local) do\n newparam(:name)\nend\n"})
|
||||
if err := os.Symlink("/tmp", filepath.Join(f.control, ".resource_types")); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
gitT(t, f.control, "add", "-A")
|
||||
gitT(t, f.control, "commit", "-q", "-m", "link")
|
||||
if err := f.deploy(false); err == nil || !strings.Contains(err.Error(), "not a directory") {
|
||||
t.Fatalf("committed .resource_types symlink must fail: %v", err)
|
||||
}
|
||||
if f.env("main") != live {
|
||||
t.Fatal("failed generation must leave the live env untouched")
|
||||
}
|
||||
}
|
||||
|
||||
func TestGenerateTypesToggleRedeploys(t *testing.T) {
|
||||
f := newFixture(t)
|
||||
commit(t, f.control, map[string]string{
|
||||
"environment.conf": "modulepath = site:$basemodulepath\n",
|
||||
"site/local/lib/puppet/type/local.rb": "Puppet::Type.newtype(:local) do\n newparam(:name)\nend\n",
|
||||
})
|
||||
f.mustDeploy(false)
|
||||
plain := f.env("main")
|
||||
if exists(filepath.Join(plain, ".resource_types")) {
|
||||
t.Fatal("types generated while generate_types is off")
|
||||
}
|
||||
f.cfg.W10k.GenerateTypes = true
|
||||
f.mustDeploy(false)
|
||||
typed := f.env("main")
|
||||
if typed == plain || !exists(filepath.Join(typed, ".resource_types", "local.pp")) {
|
||||
t.Fatalf("enabling generate_types must deploy a new worktree with types: %s", typed)
|
||||
}
|
||||
f.mustDeploy(false)
|
||||
if f.env("main") != typed {
|
||||
t.Fatal("an unchanged typed env must not be redeployed")
|
||||
}
|
||||
f.cfg.W10k.GenerateTypes = false
|
||||
f.mustDeploy(false)
|
||||
if f.env("main") != plain {
|
||||
t.Fatalf("disabling generate_types must return to the untyped worktree, got %s", f.env("main"))
|
||||
}
|
||||
}
|
||||
|
||||
func readFileT(t *testing.T, p string) string {
|
||||
t.Helper()
|
||||
b, err := os.ReadFile(p)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return string(b)
|
||||
}
|
||||
|
||||
func TestCommittedMarkerTmpSymlinkWritesOutside(t *testing.T) {
|
||||
f := newFixture(t)
|
||||
commit(t, f.control, map[string]string{"manifests/site.pp": "node default {}\n"})
|
||||
|
||||
@@ -0,0 +1,37 @@
|
||||
package gentypes
|
||||
|
||||
import (
|
||||
"io/fs"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func FuzzParseFile(f *testing.F) {
|
||||
err := filepath.WalkDir("testdata/env", func(p string, d fs.DirEntry, err error) error {
|
||||
if err == nil && strings.HasSuffix(p, ".rb") {
|
||||
b, rerr := os.ReadFile(p)
|
||||
f.Add(string(b))
|
||||
return rerr
|
||||
}
|
||||
return err
|
||||
})
|
||||
if err != nil {
|
||||
f.Fatal(err)
|
||||
}
|
||||
mix := "module PuppetX\n module M\n def exists?; end\n end\nend\n"
|
||||
f.Fuzz(func(t *testing.T, src string) {
|
||||
types, err := parseFile(src, func(string, bool) ([]string, error) { return []string{mix, src}, nil })
|
||||
if err == nil {
|
||||
for _, ty := range types {
|
||||
_, _ = render(ty, []string{"a"}, time.Unix(0, 0))
|
||||
}
|
||||
}
|
||||
_, _, _ = providerOf(src, "t")
|
||||
_, _ = mixinMethods(src, "PuppetX::M")
|
||||
_, _ = inertLib(src)
|
||||
_, _ = parsePType(src)
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,395 @@
|
||||
// Package gentypes is a static port of `puppet generate types`.
|
||||
package gentypes
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io/fs"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"regexp"
|
||||
"slices"
|
||||
"sort"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
const OutDir = ".resource_types"
|
||||
|
||||
// Version changes whenever generated output can change, so deploys rebuild typed environments.
|
||||
const Version = "3"
|
||||
|
||||
var moduleName = regexp.MustCompile(`^[a-z][a-z0-9_]*$`)
|
||||
|
||||
var errConfine = errors.New("resolves outside the environment and module cache")
|
||||
|
||||
// skipErr marks an input skipped the way `puppet generate types` skips a type that fails to load.
|
||||
type skipErr struct{ error }
|
||||
|
||||
func (u skipErr) Unwrap() error { return u.error }
|
||||
|
||||
func unparsed(err error) error {
|
||||
var pe *fs.PathError
|
||||
if errors.Is(err, errLimit) || errors.Is(err, errConfine) || errors.As(err, &pe) {
|
||||
return err
|
||||
}
|
||||
return skipErr{err}
|
||||
}
|
||||
|
||||
type gen struct {
|
||||
env string
|
||||
roots []string
|
||||
}
|
||||
|
||||
// Generate writes <env>/.resource_types; every file it reads must resolve inside env or one of roots.
|
||||
// Inputs that fail to parse are returned as skipped and keep any previous output.
|
||||
func Generate(env string, roots ...string) (skipped []error, err error) {
|
||||
g := &gen{}
|
||||
for i, r := range append([]string{env}, roots...) {
|
||||
real, err := filepath.EvalSymlinks(r)
|
||||
if i > 0 && errors.Is(err, os.ErrNotExist) {
|
||||
continue
|
||||
}
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
g.roots = append(g.roots, real)
|
||||
}
|
||||
g.env = g.roots[0]
|
||||
mods, err := g.modules()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var inputs []string
|
||||
providers := map[string][]string{}
|
||||
for _, m := range mods {
|
||||
files, err := g.glob(filepath.Join(m, "lib", "puppet", "type"))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
inputs = append(inputs, files...)
|
||||
dirs, err := g.list(filepath.Join(m, "lib", "puppet", "provider"))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
for _, d := range dirs {
|
||||
files, err := g.glob(d)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
for _, f := range files {
|
||||
typ := filepath.Base(d)
|
||||
if !slices.ContainsFunc(providers[typ], func(o string) bool { return filepath.Base(o) == filepath.Base(f) }) {
|
||||
providers[typ] = append(providers[typ], f)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
sort.Strings(inputs)
|
||||
out, err := openOut(g.env)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer func() { _ = out.Close() }()
|
||||
keep := map[string]bool{}
|
||||
for _, in := range inputs {
|
||||
keep[strings.TrimSuffix(filepath.Base(in), ".rb")+".pp"] = true
|
||||
}
|
||||
dir, err := out.Open(".")
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
entries, err := dir.ReadDir(-1)
|
||||
_ = dir.Close()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
for _, e := range entries {
|
||||
if !keep[e.Name()] && (e.Type().IsRegular() || e.Type()&fs.ModeSymlink != 0) {
|
||||
if err := out.Remove(e.Name()); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
}
|
||||
var errs []error
|
||||
for _, in := range inputs {
|
||||
if err := generateOne(in, out, providers[strings.TrimSuffix(filepath.Base(in), ".rb")], g.libs(mods, in)); err != nil {
|
||||
err = fmt.Errorf("%s: %w", strings.TrimPrefix(in, g.env+"/"), err)
|
||||
if errors.As(err, new(skipErr)) {
|
||||
skipped = append(skipped, err)
|
||||
} else {
|
||||
errs = append(errs, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
return skipped, errors.Join(errs...)
|
||||
}
|
||||
|
||||
// openOut returns an os.Root on <env>/.resource_types, refusing anything but a real directory there.
|
||||
func openOut(env string) (*os.Root, error) {
|
||||
root, err := os.OpenRoot(env)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer func() { _ = root.Close() }()
|
||||
fi, err := root.Lstat(OutDir)
|
||||
switch {
|
||||
case errors.Is(err, os.ErrNotExist):
|
||||
if err := root.Mkdir(OutDir, 0o755); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
case err != nil:
|
||||
return nil, err
|
||||
case !fi.IsDir():
|
||||
return nil, fmt.Errorf("%s exists and is not a directory", filepath.Join(env, OutDir))
|
||||
}
|
||||
return root.OpenRoot(OutDir)
|
||||
}
|
||||
|
||||
// generateOne writes the type defined by in; providers are the first-found provider files the autoloader loads for it.
|
||||
func generateOne(in string, out *os.Root, providers []string, resolve Resolver) (err error) {
|
||||
defer func() {
|
||||
if r := recover(); r != nil {
|
||||
err = fmt.Errorf("panic: %v", r)
|
||||
}
|
||||
}()
|
||||
ifi, err := os.Stat(in)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
name := strings.TrimSuffix(filepath.Base(in), ".rb")
|
||||
dst := name + ".pp"
|
||||
if ofi, err := out.Lstat(dst); err == nil && ofi.Mode().IsRegular() && ofi.ModTime().Equal(ifi.ModTime()) {
|
||||
return nil
|
||||
}
|
||||
src, err := os.ReadFile(in)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
types, err := parseFile(string(src), resolve)
|
||||
if err != nil {
|
||||
return unparsed(err)
|
||||
}
|
||||
var t *rtype
|
||||
for _, c := range types {
|
||||
if c.name == name {
|
||||
t = c
|
||||
}
|
||||
}
|
||||
if t == nil {
|
||||
return skipErr{fmt.Errorf("custom type %q was not defined", name)}
|
||||
}
|
||||
names, err := providerNames(t, providers)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
body, err := render(t, names, time.Now())
|
||||
if err != nil {
|
||||
return unparsed(err)
|
||||
}
|
||||
tmp := "." + dst + ".tmp"
|
||||
if err := out.RemoveAll(tmp); err != nil {
|
||||
return err
|
||||
}
|
||||
f, err := out.OpenFile(tmp, os.O_CREATE|os.O_EXCL|os.O_WRONLY, 0o644)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer func() { _ = out.Remove(tmp) }()
|
||||
if _, err := f.WriteString(body); err != nil {
|
||||
_ = f.Close()
|
||||
return err
|
||||
}
|
||||
if err := f.Close(); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := out.Chtimes(tmp, ifi.ModTime(), ifi.ModTime()); err != nil {
|
||||
return err
|
||||
}
|
||||
return out.Rename(tmp, dst)
|
||||
}
|
||||
|
||||
// providerNames returns the providers puppet registers for t, or a skip when a provider file is not a recognised provide call.
|
||||
func providerNames(t *rtype, files []string) ([]string, error) {
|
||||
var names, parents []string
|
||||
for _, f := range files {
|
||||
src, err := os.ReadFile(f)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
name, parent, err := providerOf(string(src), t.name)
|
||||
switch {
|
||||
case err != nil:
|
||||
case t.rsapi && name != "":
|
||||
err = fmt.Errorf("provide on a Resource API type")
|
||||
case !t.rsapi && name == "":
|
||||
err = fmt.Errorf("no Puppet::Type.type(:%s).provide call", t.name)
|
||||
}
|
||||
if err != nil {
|
||||
return nil, unparsed(fmt.Errorf("provider %s: %w", filepath.Base(f), err))
|
||||
}
|
||||
if !slices.Contains(names, name) && name != "" {
|
||||
names = append(names, name)
|
||||
}
|
||||
if parent != "" {
|
||||
parents = append(parents, parent)
|
||||
}
|
||||
}
|
||||
for _, p := range parents {
|
||||
if !slices.Contains(names, p) {
|
||||
return nil, skipErr{fmt.Errorf("parent provider %s is not defined", p)}
|
||||
}
|
||||
}
|
||||
return names, nil
|
||||
}
|
||||
|
||||
// libs resolves a lib-relative path in every module as Ruby's require would search, or only in the module of in when local.
|
||||
func (g *gen) libs(mods []string, in string) Resolver {
|
||||
own := filepath.Dir(filepath.Dir(filepath.Dir(filepath.Dir(in))))
|
||||
return func(rel string, local bool) ([]string, error) {
|
||||
var srcs []string
|
||||
for _, m := range mods {
|
||||
if local && m != own {
|
||||
continue
|
||||
}
|
||||
p := filepath.Join(m, "lib", rel)
|
||||
if _, err := os.Lstat(p); errors.Is(err, os.ErrNotExist) {
|
||||
continue
|
||||
}
|
||||
real, err := g.confine(p)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
b, err := os.ReadFile(real)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
srcs = append(srcs, string(b))
|
||||
}
|
||||
return srcs, nil
|
||||
}
|
||||
}
|
||||
|
||||
func (g *gen) confine(p string) (string, error) {
|
||||
real, err := filepath.EvalSymlinks(p)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
for _, r := range g.roots {
|
||||
if real == r || strings.HasPrefix(real, r+string(filepath.Separator)) {
|
||||
return real, nil
|
||||
}
|
||||
}
|
||||
return "", fmt.Errorf("%s %w", p, errConfine)
|
||||
}
|
||||
|
||||
// list returns the confined subdirectories of dir, or nothing when dir is absent.
|
||||
func (g *gen) list(dir string) ([]string, error) {
|
||||
if _, err := os.Lstat(dir); errors.Is(err, os.ErrNotExist) {
|
||||
return nil, nil
|
||||
}
|
||||
real, err := g.confine(dir)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
entries, err := os.ReadDir(real)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var out []string
|
||||
for _, e := range entries {
|
||||
p, err := g.confine(filepath.Join(real, e.Name()))
|
||||
if errors.Is(err, os.ErrNotExist) {
|
||||
continue
|
||||
}
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if fi, err := os.Stat(p); err == nil && fi.IsDir() {
|
||||
out = append(out, filepath.Join(dir, e.Name()))
|
||||
}
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// glob returns the confined regular *.rb files directly inside dir.
|
||||
func (g *gen) glob(dir string) ([]string, error) {
|
||||
if _, err := os.Lstat(dir); errors.Is(err, os.ErrNotExist) {
|
||||
return nil, nil
|
||||
}
|
||||
real, err := g.confine(dir)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
entries, err := os.ReadDir(real)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var out []string
|
||||
for _, e := range entries {
|
||||
if !strings.HasSuffix(e.Name(), ".rb") {
|
||||
continue
|
||||
}
|
||||
p, err := g.confine(filepath.Join(real, e.Name()))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if fi, err := os.Stat(p); err == nil && fi.Mode().IsRegular() {
|
||||
out = append(out, filepath.Join(dir, e.Name()))
|
||||
}
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// modules resolves environment.conf's modulepath to module dirs, first name wins; $basemodulepath is skipped.
|
||||
func (g *gen) modules() ([]string, error) {
|
||||
modulepath := "modules:$basemodulepath"
|
||||
conf := filepath.Join(g.env, "environment.conf")
|
||||
if _, err := os.Lstat(conf); err == nil {
|
||||
real, err := g.confine(conf)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
f, err := os.Open(real)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
sc := bufio.NewScanner(f)
|
||||
for sc.Scan() {
|
||||
k, v, ok := strings.Cut(sc.Text(), "=")
|
||||
if ok && strings.TrimSpace(k) == "modulepath" {
|
||||
modulepath = strings.Trim(strings.TrimSpace(v), `"'`)
|
||||
}
|
||||
}
|
||||
_ = f.Close()
|
||||
if err := sc.Err(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
seen := map[string]bool{}
|
||||
var mods []string
|
||||
for _, entry := range strings.Split(modulepath, ":") {
|
||||
entry = strings.TrimSpace(entry)
|
||||
if entry == "" || entry == "$basemodulepath" {
|
||||
continue
|
||||
}
|
||||
if strings.Contains(entry, "$") {
|
||||
return nil, fmt.Errorf("environment.conf: unsupported modulepath entry %q", entry)
|
||||
}
|
||||
if !filepath.IsAbs(entry) {
|
||||
entry = filepath.Join(g.env, entry)
|
||||
}
|
||||
dirs, err := g.list(entry)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
for _, d := range dirs {
|
||||
if name := filepath.Base(d); moduleName.MatchString(name) && !seen[name] {
|
||||
seen[name] = true
|
||||
mods = append(mods, d)
|
||||
}
|
||||
}
|
||||
}
|
||||
return mods, nil
|
||||
}
|
||||
@@ -0,0 +1,762 @@
|
||||
package gentypes
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"os"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
"regexp"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
var (
|
||||
commentLine = regexp.MustCompile(`(?m)^\s*#.*\n`)
|
||||
blankRun = regexp.MustCompile(`\n{2,}`)
|
||||
)
|
||||
|
||||
func uncommented(s string) string {
|
||||
return blankRun.ReplaceAllString(commentLine.ReplaceAllString(s, ""), "\n")
|
||||
}
|
||||
|
||||
// realOnly are golden files real puppet generates that w10k skips because it cannot prove the output matches.
|
||||
var realOnly = set("r_const_call r_helper r_inline_provide r_prov_class r_prov_empty r_rs_bad_uncertain r_rs_bad_undef r_send")
|
||||
|
||||
// GENTYPES_ENV/GENTYPES_GOLDEN compare a full environment without comments, since provider docs are not ported.
|
||||
func TestGolden(t *testing.T) {
|
||||
env, golden, view, allowSkip := "testdata/env", "testdata/golden", func(s string) string { _, rest, _ := strings.Cut(s, "\n"); return rest }, realOnly
|
||||
if e := os.Getenv("GENTYPES_ENV"); e != "" {
|
||||
env, golden, view, allowSkip = e, os.Getenv("GENTYPES_GOLDEN"), uncommented, nil
|
||||
}
|
||||
work := t.TempDir()
|
||||
if err := os.CopyFS(work, os.DirFS(env)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := os.RemoveAll(filepath.Join(work, OutDir)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := Generate(work); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
want, _ := filepath.Glob(filepath.Join(golden, "*.pp"))
|
||||
if len(want) == 0 {
|
||||
t.Fatal("no golden files")
|
||||
}
|
||||
got, _ := filepath.Glob(filepath.Join(work, OutDir, "*.pp"))
|
||||
for _, g := range got {
|
||||
if !exists(filepath.Join(golden, filepath.Base(g))) {
|
||||
t.Errorf("%s generated, real puppet does not generate it", filepath.Base(g))
|
||||
}
|
||||
}
|
||||
match := 0
|
||||
for _, w := range want {
|
||||
name := filepath.Base(w)
|
||||
t.Run(strings.TrimSuffix(name, ".pp"), func(t *testing.T) {
|
||||
wb, _ := os.ReadFile(w)
|
||||
gb, err := os.ReadFile(filepath.Join(work, OutDir, name))
|
||||
if allowSkip[strings.TrimSuffix(name, ".pp")] {
|
||||
if err == nil {
|
||||
t.Fatal("expected a skip")
|
||||
}
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if g, w := view(string(gb)), view(string(wb)); g != w {
|
||||
t.Fatalf("mismatch:\n--- got\n%s\n--- want\n%s", g, w)
|
||||
}
|
||||
if _, gotDoc, _ := strings.Cut(string(gb), "\n"); !strings.Contains(string(wb), strings.SplitN(gotDoc, "Puppet::Resource::ResourceType3", 2)[0]) {
|
||||
t.Error("type doc comments differ from golden")
|
||||
}
|
||||
match++
|
||||
})
|
||||
}
|
||||
t.Logf("%d/%d golden files match", match, len(want)-len(allowSkip))
|
||||
}
|
||||
|
||||
// TestReviewSkips pins why each testdata/env/modules/review type that real puppet 9.3.0 fails to load, or that
|
||||
// w10k cannot prove, is skipped.
|
||||
func TestReviewSkips(t *testing.T) {
|
||||
work := t.TempDir()
|
||||
if err := os.CopyFS(work, os.DirFS("testdata/env")); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
skipped, err := Generate(work)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
got := map[string]string{}
|
||||
for _, s := range skipped {
|
||||
file, why, _ := strings.Cut(s.Error(), ": ")
|
||||
got[strings.TrimSuffix(filepath.Base(file), ".rb")] = why
|
||||
}
|
||||
for name, want := range map[string]string{
|
||||
"r_dollar": "line 4: unsupported top-level $",
|
||||
"r_prov_empty": "provider posix.rb: no Puppet::Type.type(:r_prov_empty).provide call",
|
||||
"r_prov_class": "provider posix.rb: no Puppet::Type.type(:r_prov_class).provide call",
|
||||
"r_prov_parent_missing": "parent provider nope is not defined",
|
||||
"r_send": "line 4: unsupported top-level Puppet::Type.type",
|
||||
"r_inline_provide": "line 4: unsupported top-level Puppet::Type.type",
|
||||
"r_helper": "line 1: unsupported top-level module RHelper",
|
||||
"r_const_call": "unsupported non-literal constant X",
|
||||
"r_require_missing": `require "puppet_x/review/nope": no module provides it`,
|
||||
"r_rs_str_key": "register_type: unsupported string key",
|
||||
"r_rs_bad_lower": `type "string": unsupported type`,
|
||||
"r_rs_bad_range": "unsupported Integer[5,1]",
|
||||
"r_rs_bad_regex": "unsupported regex /(/",
|
||||
"r_rs_bad_undef": "unsupported Undef",
|
||||
"r_rs_bad_uncertain": "cannot tell whether String and String[0] are the same type",
|
||||
"r_rs_bad_words": "unsupported word if",
|
||||
"r_dup_prop": "duplicate property a",
|
||||
"r_dup_param": "duplicate parameter a",
|
||||
"r_dup_ensure": "duplicate property ensure",
|
||||
"r_bare": "unsupported top-level Type.newtype",
|
||||
"r_mod_foo": "unsupported top-level module RFoo",
|
||||
"r_mod_compact": "unsupported top-level module Puppet::RCompact",
|
||||
"r_include_noreq": "include PuppetX::Review::Mix: no require defines it",
|
||||
"r_feature_const": "uninitialized constant RNope",
|
||||
} {
|
||||
if !strings.Contains(got[name], want) {
|
||||
t.Errorf("%s: got %q, want %q", name, got[name], want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestScrub(t *testing.T) {
|
||||
for _, c := range []struct{ in, want string }{
|
||||
{" one line \n\n", "one line"},
|
||||
{"First line\n indented\n more\n\n back ", "First line\nindented\n more\n\nback"},
|
||||
{"\n Lead\n blank\n \n end\n ", "\nLead\nblank\n\nend"},
|
||||
{"a\n\tb\n\t\tc", "a\nb\n\tc"},
|
||||
{"a\nb\n c", "a\nb\n c"},
|
||||
} {
|
||||
if got := scrub(c.in); got != c.want {
|
||||
t.Errorf("scrub(%q) = %q, want %q", c.in, got, c.want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestRegexRender(t *testing.T) {
|
||||
for _, c := range []struct {
|
||||
re regex
|
||||
puppet string
|
||||
inspect string
|
||||
}{
|
||||
{regex{"(.*)", "m"}, "/(?m-ix:(.*))/", "/(.*)/m"},
|
||||
{regex{"^a/b$", ""}, `/^a\/b$/`, `/^a\/b$/`},
|
||||
{regex{`^a\/b$`, ""}, `/^a\/b$/`, `/^a\/b$/`},
|
||||
{regex{`^(.*):([a-z]:(/|\\).*)$`, "i"}, `/(?i-mx:^(.*):([a-z]:(\/|\\).*)$)/`, `/^(.*):([a-z]:(\/|\\).*)$/i`},
|
||||
{regex{"x", "xim"}, "/(?mix:x)/", "/x/mix"},
|
||||
{regex{"", ""}, "//", "//"},
|
||||
} {
|
||||
got, err := c.re.puppet()
|
||||
if err != nil || got != c.puppet {
|
||||
t.Errorf("%+v puppet = %q (%v), want %q", c.re, got, err, c.puppet)
|
||||
}
|
||||
if got := c.re.inspect(); got != c.inspect {
|
||||
t.Errorf("%+v inspect = %q, want %q", c.re, got, c.inspect)
|
||||
}
|
||||
}
|
||||
if _, err := (regex{"(?i:a)", "m"}).puppet(); err == nil {
|
||||
t.Error("leading inline group with flags must be rejected")
|
||||
}
|
||||
}
|
||||
|
||||
func TestQuote(t *testing.T) {
|
||||
for in, want := range map[string]string{"name": "'name'", "it's": `'it\'s'`, `a\b`: `'a\b'`, `end\`: `'end\'`, "a\nb": `"a\nb"`, "": "''"} {
|
||||
if got := quote(in); got != want {
|
||||
t.Errorf("quote(%q) = %s, want %s", in, got, want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func typeOf(t *testing.T, body string) []string {
|
||||
t.Helper()
|
||||
types, err := parseFile("require 'puppet/parameter/boolean'\nPuppet::Type.newtype(:t) do\n"+body+"\nend\n", nil)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var out []string
|
||||
for _, a := range append(types[0].props, types[0].params...) {
|
||||
typ, err := a.puppetType()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
out = append(out, a.name+" "+typ)
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func TestPuppetTypeMapping(t *testing.T) {
|
||||
for _, c := range []struct{ body, want string }{
|
||||
{"newparam(:a)", "a Any"},
|
||||
{"newproperty(:a) do\n newvalues(:x, 'y')\nend", "a Enum['x', 'y']"},
|
||||
{"newparam(:a, parent: Puppet::Parameter::Boolean)", "a Variant[Boolean, Enum['true', 'false', 'yes', 'no']]"},
|
||||
{"newproperty(:a, :parent => Puppet::Property::Boolean)", "a Any"},
|
||||
{"newparam(:a) do\n newvalues(true, false)\nend", "a Variant[Boolean, Enum['true', 'false']]"},
|
||||
{"newparam(:a) do\n newvalues(%r{^\\d+$}, :absent)\nend", `a Variant[Enum['absent'], Pattern[/^\d+$/]]`},
|
||||
{"newparam(:a) do\n newvalue(:x)\n aliasvalue(:y, :x)\n newvalue(:z)\nend", "a Enum['x', 'y', 'z']"},
|
||||
{"newparam(:a) do\n newvalues(:x, :y)\n newvalue(:x) { }\nend", "a Enum['x', 'y']"},
|
||||
{"newparam(:a) do\n newvalues(nil, '')\nend", "a Enum['', '']"},
|
||||
{"ensurable", "ensure Enum['present', 'absent']"},
|
||||
{"ensurable do\n defaultvalues\n newvalue(:latest)\nend", "ensure Enum['present', 'absent', 'latest']"},
|
||||
} {
|
||||
if got := strings.Join(typeOf(t, c.body), "\n"); got != c.want {
|
||||
t.Errorf("%s:\n got %s\nwant %s", c.body, got, c.want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Expected values are ValueCreator.create_values on Puppet::Pops::Types::TypeParser.singleton.parse(typ) in openvox 9.3.0.
|
||||
func TestResourceAPIMapping(t *testing.T) {
|
||||
const str, num, boolean = "Pattern[//]", `Pattern[/^-?\d+$/]`, "Variant[Boolean, Enum['true', 'true', 'true', 'false', 'false', 'false']]"
|
||||
for typ, want := range map[string]string{
|
||||
"String": str,
|
||||
" Optional[String[1]] ": str,
|
||||
"Integer[0,65535]": num,
|
||||
"Boolean": boolean,
|
||||
"Enum[present, absent]": "Enum['absent', 'present']",
|
||||
"Optional[Enum[a, b]]": "Any",
|
||||
"Array[String]": "Any",
|
||||
"Sensitive[String]": "Any",
|
||||
"Optional[Numeric]": "Pattern[/" + strings.ReplaceAll(numericRe, "/", `\/`) + "/]",
|
||||
"Variant[String]": str,
|
||||
"Optional[Variant[Integer]]": num,
|
||||
"Variant[Optional[Float]]": "Pattern[/" + strings.ReplaceAll(numericRe, "/", `\/`) + "/]",
|
||||
"Variant[Integer[ 1 , 2 ], Integer[1,2]]": num,
|
||||
"Optional[Optional[String]]": "Any",
|
||||
"Optional['x']": str,
|
||||
"Variant[Variant[Boolean], Boolean]": boolean,
|
||||
"Variant[String, Integer]": "Any",
|
||||
"Optional": "Any",
|
||||
"Variant": "Any",
|
||||
"Hash[String, Integer, 1, 2]": "Any",
|
||||
"Integer[-5, default]": num,
|
||||
} {
|
||||
a := &attr{}
|
||||
if err := rsapiValues(a, typ); err != nil {
|
||||
t.Errorf("%s: %v", typ, err)
|
||||
continue
|
||||
}
|
||||
if got, _ := a.puppetType(); got != want {
|
||||
t.Errorf("%s = %s, want %s", typ, got, want)
|
||||
}
|
||||
}
|
||||
for _, typ := range []string{
|
||||
"string", "Stdlib::Port", "Optional[]", "Variant[]", "Integer[5,1]", "Integer[1.5]", "Numeric[1]", "Array[String, 3, 1]", "Hash[String]",
|
||||
"Float[2, 1.5]", "Pattern[/(/]", "Pattern['(']", "Pattern[/(?P<a>x)/]", "Enum[if]", "Variant[String, Undef]",
|
||||
"Variant[Integer, Integer[default,default]]", "Integer[0x10]", "String[1,2,3]", "Optional[String, Integer]", "Integer[",
|
||||
} {
|
||||
if err := rsapiValues(&attr{}, typ); err == nil {
|
||||
t.Errorf("%s: TypeParser rejects it or its values are not provable, want an error", typ)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestHeredocs(t *testing.T) {
|
||||
for src, want := range map[string]string{
|
||||
"x = <<~EOT\n a\n b\n\n \tc #{'d'}\n EOT\n": "a\n b\n\n\tc #{'d'}\n",
|
||||
"x = <<-EOT\n a\\tb\n EOT\n": " a\tb\n",
|
||||
"x = <<-'EOT'\n a\\tb\n EOT\n": " a\\tb\n",
|
||||
"x = <<EOT.strip\nbody\nEOT\n": "body\n",
|
||||
} {
|
||||
toks, err := lex(src)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var got string
|
||||
for _, p := range toks[2].parts {
|
||||
if p.code {
|
||||
got += "#{" + p.text + "}"
|
||||
} else {
|
||||
got += p.text
|
||||
}
|
||||
}
|
||||
if got != want {
|
||||
t.Errorf("%q: got %q, want %q", src, got, want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestUnsupported(t *testing.T) {
|
||||
for _, c := range []struct{ src, want string }{
|
||||
{"Puppet::Type.newtype(:t) do\n newparam(name_var)\nend", "unsupported expression"},
|
||||
{"Puppet::Type.newtype(:t) do\n newparam(:a) do\n desc \"x #{NOPE}\"\n end\nend", "#{NOPE}"},
|
||||
{"Puppet::Type.newtype(:t) do\n newparam(:a, parent: Puppet::Parameter::Custom)\nend", "uninitialized constant Puppet::Parameter::Custom"},
|
||||
{"Puppet::Type.newtype(:t) do\n if x\n newparam(:a)\n end\nend", "unsupported if x in type body"},
|
||||
{"Puppet::Type.newtype(:t) do\n if defined? X\n newparam(:a)\n end\nend", "unsupported conditional newparam"},
|
||||
{"Puppet::Type.newtype(:t) do\n [:a, :b].each { |n| newparam(n) }\nend", "unsupported [ :a , :b ].each in type body"},
|
||||
{"Puppet::Type.newtype(:t) do\n newparam(:a) do\n validate do\n newvalues(:x)\n end\n end\nend", "unsupported use of newvalues"},
|
||||
{"Puppet::Type.newtype(:t) do\n def self.title_patterns\n [[/(.*)/, [[:a, lambda { |x| x }]]]]\n end\nend", "title_patterns"},
|
||||
{"Puppet::Type.newtype(:t, self_refresh: true) do\nend", "newtype with options"},
|
||||
{"Puppet::Type.newtype(:t) do\n newparam(:a) do\n desc 'x' + dynamic\n end\nend", "unsupported expression"},
|
||||
{"Puppet::Type.newtype(:t) do\n @isomorphic = false\nend", "@isomorphic"},
|
||||
{"Puppet::Type.newtype(:t) do\n newparam(:a)\n newparam(:b, namevar: true)\n newparam(:c, namevar: true)\nend", "two or more key attributes"},
|
||||
} {
|
||||
types, err := parseFile(c.src, nil)
|
||||
if err == nil {
|
||||
_, err = render(types[0], nil, time.Now())
|
||||
}
|
||||
if err == nil || !strings.Contains(err.Error(), c.want) {
|
||||
t.Errorf("%q: got %v, want error containing %q", c.src, err, c.want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestDocs(t *testing.T) {
|
||||
src := `ABSENT = 'Set absent.'.freeze
|
||||
Puppet::Type.newtype(:t) do
|
||||
@doc = <<~EOT
|
||||
Squiggly doc.
|
||||
Indented.
|
||||
EOT
|
||||
newproperty(:a, required_features: %w[x y]) do
|
||||
desc "Prop #{ABSENT}
|
||||
continued #{' '}here"
|
||||
newvalues(:on, /^\d+$/)
|
||||
aliasvalue(:yes, :on)
|
||||
end
|
||||
newparam(:name, namevar: true) do
|
||||
desc _(<<-'EOT',
|
||||
Raw \n doc
|
||||
EOT
|
||||
)
|
||||
end
|
||||
end
|
||||
`
|
||||
types, err := parseFile(src, nil)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
out, err := render(types[0], []string{"posix"}, time.Now())
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for _, want := range []string{
|
||||
"# Squiggly doc.\n# Indented.\n",
|
||||
" # Prop Set absent.\n # continued here\n # \n # Valid values are `on` (also called `yes`). Values can match `/^\\d+$/`.\n # \n # Requires features x y.\n",
|
||||
" # Raw \\n doc\n Puppet::Resource::Param(Any, 'name', true),",
|
||||
"Puppet::Resource::Param(Variant[Enum['on', 'yes'], Pattern[/^\\d+$/]], 'a')",
|
||||
"Available providers are:\n # \n # posix\n # :",
|
||||
" /(?m-ix:(.*))/ => ['name']\n },\n true,\n false)\n",
|
||||
} {
|
||||
if !strings.Contains(out, want) {
|
||||
t.Errorf("output missing %q:\n%s", want, out)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func writeFile(t *testing.T, p, body string) {
|
||||
t.Helper()
|
||||
if err := os.MkdirAll(filepath.Dir(p), 0o755); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := os.WriteFile(p, []byte(body), 0o644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
const simpleType = "Puppet::Type.newtype(:%s) do\n newparam(:name, namevar: true)\nend\n"
|
||||
|
||||
func TestGenerateFiles(t *testing.T) {
|
||||
env := t.TempDir()
|
||||
cache := t.TempDir()
|
||||
mod := filepath.Join(cache, "mods", "foo")
|
||||
writeFile(t, filepath.Join(mod, "lib/puppet/type/foo.rb"), strings.ReplaceAll(simpleType, "%s", "foo"))
|
||||
writeFile(t, filepath.Join(mod, "lib/puppet/provider/foo/posix.rb"), "Puppet::Type.type(:foo).provide(:posix) do\nend\n")
|
||||
writeFile(t, filepath.Join(env, "modules/bar/lib/puppet/type/bar.rb"), strings.ReplaceAll(simpleType, "%s", "bar"))
|
||||
writeFile(t, filepath.Join(env, "site/bar/lib/puppet/type/shadowed.rb"), "not ruby (")
|
||||
writeFile(t, filepath.Join(env, "environment.conf"), "# comment\nmodulepath = modules:site:$basemodulepath\n")
|
||||
if err := os.Symlink(mod, filepath.Join(env, "modules/foo")); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
out := filepath.Join(env, OutDir)
|
||||
writeFile(t, filepath.Join(out, "stale.pp"), "old")
|
||||
writeFile(t, filepath.Join(out, "keepdir", "x"), "")
|
||||
if err := os.Symlink("/etc/passwd", filepath.Join(out, "link.pp")); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
victim := filepath.Join(t.TempDir(), "victim")
|
||||
writeFile(t, victim, "untouched")
|
||||
for _, l := range []string{"foo.pp", ".bar.pp.tmp"} {
|
||||
if err := os.Symlink(victim, filepath.Join(out, l)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
if _, err := Generate(env, cache); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if exists(filepath.Join(out, "stale.pp")) || exists(filepath.Join(out, "link.pp")) || !exists(filepath.Join(out, "keepdir")) {
|
||||
t.Fatal("cleanup must unlink stale files and symlinks and keep directories")
|
||||
}
|
||||
if !exists("/etc/passwd") {
|
||||
t.Fatal("unlinking a stale symlink must not touch its target")
|
||||
}
|
||||
if readFile(t, victim) != "untouched" {
|
||||
t.Fatal("writes must never follow symlinks under the output dir")
|
||||
}
|
||||
if fi, err := os.Lstat(filepath.Join(out, "foo.pp")); err != nil || !fi.Mode().IsRegular() {
|
||||
t.Fatal("a symlinked output must be replaced by a regular file")
|
||||
}
|
||||
foo, err := os.ReadFile(filepath.Join(out, "foo.pp"))
|
||||
if err != nil || !strings.Contains(string(foo), "'provider'") {
|
||||
t.Fatalf("foo.pp via symlinked module with provider: %v\n%s", err, foo)
|
||||
}
|
||||
bar := filepath.Join(out, "bar.pp")
|
||||
in, _ := os.Stat(filepath.Join(env, "modules/bar/lib/puppet/type/bar.rb"))
|
||||
if fi, err := os.Stat(bar); err != nil || !fi.ModTime().Equal(in.ModTime()) || strings.Contains(readFile(t, bar), "provider") {
|
||||
t.Fatalf("bar.pp must carry the input mtime and no provider param: %v", err)
|
||||
}
|
||||
|
||||
writeFile(t, bar, "edited")
|
||||
if err := os.Chtimes(bar, in.ModTime(), in.ModTime()); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := Generate(env, cache); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if readFile(t, bar) != "edited" {
|
||||
t.Fatal("output with the input's mtime is up to date and must be kept")
|
||||
}
|
||||
if err := os.Chtimes(bar, in.ModTime(), in.ModTime().Add(-time.Hour)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := Generate(env, cache); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if readFile(t, bar) == "edited" {
|
||||
t.Fatal("output with a different mtime must be regenerated")
|
||||
}
|
||||
}
|
||||
|
||||
func exists(p string) bool {
|
||||
_, err := os.Lstat(p)
|
||||
return err == nil
|
||||
}
|
||||
|
||||
func readFile(t *testing.T, p string) string {
|
||||
t.Helper()
|
||||
b, err := os.ReadFile(p)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return string(b)
|
||||
}
|
||||
|
||||
func TestGenerateErrors(t *testing.T) {
|
||||
t.Run("unparseable input is skipped naming the file and line", func(t *testing.T) {
|
||||
env := t.TempDir()
|
||||
writeFile(t, filepath.Join(env, "modules/m/lib/puppet/type/bad.rb"), "Puppet::Type.newtype(:bad) do\n newparam(dynamic)\nend\n")
|
||||
writeFile(t, filepath.Join(env, "modules/m/lib/puppet/type/good.rb"), strings.ReplaceAll(simpleType, "%s", "good"))
|
||||
writeFile(t, filepath.Join(env, OutDir, "bad.pp"), "previous")
|
||||
old := time.Now().Add(-time.Hour)
|
||||
if err := os.Chtimes(filepath.Join(env, OutDir, "bad.pp"), old, old); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
skipped, err := Generate(env)
|
||||
if err != nil || len(skipped) != 1 || !strings.Contains(skipped[0].Error(), "modules/m/lib/puppet/type/bad.rb: line 2:") {
|
||||
t.Fatalf("got %v, skipped %v", err, skipped)
|
||||
}
|
||||
if !exists(filepath.Join(env, OutDir, "good.pp")) || readFile(t, filepath.Join(env, OutDir, "bad.pp")) != "previous" {
|
||||
t.Fatal("good inputs still generate; a failing input's old output is kept")
|
||||
}
|
||||
})
|
||||
t.Run("wrong type name", func(t *testing.T) {
|
||||
env := t.TempDir()
|
||||
writeFile(t, filepath.Join(env, "modules/m/lib/puppet/type/a.rb"), strings.ReplaceAll(simpleType, "%s", "b"))
|
||||
if skipped, err := Generate(env); err != nil || len(skipped) != 1 || !strings.Contains(skipped[0].Error(), `"a" was not defined`) {
|
||||
t.Fatalf("got %v, skipped %v", err, skipped)
|
||||
}
|
||||
})
|
||||
t.Run("parser limit fails the env", func(t *testing.T) {
|
||||
env := t.TempDir()
|
||||
writeFile(t, filepath.Join(env, "modules/m/lib/puppet/type/deep.rb"), "Puppet::Type.newtype(:deep) do\n newparam(:a) do\n newvalues("+strings.Repeat("[", 300)+strings.Repeat("]", 300)+")\n end\nend\n")
|
||||
if skipped, err := Generate(env); !errors.Is(err, errLimit) || len(skipped) != 0 {
|
||||
t.Fatalf("got %v, skipped %v", err, skipped)
|
||||
}
|
||||
})
|
||||
t.Run("missing mixin is skipped", func(t *testing.T) {
|
||||
env := t.TempDir()
|
||||
writeFile(t, filepath.Join(env, "modules/m/lib/puppet/type/mix.rb"), "Puppet::Type.newtype(:mix) do\n include PuppetX::Nope\nend\n")
|
||||
if skipped, err := Generate(env); err != nil || len(skipped) != 1 {
|
||||
t.Fatalf("got %v, skipped %v", err, skipped)
|
||||
}
|
||||
})
|
||||
t.Run("output dir symlink", func(t *testing.T) {
|
||||
env := t.TempDir()
|
||||
if err := os.Symlink(t.TempDir(), filepath.Join(env, OutDir)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := Generate(env); err == nil || !strings.Contains(err.Error(), "not a directory") {
|
||||
t.Fatalf("got %v", err)
|
||||
}
|
||||
})
|
||||
t.Run("input outside roots", func(t *testing.T) {
|
||||
env, outside := t.TempDir(), t.TempDir()
|
||||
writeFile(t, filepath.Join(outside, "evil.rb"), strings.ReplaceAll(simpleType, "%s", "evil"))
|
||||
if err := os.MkdirAll(filepath.Join(env, "modules/m/lib/puppet/type"), 0o755); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := os.Symlink(filepath.Join(outside, "evil.rb"), filepath.Join(env, "modules/m/lib/puppet/type/evil.rb")); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := Generate(env); err == nil || !strings.Contains(err.Error(), "outside") {
|
||||
t.Fatalf("got %v", err)
|
||||
}
|
||||
})
|
||||
t.Run("modulepath outside roots", func(t *testing.T) {
|
||||
env := t.TempDir()
|
||||
writeFile(t, filepath.Join(env, "environment.conf"), "modulepath = "+t.TempDir()+"\n")
|
||||
if _, err := Generate(env); err == nil || !strings.Contains(err.Error(), "outside") {
|
||||
t.Fatalf("got %v", err)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
func parseWithin(t *testing.T, src string, resolve Resolver) ([]*rtype, error) {
|
||||
t.Helper()
|
||||
type res struct {
|
||||
ts []*rtype
|
||||
err error
|
||||
}
|
||||
ch := make(chan res, 1)
|
||||
go func() { ts, err := parseFile(src, resolve); ch <- res{ts, err} }()
|
||||
select {
|
||||
case r := <-ch:
|
||||
return r.ts, r.err
|
||||
case <-time.After(3 * time.Second):
|
||||
t.Fatalf("parseFile(%.40q) did not return", src)
|
||||
}
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
func TestStrayCloserIsAnError(t *testing.T) {
|
||||
for src, want := range map[string]string{
|
||||
")\n": "unsupported top-level )",
|
||||
"end\n": "unsupported top-level end",
|
||||
"Puppet::Type.newtype(:t) do\n }\nend\n": "line 2: unsupported } in type body",
|
||||
"Puppet::Type.newtype(:t) do\n newparam(:a) do\n )\n end\nend\n": "line 3: unsupported ) in attribute a",
|
||||
} {
|
||||
if _, err := parseWithin(t, src, nil); err == nil || !strings.Contains(err.Error(), want) {
|
||||
t.Errorf("%q: got %v, want %q", src, err, want)
|
||||
}
|
||||
}
|
||||
for src, want := range map[string]string{")\n": `unmatched ")"`, "]\n": `unmatched "]"`, "}\n": `unmatched "}"`, "end\n": `unmatched "end"`, "class A\n foo )\nend\n": "unmatched"} {
|
||||
if _, _, err := providerOf(src, "t"); err == nil || !strings.Contains(err.Error(), want) {
|
||||
t.Errorf("provider %q: got %v, want %q", src, err, want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestStepBudget(t *testing.T) {
|
||||
var err error
|
||||
func() {
|
||||
defer guard(&err)
|
||||
p := &parser{toks: []token{{kind: tEOF}}}
|
||||
for {
|
||||
p.cur()
|
||||
}
|
||||
}()
|
||||
if !errors.Is(err, errBudget) {
|
||||
t.Fatalf("got %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDeepNestingIsAnError(t *testing.T) {
|
||||
if os.Getenv("GENTYPES_DEEP_CHILD") == "1" {
|
||||
_, err := parseFile("Puppet::Type.newtype(:t) do\n newparam(:a) do\n newvalues("+strings.Repeat("[", 4<<20)+"\n", nil)
|
||||
if err == nil || !strings.Contains(err.Error(), "more than 262144 tokens") {
|
||||
os.Exit(3)
|
||||
}
|
||||
return
|
||||
}
|
||||
for _, src := range []string{
|
||||
"Puppet::Type.newtype(:u) do\n newparam(:a) do\n newvalues(" + strings.Repeat("[", 300) + strings.Repeat("]", 300) + ")\n end\nend\n",
|
||||
"Puppet::Type.newtype(:t) do\n newparam(:a) do\n" + strings.Repeat("if defined? X\n", 300) + strings.Repeat("end\n", 300) + "end\nend\n",
|
||||
`x = "` + strings.Repeat(`#{"`, 300) + strings.Repeat(`"}`, 300) + `"` + "\n",
|
||||
} {
|
||||
if _, err := parseWithin(t, "Puppet::Type.newtype(:t) do\nend\n"+src, nil); err == nil || !strings.Contains(err.Error(), "deeper than") {
|
||||
t.Errorf("%.40q: got %v", src, err)
|
||||
}
|
||||
}
|
||||
if _, err := inertLib("module PuppetX\n" + strings.Repeat("module A\n", 300) + strings.Repeat("end\n", 301)); err == nil || !strings.Contains(err.Error(), "deeper than") {
|
||||
t.Errorf("nested required modules: got %v", err)
|
||||
}
|
||||
cmd := exec.Command(os.Args[0], "-test.run=^TestDeepNestingIsAnError$")
|
||||
cmd.Env = append(os.Environ(), "GENTYPES_DEEP_CHILD=1")
|
||||
if out, err := cmd.CombinedOutput(); err != nil {
|
||||
t.Fatalf("4MiB of '[' must hit the token cap: %v\n%.300s", err, out)
|
||||
}
|
||||
}
|
||||
|
||||
func TestImplicitEnsurable(t *testing.T) {
|
||||
const head = "Puppet::Type.newtype(:t) do\n newproperty(:a)\n newparam(:name, namevar: true)\n"
|
||||
for body, want := range map[string]string{
|
||||
" def exists?; end\n def create; end\n def destroy\n true\n end\n": "ensure Enum['present', 'absent']\na Any\nname Any",
|
||||
" def exists?; end\n def create; end\n private\n def destroy; end\n": "a Any\nname Any",
|
||||
" def exists?; end\n def create; end\n": "a Any\nname Any",
|
||||
" ensurable do\n newvalue(:x)\n end\n def exists?; end\n def create; end\n def destroy; end\n": "ensure Enum['x']\na Any\nname Any",
|
||||
} {
|
||||
types, err := parseWithin(t, head+body+"end\n", nil)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var got []string
|
||||
for _, a := range append(types[0].props, types[0].params...) {
|
||||
typ, _ := a.puppetType()
|
||||
got = append(got, a.name+" "+typ)
|
||||
}
|
||||
if g := strings.Join(got, "\n"); g != want {
|
||||
t.Errorf("%s:\n got %s\nwant %s", body, g, want)
|
||||
}
|
||||
}
|
||||
out, err := render(mustParse(t, head+" def exists?; end\n def create; end\n def destroy; end\nend\n"), nil, time.Unix(0, 0))
|
||||
if err != nil || !strings.Contains(out, " # The basic property that the resource should be in.\n # \n # Valid values are `present`, `absent`.\n Puppet::Resource::Param(Enum['present', 'absent'], 'ensure'),\n") {
|
||||
t.Fatalf("implicit ensure must render like real puppet: %v\n%s", err, out)
|
||||
}
|
||||
if _, err := parseWithin(t, head+" if defined? X\n def create; end\n end\nend\n", nil); err == nil || !strings.Contains(err.Error(), "conditional def create") {
|
||||
t.Fatalf("got %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func mustParse(t *testing.T, src string) *rtype {
|
||||
t.Helper()
|
||||
types, err := parseWithin(t, src, nil)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return types[0]
|
||||
}
|
||||
|
||||
func TestResourceAPIBehaviorSpelling(t *testing.T) {
|
||||
ty := mustParse(t, "require 'puppet/resource_api'\nPuppet::ResourceApi.register_type(name: 't', attributes: { name: { type: 'String', behavior: :namevar }, p: { type: 'String', behavior: :parameter } })\n")
|
||||
if len(ty.params) != 2 || !ty.params[0].namevar || ty.params[1].namevar || len(ty.props) != 0 {
|
||||
t.Fatalf("behavior: is an alias of behaviour: %+v %+v", ty.params, ty.props)
|
||||
}
|
||||
for src, want := range map[string]string{
|
||||
"Puppet::ResourceApi.register_type(name: 't', attributes: { name: { type: 'String', behavior: :namevar, behaviour: :namevar } })\n": "both behavior and behaviour",
|
||||
"Puppet::ResourceApi.register_type(name: 't', attributes: { name: { type: 'String', behaviour: 'namevar' } })\n": "behaviour must be a symbol",
|
||||
} {
|
||||
if _, err := parseWithin(t, "require 'puppet/resource_api'\n"+src, nil); err == nil || !strings.Contains(err.Error(), want) {
|
||||
t.Errorf("%s: got %v, want %q", src, err, want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestTypeBodyRejectsUnknownStatements(t *testing.T) {
|
||||
for stmt, want := range map[string]string{
|
||||
"include PuppetX::Foo::Params": "line 3: include PuppetX::Foo::Params: mixin source is not available",
|
||||
"extend PuppetX::Foo": "line 3: unsupported extend PuppetX::Foo in type body",
|
||||
"PuppetX::Foo.add_params(self)": "line 3: unsupported PuppetX::Foo.add_params in type body",
|
||||
"instance_eval(&PuppetX::Foo::PARAMS)": "line 3: unsupported instance_eval in type body",
|
||||
"self.class_eval { newparam(:x) }": "unsupported self.class_eval in type body",
|
||||
"attr_accessor :create": "unsupported attr_accessor :create in type body",
|
||||
"private :create": "unsupported private :create in type body",
|
||||
"x ||= 1": "unsupported x ||= 1 in type body",
|
||||
"@parameters = []": "unsupported @parameters in type body",
|
||||
"@@count = 1": "unsupported @@count in type body",
|
||||
"FOO = compute": "unsupported non-literal constant FOO",
|
||||
"x = compute": "unsupported expression \"compute\"",
|
||||
"Puppet.warning(compute)": "unsupported expression \"compute\"",
|
||||
"def self.doc; 'x'; end": "unsupported def self.doc in type body",
|
||||
"class << self\n def title_patterns; []; end\n end": "unsupported def title_patterns in class << self",
|
||||
"class << self\n attr_reader :doc\n end": "attr_reader doc shadows a Puppet::Type class method",
|
||||
"validate(compute) do\n end": "validate: unsupported expression",
|
||||
"newparam(:b) do\n defaultto Facter.value(:x)\n end": `unsupported "." after "defaultto"`,
|
||||
"newparam(:b) do\n def self.doc; end\n end": "unsupported def self.doc in attribute b",
|
||||
"newparam(:b) do\n include Foo\n end": "unsupported include Foo in attribute b",
|
||||
"newparam(:b) do\n @doc2 = 'x'\n end": "unsupported @doc2 in attribute b",
|
||||
"newparam(:b) do\n newvalues(:a) if x\n end": `unsupported "if" after "newvalues"`,
|
||||
"newparam(:b) do\n if defined? X\n desc 'x'\n end\n end": "unsupported conditional desc",
|
||||
} {
|
||||
_, err := parseWithin(t, "Puppet::Type.newtype(:t) do\n newparam(:name, namevar: true)\n "+stmt+"\nend\n", nil)
|
||||
if err == nil || !strings.Contains(err.Error(), want) {
|
||||
t.Errorf("%q: got %v, want %q", stmt, err, want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestMixinMethods(t *testing.T) {
|
||||
const path = "PuppetX::M::Mix"
|
||||
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 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",
|
||||
} {
|
||||
got, err := mixinMethods(src, path)
|
||||
if g := strings.Join(got, " "); err != nil && !strings.Contains(err.Error(), want) || err == nil && g != want {
|
||||
t.Errorf("%q: got %q %v, want %q", src, g, err, want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestLiteralNormalisation(t *testing.T) {
|
||||
out, err := render(mustParse(t, "Puppet::Type.newtype(:t) do\n newparam(:name, namevar: true)\n newparam(:a) do\n newvalues(0x1f, 1_000, \"\\101\", /é/)\n end\nend\n"), nil, time.Unix(0, 0))
|
||||
if err != nil || !strings.Contains(out, "Variant[Enum['31', '1000', 'A'], Pattern[/(?-mix:é)/]]") || !strings.Contains(out, "Values can match `/é/`.") {
|
||||
t.Fatalf("got %v:\n%s", err, out)
|
||||
}
|
||||
for _, v := range []string{"?a", "1r", "2i", "1e400", "0x", "1__0", "08", `"\M-a"`, `"\xff"`, `"\377"`, "`id`", "%W[a#{1}]", `%w[a\ b]`, "%x(id)", `/\M-a/`, `/\xff/`, `/\200/`, `/(?i)é/`, `/a/n`} {
|
||||
types, err := parseWithin(t, "Puppet::Type.newtype(:t) do\n newparam(:name, namevar: true)\n newparam(:a) do\n newvalues("+v+")\n end\nend\n", nil)
|
||||
if err == nil {
|
||||
_, err = render(types[0], nil, time.Unix(0, 0))
|
||||
}
|
||||
if err == nil {
|
||||
t.Errorf("%s: literal Ruby renders differently must be rejected", v)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestProviderOf(t *testing.T) {
|
||||
for src, want := range map[string]string{
|
||||
"Puppet::Type.type(:t).provide(:a) do\nend\n": "a ",
|
||||
"require 'json'\nPuppet::Type.type('t').provide :b, parent: :a do\nend\nclass X\nend\n": "b a",
|
||||
"Puppet::Type.type(:t).provide(:c, parent: Puppet::Provider::Foo) {}\n": "c ",
|
||||
"class Puppet::Provider::T::Rsapi\nend\n": " ",
|
||||
"": " ",
|
||||
"Puppet::Type.type(:t).provide(name) do\nend\n": "error",
|
||||
"Puppet::Type.type(:other).provide(:a) do\nend\n": "error",
|
||||
"Puppet::Type.type(:t).provide(:a)\nPuppet::Type.type(:t).provide(:b)\n": "error",
|
||||
"Puppet::Type.type(:t).provide(:a)\nPuppet::Type.type(:t).newparam(:x)\n": "error",
|
||||
"module M\n Puppet::Type.type(:t).provide(:a)\nend\n": "error",
|
||||
"Puppet::Type.type(:t).provide(:a, 'parent' => :b)\n": "error",
|
||||
"$": " ",
|
||||
} {
|
||||
name, parent, err := providerOf(src, "t")
|
||||
got := name + " " + parent
|
||||
if err != nil {
|
||||
got = "error"
|
||||
}
|
||||
if got != want {
|
||||
t.Errorf("%q: got %q (%v), want %q", src, got, err, want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestLexTrailingSigil(t *testing.T) {
|
||||
for _, src := range []string{"$", "x = $", "@", "@@", "Puppet::Type.newtype(:t) do\nend\n$"} {
|
||||
if _, err := parseWithin(t, src, nil); err == nil {
|
||||
t.Errorf("%q: want an error", src)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestGeneratePanicFailsTheEnv(t *testing.T) {
|
||||
env := t.TempDir()
|
||||
in := filepath.Join(env, "modules/m/lib/puppet/type/mix.rb")
|
||||
writeFile(t, in, "require 'puppet_x/m/mix'\nPuppet::Type.newtype(:mix) do\n include PuppetX::M::Mix\nend\n")
|
||||
out, err := openOut(env)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer func() { _ = out.Close() }()
|
||||
err = generateOne(in, out, nil, func(string, bool) ([]string, error) { panic("boom") })
|
||||
if err == nil || !strings.Contains(err.Error(), "panic: boom") || errors.As(err, new(skipErr)) {
|
||||
t.Fatalf("a panic must be a hard error, got %v", err)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,696 @@
|
||||
package gentypes
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"strconv"
|
||||
"strings"
|
||||
"unicode/utf8"
|
||||
)
|
||||
|
||||
const (
|
||||
maxDepth = 256
|
||||
maxTokens = 1 << 18
|
||||
)
|
||||
|
||||
type kind int
|
||||
|
||||
const (
|
||||
tEOF kind = iota
|
||||
tNL
|
||||
tIdent
|
||||
tConst
|
||||
tIVar
|
||||
tGVar
|
||||
tSym
|
||||
tLabel
|
||||
tStr
|
||||
tRegex
|
||||
tWords
|
||||
tNum
|
||||
tOp
|
||||
)
|
||||
|
||||
type part struct {
|
||||
text string
|
||||
code bool
|
||||
}
|
||||
|
||||
type token struct {
|
||||
kind kind
|
||||
text string
|
||||
parts []part
|
||||
words []string
|
||||
flags string
|
||||
line int
|
||||
space bool
|
||||
}
|
||||
|
||||
type lexer struct {
|
||||
src string
|
||||
pos int
|
||||
line int
|
||||
toks []token
|
||||
pending []heredoc
|
||||
}
|
||||
|
||||
type heredoc struct {
|
||||
tok int
|
||||
id string
|
||||
squig bool
|
||||
indent bool
|
||||
raw bool
|
||||
}
|
||||
|
||||
func lex(src string) ([]token, error) {
|
||||
if !utf8.ValidString(src) {
|
||||
return nil, fmt.Errorf("source is not valid UTF-8")
|
||||
}
|
||||
l := &lexer{src: src, line: 1}
|
||||
if err := l.run(); err != nil {
|
||||
return nil, fmt.Errorf("line %d: %w", l.line, err)
|
||||
}
|
||||
l.toks = append(l.toks, token{kind: tEOF, line: l.line})
|
||||
return l.toks, nil
|
||||
}
|
||||
|
||||
func isIdentStart(c byte) bool {
|
||||
return c == '_' || c >= 'a' && c <= 'z' || c >= 'A' && c <= 'Z' || c >= 0x80
|
||||
}
|
||||
|
||||
func isIdentChar(c byte) bool { return isIdentStart(c) || c >= '0' && c <= '9' }
|
||||
|
||||
func (l *lexer) peek(off int) byte {
|
||||
if l.pos+off < len(l.src) {
|
||||
return l.src[l.pos+off]
|
||||
}
|
||||
return 0
|
||||
}
|
||||
|
||||
func (l *lexer) emit(t token) {
|
||||
t.line = l.line
|
||||
l.toks = append(l.toks, t)
|
||||
}
|
||||
|
||||
func (l *lexer) last() *token {
|
||||
if len(l.toks) == 0 {
|
||||
return nil
|
||||
}
|
||||
return &l.toks[len(l.toks)-1]
|
||||
}
|
||||
|
||||
var keywords = map[string]bool{
|
||||
"if": true, "unless": true, "while": true, "until": true, "and": true, "or": true, "not": true,
|
||||
"return": true, "when": true, "then": true, "else": true, "elsif": true, "do": true, "in": true,
|
||||
"case": true, "begin": true, "yield": true,
|
||||
}
|
||||
|
||||
// valueBefore reports whether the previous token ends an operand, which decides /, % and << ambiguity.
|
||||
func (l *lexer) valueBefore() bool {
|
||||
t := l.last()
|
||||
if t == nil {
|
||||
return false
|
||||
}
|
||||
switch t.kind {
|
||||
case tIdent:
|
||||
return !keywords[t.text]
|
||||
case tConst, tIVar, tGVar, tNum, tStr, tSym, tRegex, tWords:
|
||||
return true
|
||||
case tOp:
|
||||
return t.text == ")" || t.text == "]" || t.text == "}"
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// literalStart decides whether an ambiguous operator char starts a literal.
|
||||
func (l *lexer) literalStart(space bool, oplen int) bool {
|
||||
if !l.valueBefore() {
|
||||
return true
|
||||
}
|
||||
t := l.last()
|
||||
next := l.peek(oplen)
|
||||
return t.kind == tIdent && space && next != ' ' && next != '=' && next != '\n'
|
||||
}
|
||||
|
||||
func (l *lexer) run() error {
|
||||
space := false
|
||||
for l.pos < len(l.src) {
|
||||
c := l.src[l.pos]
|
||||
atBOL := l.pos == 0 || l.src[l.pos-1] == '\n'
|
||||
switch {
|
||||
case c == ' ' || c == '\t' || c == '\r':
|
||||
l.pos++
|
||||
space = true
|
||||
continue
|
||||
case c == '\\' && l.peek(1) == '\n':
|
||||
l.pos += 2
|
||||
l.line++
|
||||
space = true
|
||||
continue
|
||||
case c == '\n':
|
||||
l.pos++
|
||||
l.emit(token{kind: tNL})
|
||||
l.line++
|
||||
if err := l.readHeredocs(); err != nil {
|
||||
return err
|
||||
}
|
||||
space = false
|
||||
continue
|
||||
case c == '#':
|
||||
for l.pos < len(l.src) && l.src[l.pos] != '\n' {
|
||||
l.pos++
|
||||
}
|
||||
continue
|
||||
case atBOL && strings.HasPrefix(l.src[l.pos:], "=begin"):
|
||||
end := strings.Index(l.src[l.pos:], "\n=end")
|
||||
if end < 0 {
|
||||
return fmt.Errorf("unterminated =begin")
|
||||
}
|
||||
l.line += strings.Count(l.src[l.pos:l.pos+end+5], "\n")
|
||||
l.pos += end + 5
|
||||
for l.pos < len(l.src) && l.src[l.pos] != '\n' {
|
||||
l.pos++
|
||||
}
|
||||
continue
|
||||
case atBOL && strings.HasPrefix(l.src[l.pos:], "__END__") && (l.peek(7) == '\n' || l.peek(7) == 0):
|
||||
l.pos = len(l.src)
|
||||
continue
|
||||
}
|
||||
start := len(l.toks)
|
||||
if start > maxTokens {
|
||||
return fmt.Errorf("more than %d tokens: %w", maxTokens, errLimit)
|
||||
}
|
||||
if err := l.next(space); err != nil {
|
||||
return err
|
||||
}
|
||||
if len(l.toks) > start {
|
||||
l.toks[start].space = space
|
||||
}
|
||||
space = false
|
||||
}
|
||||
if len(l.pending) > 0 {
|
||||
return fmt.Errorf("unterminated heredoc %s", l.pending[0].id)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (l *lexer) next(space bool) error {
|
||||
c := l.src[l.pos]
|
||||
switch {
|
||||
case c >= '0' && c <= '9':
|
||||
s := l.pos
|
||||
hex := c == '0' && (l.peek(1) == 'x' || l.peek(1) == 'X')
|
||||
for l.pos < len(l.src) && (isIdentChar(l.src[l.pos]) || l.src[l.pos] == '.' && l.peek(1) >= '0' && l.peek(1) <= '9' ||
|
||||
!hex && (l.src[l.pos] == '+' || l.src[l.pos] == '-') && (l.src[l.pos-1] == 'e' || l.src[l.pos-1] == 'E') && l.peek(1) >= '0' && l.peek(1) <= '9') {
|
||||
l.pos++
|
||||
}
|
||||
l.emit(token{kind: tNum, text: l.src[s:l.pos]})
|
||||
case isIdentStart(c):
|
||||
s := l.pos
|
||||
for l.pos < len(l.src) && isIdentChar(l.src[l.pos]) {
|
||||
l.pos++
|
||||
}
|
||||
if (l.peek(0) == '?' || l.peek(0) == '!') && l.peek(1) != '=' {
|
||||
l.pos++
|
||||
}
|
||||
word := l.src[s:l.pos]
|
||||
if l.peek(0) == ':' && l.peek(1) != ':' {
|
||||
if t := l.last(); t == nil || t.kind != tOp || t.text != "?" {
|
||||
l.pos++
|
||||
l.emit(token{kind: tLabel, text: word})
|
||||
return nil
|
||||
}
|
||||
}
|
||||
if c >= 'A' && c <= 'Z' {
|
||||
l.emit(token{kind: tConst, text: word})
|
||||
} else {
|
||||
l.emit(token{kind: tIdent, text: word})
|
||||
}
|
||||
case c == '@' || c == '$':
|
||||
s := l.pos
|
||||
l.pos++
|
||||
if c == '@' && l.peek(0) == '@' {
|
||||
l.pos++
|
||||
}
|
||||
if c == '$' && !isIdentStart(l.peek(0)) && l.pos < len(l.src) {
|
||||
l.pos++
|
||||
}
|
||||
for l.pos < len(l.src) && isIdentChar(l.src[l.pos]) {
|
||||
l.pos++
|
||||
}
|
||||
k := tIVar
|
||||
if c == '$' {
|
||||
k = tGVar
|
||||
}
|
||||
l.emit(token{kind: k, text: l.src[s:l.pos]})
|
||||
case c == ':' && l.peek(1) == ':':
|
||||
l.pos += 2
|
||||
l.emit(token{kind: tOp, text: "::"})
|
||||
case c == ':' && (l.peek(1) == '"' || l.peek(1) == '\''):
|
||||
l.pos++
|
||||
parts, err := l.quoted(l.src[l.pos], l.src[l.pos], l.src[l.pos] == '"', 0)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
l.emit(token{kind: tSym, parts: parts})
|
||||
case c == ':' && isIdentStart(l.peek(1)):
|
||||
l.pos++
|
||||
s := l.pos
|
||||
for l.pos < len(l.src) && isIdentChar(l.src[l.pos]) {
|
||||
l.pos++
|
||||
}
|
||||
if c := l.peek(0); (c == '?' || c == '!' || c == '=') && l.peek(1) != '=' && l.peek(1) != '>' {
|
||||
l.pos++
|
||||
}
|
||||
l.emit(token{kind: tSym, text: l.src[s:l.pos]})
|
||||
case c == '"' || c == '\'' || c == '`':
|
||||
parts, err := l.quoted(c, c, c != '\'', 0)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
l.emit(token{kind: tStr, parts: parts, flags: string(c)})
|
||||
case c == '/' && l.literalStart(space, 1):
|
||||
return l.regex('/', '/')
|
||||
case c == '%' && l.literalStart(space, 1) && l.percentLiteral():
|
||||
return l.percent()
|
||||
case c == '<' && l.peek(1) == '<' && l.literalStart(space, 2) && l.heredocStart():
|
||||
return l.heredocHead()
|
||||
default:
|
||||
for _, op := range []string{"**=", "<=>", "===", "...", "||=", "&&=", "<<=", ">>=", "==", "!=", ">=", "<=", "&&", "||", "<<", ">>", "**", "=>", "->", "..", "+=", "-=", "*=", "/=", "%=", "|=", "&=", "=~", "!~", "&."} {
|
||||
if strings.HasPrefix(l.src[l.pos:], op) {
|
||||
l.pos += len(op)
|
||||
l.emit(token{kind: tOp, text: op})
|
||||
return nil
|
||||
}
|
||||
}
|
||||
l.pos++
|
||||
l.emit(token{kind: tOp, text: string(c)})
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func closer(open byte) byte {
|
||||
switch open {
|
||||
case '(':
|
||||
return ')'
|
||||
case '[':
|
||||
return ']'
|
||||
case '{':
|
||||
return '}'
|
||||
case '<':
|
||||
return '>'
|
||||
}
|
||||
return open
|
||||
}
|
||||
|
||||
func (l *lexer) percentLiteral() bool {
|
||||
c := l.peek(1)
|
||||
if strings.IndexByte("qQwWiIrs", c) >= 0 {
|
||||
d := l.peek(2)
|
||||
return d != 0 && !isIdentChar(d) && d != ' ' && d != '\n'
|
||||
}
|
||||
return c == '(' || c == '[' || c == '{' || c == '<' || c == '|' || c == '!'
|
||||
}
|
||||
|
||||
func (l *lexer) percent() error {
|
||||
l.pos++
|
||||
typ := byte('Q')
|
||||
if c := l.peek(0); isIdentStart(c) {
|
||||
typ = c
|
||||
l.pos++
|
||||
}
|
||||
open := l.src[l.pos]
|
||||
cl := closer(open)
|
||||
switch typ {
|
||||
case 'r':
|
||||
return l.regex(open, cl)
|
||||
case 'w', 'W', 'i', 'I':
|
||||
body, err := l.scan(open, cl, typ == 'W' || typ == 'I', 0)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if strings.ContainsRune(body, '\\') || (typ == 'W' || typ == 'I') && strings.Contains(body, "#") {
|
||||
return fmt.Errorf("unsupported escape or interpolation in %%%c literal", typ)
|
||||
}
|
||||
l.emit(token{kind: tWords, words: strings.Fields(body)})
|
||||
case 's':
|
||||
parts, err := l.quoted(open, cl, false, 0)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
l.emit(token{kind: tSym, parts: parts})
|
||||
case 'q':
|
||||
parts, err := l.quoted(open, cl, false, 0)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
l.emit(token{kind: tStr, parts: parts})
|
||||
case 'Q':
|
||||
parts, err := l.quoted(open, cl, true, 0)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
l.emit(token{kind: tStr, parts: parts})
|
||||
default:
|
||||
return fmt.Errorf("unsupported %%%c literal", typ)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// scan reads a delimited body starting at the opening delimiter, returning raw text with nesting and #{} honoured.
|
||||
func (l *lexer) scan(open, cl byte, interp bool, nest int) (string, error) {
|
||||
if nest > maxDepth {
|
||||
return "", fmt.Errorf("interpolation nested deeper than %d: %w", maxDepth, errLimit)
|
||||
}
|
||||
l.pos++
|
||||
s := l.pos
|
||||
depth := 0
|
||||
for l.pos < len(l.src) {
|
||||
c := l.src[l.pos]
|
||||
switch {
|
||||
case c == '\\':
|
||||
l.pos += 2
|
||||
continue
|
||||
case interp && c == '#' && l.peek(1) == '{':
|
||||
l.pos++
|
||||
if _, err := l.scan('{', '}', true, nest+1); err != nil {
|
||||
return "", err
|
||||
}
|
||||
continue
|
||||
case c == cl && depth == 0:
|
||||
body := l.src[s:l.pos]
|
||||
l.pos++
|
||||
l.line += strings.Count(body, "\n")
|
||||
return body, nil
|
||||
case c == cl:
|
||||
depth--
|
||||
case c == open && open != cl:
|
||||
depth++
|
||||
}
|
||||
l.pos++
|
||||
}
|
||||
return "", fmt.Errorf("unterminated literal")
|
||||
}
|
||||
|
||||
func (l *lexer) quoted(open, cl byte, dq bool, depth int) ([]part, error) {
|
||||
body, err := l.scan(open, cl, dq, depth)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if !dq {
|
||||
return []part{{text: unescapeSingle(body, open, cl)}}, nil
|
||||
}
|
||||
return splitInterp(body)
|
||||
}
|
||||
|
||||
func unescapeSingle(s string, open, cl byte) string {
|
||||
var b strings.Builder
|
||||
for i := 0; i < len(s); i++ {
|
||||
if s[i] == '\\' && i+1 < len(s) && (s[i+1] == '\\' || s[i+1] == open || s[i+1] == cl) {
|
||||
i++
|
||||
}
|
||||
b.WriteByte(s[i])
|
||||
}
|
||||
return b.String()
|
||||
}
|
||||
|
||||
func splitInterp(body string) ([]part, error) {
|
||||
var parts []part
|
||||
var b strings.Builder
|
||||
for i := 0; i < len(body); i++ {
|
||||
c := body[i]
|
||||
if c == '#' && i+1 < len(body) && body[i+1] == '{' {
|
||||
depth, j := 0, i+1
|
||||
for ; j < len(body); j++ {
|
||||
if body[j] == '{' {
|
||||
depth++
|
||||
} else if body[j] == '}' {
|
||||
depth--
|
||||
if depth == 0 {
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
if j >= len(body) {
|
||||
return nil, fmt.Errorf("unterminated interpolation")
|
||||
}
|
||||
if b.Len() > 0 {
|
||||
parts = append(parts, part{text: b.String()})
|
||||
b.Reset()
|
||||
}
|
||||
parts = append(parts, part{text: strings.TrimSpace(body[i+2 : j]), code: true})
|
||||
i = j
|
||||
continue
|
||||
}
|
||||
if c == '#' && i+1 < len(body) && (body[i+1] == '@' || body[i+1] == '$') {
|
||||
parts = append(parts, part{text: body[i:], code: true})
|
||||
break
|
||||
}
|
||||
if c != '\\' || i+1 >= len(body) {
|
||||
b.WriteByte(c)
|
||||
continue
|
||||
}
|
||||
n, err := unescape(&b, body[i+1:])
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
i += n
|
||||
}
|
||||
if b.Len() > 0 || len(parts) == 0 {
|
||||
parts = append(parts, part{text: b.String()})
|
||||
}
|
||||
for _, p := range parts {
|
||||
if !p.code && !utf8.ValidString(p.text) {
|
||||
return nil, fmt.Errorf("string escape yields invalid UTF-8")
|
||||
}
|
||||
}
|
||||
return parts, nil
|
||||
}
|
||||
|
||||
func hexVal(s string, max int) (uint64, int) {
|
||||
n := 0
|
||||
for n < len(s) && n < max && strings.IndexByte("0123456789abcdefABCDEF", s[n]) >= 0 {
|
||||
n++
|
||||
}
|
||||
v, _ := strconv.ParseUint(s[:n], 16, 32)
|
||||
return v, n
|
||||
}
|
||||
|
||||
// unescape writes the Ruby double-quoted escape at the start of s (after the backslash), returning its length.
|
||||
func unescape(b *strings.Builder, s string) (int, error) {
|
||||
if i := strings.IndexByte("ntsrfvaeb", s[0]); i >= 0 {
|
||||
b.WriteByte("\n\t \r\f\v\a\x1b\b"[i])
|
||||
return 1, nil
|
||||
}
|
||||
switch e := s[0]; {
|
||||
case e == '\n':
|
||||
return 1, nil
|
||||
case e >= '0' && e <= '7':
|
||||
n, v := 0, 0
|
||||
for n < len(s) && n < 3 && s[n] >= '0' && s[n] <= '7' {
|
||||
v = v*8 + int(s[n]-'0')
|
||||
n++
|
||||
}
|
||||
b.WriteByte(byte(v))
|
||||
return n, nil
|
||||
case e == 'x':
|
||||
v, n := hexVal(s[1:], 2)
|
||||
if n == 0 {
|
||||
return 0, fmt.Errorf("invalid \\x escape")
|
||||
}
|
||||
b.WriteByte(byte(v))
|
||||
return n + 1, nil
|
||||
case e == 'u':
|
||||
if len(s) > 1 && s[1] == '{' {
|
||||
end := strings.IndexByte(s, '}')
|
||||
if end < 0 || strings.TrimSpace(s[2:end]) == "" {
|
||||
return 0, fmt.Errorf("invalid \\u escape")
|
||||
}
|
||||
for _, h := range strings.Fields(s[2:end]) {
|
||||
v, n := hexVal(h, 6)
|
||||
if n != len(h) || !utf8.ValidRune(rune(v)) {
|
||||
return 0, fmt.Errorf("invalid \\u escape")
|
||||
}
|
||||
b.WriteRune(rune(v))
|
||||
}
|
||||
return end + 1, nil
|
||||
}
|
||||
v, n := hexVal(s[1:], 4)
|
||||
if n != 4 || !utf8.ValidRune(rune(v)) {
|
||||
return 0, fmt.Errorf("invalid \\u escape")
|
||||
}
|
||||
b.WriteRune(rune(v))
|
||||
return 5, nil
|
||||
case e == 'c' || e == 'C' && len(s) > 1 && s[1] == '-':
|
||||
n := 1
|
||||
if e == 'C' {
|
||||
n = 2
|
||||
}
|
||||
if n >= len(s) || s[n] == '\\' || s[n] >= 0x80 {
|
||||
return 0, fmt.Errorf("unsupported control escape")
|
||||
}
|
||||
if s[n] == '?' {
|
||||
b.WriteByte(127)
|
||||
} else {
|
||||
b.WriteByte(s[n] & 0x9f)
|
||||
}
|
||||
return n + 1, nil
|
||||
case e == 'M' || e == 'C':
|
||||
return 0, fmt.Errorf("unsupported \\%c escape", e)
|
||||
}
|
||||
_, n := utf8.DecodeRuneInString(s)
|
||||
b.WriteString(s[:n])
|
||||
return n, nil
|
||||
}
|
||||
|
||||
func (l *lexer) regex(open, cl byte) error {
|
||||
raw, err := l.scan(open, cl, true, 0)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
var body strings.Builder
|
||||
for i := 0; i < len(raw); i++ {
|
||||
if raw[i] == '\\' && i+1 < len(raw) {
|
||||
if raw[i+1] != cl || strings.IndexByte("$*+.?^|)]}>", cl) >= 0 {
|
||||
body.WriteByte('\\')
|
||||
}
|
||||
i++
|
||||
}
|
||||
body.WriteByte(raw[i])
|
||||
}
|
||||
s := l.pos
|
||||
for l.pos < len(l.src) && strings.IndexByte("mixounse", l.src[l.pos]) >= 0 {
|
||||
l.pos++
|
||||
}
|
||||
l.emit(token{kind: tRegex, text: body.String(), flags: l.src[s:l.pos]})
|
||||
return nil
|
||||
}
|
||||
|
||||
func (l *lexer) heredocStart() bool {
|
||||
i := 2
|
||||
if c := l.peek(i); c == '-' || c == '~' {
|
||||
i++
|
||||
}
|
||||
c := l.peek(i)
|
||||
return c == '\'' || c == '"' || isIdentStart(c)
|
||||
}
|
||||
|
||||
func (l *lexer) heredocHead() error {
|
||||
l.pos += 2
|
||||
h := heredoc{tok: len(l.toks)}
|
||||
switch l.peek(0) {
|
||||
case '-':
|
||||
h.indent = true
|
||||
l.pos++
|
||||
case '~':
|
||||
h.indent, h.squig = true, true
|
||||
l.pos++
|
||||
}
|
||||
if q := l.peek(0); q == '\'' || q == '"' {
|
||||
end := strings.IndexByte(l.src[l.pos+1:], q)
|
||||
if end < 0 {
|
||||
return fmt.Errorf("bad heredoc identifier")
|
||||
}
|
||||
h.id, h.raw = l.src[l.pos+1:l.pos+1+end], q == '\''
|
||||
l.pos += end + 2
|
||||
} else {
|
||||
s := l.pos
|
||||
for l.pos < len(l.src) && isIdentChar(l.src[l.pos]) {
|
||||
l.pos++
|
||||
}
|
||||
h.id = l.src[s:l.pos]
|
||||
}
|
||||
l.pending = append(l.pending, h)
|
||||
l.emit(token{kind: tStr})
|
||||
return nil
|
||||
}
|
||||
|
||||
func (l *lexer) readHeredocs() error {
|
||||
for _, h := range l.pending {
|
||||
var lines []string
|
||||
for {
|
||||
if l.pos >= len(l.src) {
|
||||
return fmt.Errorf("unterminated heredoc %s", h.id)
|
||||
}
|
||||
end := strings.IndexByte(l.src[l.pos:], '\n')
|
||||
var line string
|
||||
if end < 0 {
|
||||
line, l.pos = l.src[l.pos:], len(l.src)
|
||||
} else {
|
||||
line, l.pos = l.src[l.pos:l.pos+end], l.pos+end+1
|
||||
}
|
||||
l.line++
|
||||
term := strings.TrimRight(line, "\r")
|
||||
if h.indent {
|
||||
term = strings.TrimLeft(term, " \t")
|
||||
}
|
||||
if term == h.id {
|
||||
break
|
||||
}
|
||||
lines = append(lines, line+"\n")
|
||||
}
|
||||
if h.squig {
|
||||
lines = dedent(lines)
|
||||
}
|
||||
body := strings.Join(lines, "")
|
||||
if h.raw {
|
||||
l.toks[h.tok].parts = []part{{text: body}}
|
||||
continue
|
||||
}
|
||||
parts, err := splitInterp(body)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
l.toks[h.tok].parts = parts
|
||||
}
|
||||
l.pending = nil
|
||||
return nil
|
||||
}
|
||||
|
||||
func indentWidth(s string) (width, n int) {
|
||||
for n < len(s) {
|
||||
switch s[n] {
|
||||
case ' ':
|
||||
width++
|
||||
case '\t':
|
||||
width = width/8*8 + 8
|
||||
default:
|
||||
return width, n
|
||||
}
|
||||
n++
|
||||
}
|
||||
return width, n
|
||||
}
|
||||
|
||||
// dedent applies <<~ semantics: strip the smallest indent of non-blank lines from every line.
|
||||
func dedent(lines []string) []string {
|
||||
min := -1
|
||||
for _, ln := range lines {
|
||||
if strings.TrimSpace(ln) == "" {
|
||||
continue
|
||||
}
|
||||
if w, _ := indentWidth(ln); min < 0 || w < min {
|
||||
min = w
|
||||
}
|
||||
}
|
||||
if min <= 0 {
|
||||
return lines
|
||||
}
|
||||
out := make([]string, len(lines))
|
||||
for i, ln := range lines {
|
||||
w, n := 0, 0
|
||||
for n < len(ln) && w < min && (ln[n] == ' ' || ln[n] == '\t') {
|
||||
if ln[n] == '\t' {
|
||||
nw := w/8*8 + 8
|
||||
if nw > min {
|
||||
break
|
||||
}
|
||||
w = nw
|
||||
} else {
|
||||
w++
|
||||
}
|
||||
n++
|
||||
}
|
||||
out[i] = ln[n:]
|
||||
}
|
||||
return out
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,334 @@
|
||||
package gentypes
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"math/big"
|
||||
"regexp"
|
||||
"regexp/syntax"
|
||||
"strconv"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// ptype is a Resource API type string parsed the way Puppet::Pops::Types::TypeParser does,
|
||||
// limited to the forms whose result puppet-resource_api's ValueCreator.create_values can be decided for.
|
||||
type ptype struct {
|
||||
name string
|
||||
canon string
|
||||
kids []*ptype
|
||||
}
|
||||
|
||||
type tparser struct {
|
||||
s string
|
||||
pos int
|
||||
}
|
||||
|
||||
var (
|
||||
intLit = regexp.MustCompile(`^(?:0|[1-9][0-9]*)$`)
|
||||
floatLit = regexp.MustCompile(`^(?:0|[1-9][0-9]*)(?:\.[0-9]+)?(?:[eE][+-]?[0-9]+)?$`)
|
||||
enumWord = regexp.MustCompile(`^[a-z][a-z0-9_]*$`)
|
||||
typeName = regexp.MustCompile(`^[A-Z][A-Za-z0-9_]*`)
|
||||
puppetKws = set("and application attr case class consumes default define else elsif environment false function if import in inherits node or private produces site true type undef unless plan apply")
|
||||
// Onigmo syntax RE2 accepts with another meaning, or accepts where Ruby raises.
|
||||
reUnsafe = regexp.MustCompile(`\(\?P|\(\?[imsU-]*[sU]|\\[pPxQEC0-9]|\[\^?\]`)
|
||||
)
|
||||
|
||||
// parsePType returns the value category ValueCreator sees after unwrapping one Optional:
|
||||
// String, Boolean, Integer, Float, Numeric, or "" for any other type.
|
||||
func parsePType(s string) (string, error) {
|
||||
p := &tparser{s: s}
|
||||
t, err := p.typ(0)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("type %q: %w", s, err)
|
||||
}
|
||||
if p.skip(); p.pos != len(p.s) {
|
||||
return "", fmt.Errorf("type %q: unsupported trailing input", s)
|
||||
}
|
||||
if t, err = normalize(t); err != nil {
|
||||
return "", fmt.Errorf("type %q: %w", s, err)
|
||||
}
|
||||
if t.name == "Optional" {
|
||||
if len(t.kids) == 0 {
|
||||
return "", nil
|
||||
}
|
||||
t = t.kids[0]
|
||||
}
|
||||
switch t.name {
|
||||
case "String", "Boolean", "Integer", "Float", "Numeric":
|
||||
return t.name, nil
|
||||
}
|
||||
return "", nil
|
||||
}
|
||||
|
||||
// normalize mirrors PVariantType.maybe_create: flatten nested variants, drop eql duplicates, collapse a single member.
|
||||
// Members are only known eql when their canonical text matches, so a choice it cannot decide is an error.
|
||||
func normalize(t *ptype) (*ptype, error) {
|
||||
switch t.name {
|
||||
case "Optional":
|
||||
if len(t.kids) == 0 {
|
||||
return t, nil
|
||||
}
|
||||
k, err := normalize(t.kids[0])
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &ptype{name: "Optional", canon: "Optional[" + k.canon + "]", kids: []*ptype{k}}, nil
|
||||
case "Variant":
|
||||
if len(t.kids) == 0 {
|
||||
return t, nil
|
||||
}
|
||||
var members []*ptype
|
||||
seen := map[string]bool{}
|
||||
for _, k := range t.kids {
|
||||
k, err := normalize(k)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
flat := []*ptype{k}
|
||||
if k.name == "Variant" && len(k.kids) > 0 {
|
||||
flat = k.kids
|
||||
}
|
||||
for _, m := range flat {
|
||||
if !seen[m.canon] {
|
||||
seen[m.canon] = true
|
||||
members = append(members, m)
|
||||
}
|
||||
}
|
||||
}
|
||||
if len(members) == 1 {
|
||||
return members[0], nil
|
||||
}
|
||||
for i, a := range members {
|
||||
for _, b := range members[i+1:] {
|
||||
if a.name == b.name && a.name != "" {
|
||||
return nil, fmt.Errorf("cannot tell whether %s and %s are the same type", a.canon, b.canon)
|
||||
}
|
||||
}
|
||||
}
|
||||
canon := make([]string, len(members))
|
||||
for i, m := range members {
|
||||
canon[i] = m.canon
|
||||
}
|
||||
return &ptype{name: "Variant", canon: "Variant[" + strings.Join(canon, ",") + "]", kids: members}, nil
|
||||
}
|
||||
return t, nil
|
||||
}
|
||||
|
||||
func (p *tparser) skip() {
|
||||
for p.pos < len(p.s) && strings.IndexByte(" \t\r\n", p.s[p.pos]) >= 0 {
|
||||
p.pos++
|
||||
}
|
||||
}
|
||||
|
||||
func (p *tparser) peek() byte {
|
||||
p.skip()
|
||||
if p.pos < len(p.s) {
|
||||
return p.s[p.pos]
|
||||
}
|
||||
return 0
|
||||
}
|
||||
|
||||
type targ struct {
|
||||
t *ptype
|
||||
text string
|
||||
kind byte // 't' type, 'i' integer, 'f' float, 'd' default, 's' string, 'w' word, 'r' regex
|
||||
}
|
||||
|
||||
func (p *tparser) typ(depth int) (*ptype, error) {
|
||||
if depth > maxDepth {
|
||||
return nil, fmt.Errorf("nesting deeper than %d: %w", maxDepth, errLimit)
|
||||
}
|
||||
p.skip()
|
||||
name := typeName.FindString(p.s[p.pos:])
|
||||
if name == "" || p.pos+len(name) < len(p.s) && p.s[p.pos+len(name)] == ':' {
|
||||
return nil, fmt.Errorf("unsupported type at offset %d", p.pos)
|
||||
}
|
||||
p.pos += len(name)
|
||||
var args []targ
|
||||
hasArgs := p.peek() == '['
|
||||
if hasArgs {
|
||||
p.pos++
|
||||
for {
|
||||
if p.peek() == ']' {
|
||||
p.pos++
|
||||
break
|
||||
}
|
||||
a, err := p.arg(depth)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
args = append(args, a)
|
||||
if c := p.peek(); c == ',' {
|
||||
p.pos++
|
||||
} else if c != ']' {
|
||||
return nil, fmt.Errorf("expected , or ] at offset %d", p.pos)
|
||||
}
|
||||
}
|
||||
if len(args) == 0 {
|
||||
return nil, fmt.Errorf("%s[] takes parameters", name)
|
||||
}
|
||||
}
|
||||
t := &ptype{name: name}
|
||||
kinds := ""
|
||||
texts := make([]string, len(args))
|
||||
for i, a := range args {
|
||||
kinds += string(a.kind)
|
||||
texts[i] = a.text
|
||||
if a.t != nil {
|
||||
t.kids = append(t.kids, a.t)
|
||||
}
|
||||
}
|
||||
t.canon = name
|
||||
if hasArgs {
|
||||
t.canon += "[" + strings.Join(texts, ",") + "]"
|
||||
}
|
||||
ok := false
|
||||
switch name {
|
||||
case "String":
|
||||
ok = rangeArgs(kinds, args, false)
|
||||
case "Integer":
|
||||
ok = rangeArgs(kinds, args, false)
|
||||
case "Float":
|
||||
ok = rangeArgs(kinds, args, true)
|
||||
case "Numeric", "Boolean":
|
||||
ok = !hasArgs
|
||||
case "Optional":
|
||||
ok = kinds == "" || kinds == "t" || kinds == "s"
|
||||
if kinds == "s" {
|
||||
t.kids = []*ptype{{name: "String", canon: "String[" + texts[0] + "]"}}
|
||||
}
|
||||
case "Variant":
|
||||
ok = !strings.ContainsFunc(kinds, func(r rune) bool { return r != 't' })
|
||||
case "Enum", "Pattern", "Array", "Hash", "Sensitive":
|
||||
t.name = ""
|
||||
switch name {
|
||||
case "Enum":
|
||||
ok = hasArgs && !strings.ContainsFunc(kinds, func(r rune) bool { return r != 's' && r != 'w' })
|
||||
case "Pattern":
|
||||
ok = hasArgs && !strings.ContainsFunc(kinds, func(r rune) bool { return r != 's' && r != 'r' })
|
||||
for i, a := range args {
|
||||
if a.kind == 's' && !rubyRegexp(unquote(texts[i])) {
|
||||
return nil, fmt.Errorf("unsupported regex %s", texts[i])
|
||||
}
|
||||
}
|
||||
case "Array":
|
||||
ok = kinds == "" || len(kinds) <= 3 && kinds[0] == 't' && rangeArgs(kinds[1:], args[1:], false)
|
||||
case "Hash":
|
||||
ok = kinds == "" || kinds == "tt" || len(kinds) == 4 && kinds[:2] == "tt" && rangeArgs(kinds[2:], args[2:], false)
|
||||
case "Sensitive":
|
||||
ok = kinds == "" || kinds == "t"
|
||||
}
|
||||
}
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("unsupported %s", t.canon)
|
||||
}
|
||||
return t, nil
|
||||
}
|
||||
|
||||
// rangeArgs accepts [], [min] and [min, max] of integers (or floats) and default, rejecting min > max as TypeParser does.
|
||||
func rangeArgs(kinds string, args []targ, float bool) bool {
|
||||
if len(kinds) > 2 || strings.ContainsFunc(kinds, func(r rune) bool { return r != 'i' && r != 'd' && (!float || r != 'f') }) {
|
||||
return false
|
||||
}
|
||||
if kinds != "ii" && kinds != "if" && kinds != "fi" && kinds != "ff" {
|
||||
return true
|
||||
}
|
||||
a, _, err1 := big.ParseFloat(args[0].text, 10, 256, big.ToNearestEven)
|
||||
b, _, err2 := big.ParseFloat(args[1].text, 10, 256, big.ToNearestEven)
|
||||
return err1 == nil && err2 == nil && a.Cmp(b) <= 0
|
||||
}
|
||||
|
||||
func (p *tparser) arg(depth int) (targ, error) {
|
||||
c := p.peek()
|
||||
switch {
|
||||
case c >= 'A' && c <= 'Z':
|
||||
t, err := p.typ(depth + 1)
|
||||
if err != nil {
|
||||
return targ{}, err
|
||||
}
|
||||
return targ{t: t, text: t.canon, kind: 't'}, nil
|
||||
case c == '-' || c >= '0' && c <= '9':
|
||||
neg := c == '-'
|
||||
if neg {
|
||||
p.pos++
|
||||
p.skip()
|
||||
}
|
||||
s := p.pos
|
||||
for p.pos < len(p.s) {
|
||||
c := p.s[p.pos]
|
||||
sign := c == '+' || c == '-'
|
||||
if strings.IndexByte("0123456789.eE_xXabcdefABCDEF", c) < 0 && (!sign || p.pos == s || p.s[p.pos-1] != 'e' && p.s[p.pos-1] != 'E') {
|
||||
break
|
||||
}
|
||||
p.pos++
|
||||
}
|
||||
text := p.s[s:p.pos]
|
||||
if neg {
|
||||
text = "-" + text
|
||||
}
|
||||
switch {
|
||||
case intLit.MatchString(strings.TrimPrefix(text, "-")):
|
||||
if _, err := strconv.ParseInt(text, 10, 64); err != nil {
|
||||
return targ{}, fmt.Errorf("unsupported integer %s", text)
|
||||
}
|
||||
return targ{text: text, kind: 'i'}, nil
|
||||
case floatLit.MatchString(strings.TrimPrefix(text, "-")):
|
||||
return targ{text: text, kind: 'f'}, nil
|
||||
}
|
||||
return targ{}, fmt.Errorf("unsupported number %s", text)
|
||||
case c == '\'':
|
||||
s := p.pos
|
||||
for p.pos++; p.pos < len(p.s) && p.s[p.pos] != '\''; p.pos++ {
|
||||
if p.s[p.pos] == '\\' {
|
||||
p.pos++
|
||||
}
|
||||
}
|
||||
if p.pos >= len(p.s) {
|
||||
return targ{}, fmt.Errorf("unterminated string")
|
||||
}
|
||||
p.pos++
|
||||
return targ{text: p.s[s:p.pos], kind: 's'}, nil
|
||||
case c == '/':
|
||||
s := p.pos
|
||||
for p.pos++; p.pos < len(p.s) && p.s[p.pos] != '/'; p.pos++ {
|
||||
if p.s[p.pos] == '\\' {
|
||||
p.pos++
|
||||
}
|
||||
}
|
||||
if p.pos >= len(p.s) {
|
||||
return targ{}, fmt.Errorf("unterminated regex")
|
||||
}
|
||||
p.pos++
|
||||
text := p.s[s:p.pos]
|
||||
if !rubyRegexp(strings.ReplaceAll(text[1:len(text)-1], `\/`, "/")) {
|
||||
return targ{}, fmt.Errorf("unsupported regex %s", text)
|
||||
}
|
||||
return targ{text: text, kind: 'r'}, nil
|
||||
case c >= 'a' && c <= 'z':
|
||||
s := p.pos
|
||||
for p.pos < len(p.s) && (isIdentChar(p.s[p.pos]) && p.s[p.pos] < 0x80) {
|
||||
p.pos++
|
||||
}
|
||||
w := p.s[s:p.pos]
|
||||
switch {
|
||||
case w == "default":
|
||||
return targ{text: w, kind: 'd'}, nil
|
||||
case enumWord.MatchString(w) && !puppetKws[w] && p.peek() != ':':
|
||||
return targ{text: "'" + w + "'", kind: 'w'}, nil
|
||||
}
|
||||
return targ{}, fmt.Errorf("unsupported word %s", w)
|
||||
}
|
||||
return targ{}, fmt.Errorf("unsupported parameter at offset %d", p.pos)
|
||||
}
|
||||
|
||||
func unquote(s string) string {
|
||||
return strings.NewReplacer(`\\`, `\`, `\'`, `'`).Replace(s[1 : len(s)-1])
|
||||
}
|
||||
|
||||
// rubyRegexp reports whether Ruby's Regexp.new surely accepts src: RE2 parses it and it avoids syntax the engines disagree on.
|
||||
func rubyRegexp(src string) bool {
|
||||
if reUnsafe.MatchString(src) {
|
||||
return false
|
||||
}
|
||||
_, err := syntax.Parse(src, syntax.Perl)
|
||||
return err == nil
|
||||
}
|
||||
@@ -0,0 +1,393 @@
|
||||
package gentypes
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"slices"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
"unicode/utf8"
|
||||
)
|
||||
|
||||
const rubySpace = " \t\r\n\f\v\x00"
|
||||
|
||||
func strip(s string) string { return strings.Trim(s, rubySpace) }
|
||||
|
||||
// scrub ports Puppet::Util::Docs.scrub: drop the least common indent (ignoring the first line) and trailing space.
|
||||
func scrub(text string) string {
|
||||
if !strings.Contains(strip(text), "\n") {
|
||||
return strip(text)
|
||||
}
|
||||
_, rest, _ := strings.Cut(text, "\n")
|
||||
indent, found := "", false
|
||||
for _, line := range strings.Split(rest, "\n") {
|
||||
n := len(line) - len(strings.TrimLeft(line, " \t"))
|
||||
if n == len(line) || strings.ContainsRune(rubySpace, rune(line[n])) {
|
||||
continue
|
||||
}
|
||||
if !found || line[:n] < indent {
|
||||
indent, found = line[:n], true
|
||||
}
|
||||
}
|
||||
lines := strings.Split(text, "\n")
|
||||
for i, line := range lines {
|
||||
if indent != "" {
|
||||
line = strings.TrimPrefix(line, indent)
|
||||
}
|
||||
lines[i] = strings.TrimRight(line, rubySpace)
|
||||
}
|
||||
return strings.TrimRight(strings.Join(lines, "\n"), rubySpace)
|
||||
}
|
||||
|
||||
// quote ports Puppet's StringConverter#puppet_quote.
|
||||
func quote(s string) string {
|
||||
for _, r := range s {
|
||||
if r < 0x20 {
|
||||
return doubleQuote(s)
|
||||
}
|
||||
}
|
||||
var b strings.Builder
|
||||
b.WriteByte('\'')
|
||||
escaped := false
|
||||
for _, r := range s {
|
||||
switch {
|
||||
case escaped:
|
||||
b.WriteByte('\\')
|
||||
b.WriteRune(r)
|
||||
escaped = false
|
||||
case r == '\'':
|
||||
b.WriteString(`\'`)
|
||||
case r == '\\':
|
||||
escaped = true
|
||||
default:
|
||||
b.WriteRune(r)
|
||||
}
|
||||
}
|
||||
if escaped {
|
||||
b.WriteByte('\\')
|
||||
}
|
||||
b.WriteByte('\'')
|
||||
return b.String()
|
||||
}
|
||||
|
||||
func doubleQuote(s string) string {
|
||||
var b strings.Builder
|
||||
b.WriteByte('"')
|
||||
for _, r := range s {
|
||||
switch r {
|
||||
case '\t':
|
||||
b.WriteString(`\t`)
|
||||
case '\n':
|
||||
b.WriteString(`\n`)
|
||||
case '\r':
|
||||
b.WriteString(`\r`)
|
||||
case '"':
|
||||
b.WriteString(`\"`)
|
||||
case '$':
|
||||
b.WriteString(`\$`)
|
||||
case '\\':
|
||||
b.WriteString(`\\`)
|
||||
default:
|
||||
if r < 0x20 {
|
||||
fmt.Fprintf(&b, `\u{%X}`, r)
|
||||
} else {
|
||||
b.WriteRune(r)
|
||||
}
|
||||
}
|
||||
}
|
||||
b.WriteByte('"')
|
||||
return b.String()
|
||||
}
|
||||
|
||||
// exprStr ports Ruby's rb_reg_expr_str: escape unescaped '/' and hex-escape non-printable ASCII.
|
||||
func exprStr(src string) string {
|
||||
var b strings.Builder
|
||||
for i := 0; i < len(src); i++ {
|
||||
switch c := src[i]; {
|
||||
case c == '\\' && i+1 < len(src):
|
||||
_, n := utf8.DecodeRuneInString(src[i+1:])
|
||||
b.WriteString(src[i : i+1+n])
|
||||
i += n
|
||||
case c == '/':
|
||||
b.WriteString(`\/`)
|
||||
case c < 0x80 && (c < 0x20 || c == 0x7f) && !strings.ContainsRune("\t\n\v\f\r", rune(c)):
|
||||
fmt.Fprintf(&b, `\x%02X`, c)
|
||||
default:
|
||||
b.WriteByte(c)
|
||||
}
|
||||
}
|
||||
return b.String()
|
||||
}
|
||||
|
||||
func (r regex) opts() (on, off string) {
|
||||
for _, f := range "mix" {
|
||||
if strings.ContainsRune(r.flags, f) {
|
||||
on += string(f)
|
||||
} else {
|
||||
off += string(f)
|
||||
}
|
||||
}
|
||||
return on, off
|
||||
}
|
||||
|
||||
// fixedEncoding reports whether Ruby marks the regex FIXEDENCODING, rejecting escapes Ruby rewrites or refuses.
|
||||
func (r regex) fixedEncoding() (bool, error) {
|
||||
fixed := false
|
||||
for i := 0; i < len(r.src); i++ {
|
||||
if r.src[i] >= 0x80 {
|
||||
fixed = true
|
||||
continue
|
||||
}
|
||||
if r.src[i] != '\\' || i+1 >= len(r.src) {
|
||||
continue
|
||||
}
|
||||
i++
|
||||
rest := r.src[i:]
|
||||
switch rest[0] {
|
||||
case 'p', 'P':
|
||||
fixed = true
|
||||
case 'u':
|
||||
var cps []string
|
||||
if len(rest) > 1 && rest[1] == '{' {
|
||||
end := strings.IndexByte(rest, '}')
|
||||
if end < 0 {
|
||||
return false, fmt.Errorf("regex /%s/: invalid \\u escape", r.src)
|
||||
}
|
||||
cps = strings.Fields(rest[2:end])
|
||||
} else if len(rest) >= 5 {
|
||||
cps = []string{rest[1:5]}
|
||||
}
|
||||
if len(cps) == 0 {
|
||||
return false, fmt.Errorf("regex /%s/: invalid \\u escape", r.src)
|
||||
}
|
||||
for _, h := range cps {
|
||||
v, err := strconv.ParseUint(h, 16, 32)
|
||||
if err != nil {
|
||||
return false, fmt.Errorf("regex /%s/: invalid \\u escape", r.src)
|
||||
}
|
||||
fixed = fixed || v >= 0x80
|
||||
}
|
||||
case 'x':
|
||||
if v, n := hexVal(rest[1:], 2); n > 0 && v >= 0x80 {
|
||||
return false, fmt.Errorf("regex /%s/: non-ASCII \\x escape is not supported", r.src)
|
||||
}
|
||||
case 'M', 'C', 'c':
|
||||
return false, fmt.Errorf("regex /%s/: \\%c escapes are not supported", r.src, rest[0])
|
||||
case '2', '3':
|
||||
if len(rest) >= 3 && strings.IndexByte("01234567", rest[1]) >= 0 && strings.IndexByte("01234567", rest[2]) >= 0 {
|
||||
return false, fmt.Errorf("regex /%s/: non-ASCII octal escape is not supported", r.src)
|
||||
}
|
||||
}
|
||||
}
|
||||
return fixed, nil
|
||||
}
|
||||
|
||||
// inspect renders Ruby's Regexp#inspect.
|
||||
func (r regex) inspect() string {
|
||||
on, _ := r.opts()
|
||||
return "/" + exprStr(r.src) + "/" + on
|
||||
}
|
||||
|
||||
// puppet ports Puppet's regexp_to_s_with_delimiters: inspect when options are 0, else /#{Regexp#to_s}/.
|
||||
func (r regex) puppet() (string, error) {
|
||||
if strings.ContainsAny(r.flags, "nesu") {
|
||||
return "", fmt.Errorf("regex /%s/%s: encoding flags are not supported", r.src, r.flags)
|
||||
}
|
||||
fixed, err := r.fixedEncoding()
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
on, off := r.opts()
|
||||
if on == "" && !fixed {
|
||||
return r.inspect(), nil
|
||||
}
|
||||
if strings.HasPrefix(r.src, "(?") {
|
||||
return "", fmt.Errorf("regex /%s/%s: leading inline group with options is not supported", r.src, r.flags)
|
||||
}
|
||||
if off != "" {
|
||||
off = "-" + off
|
||||
}
|
||||
return "/(?" + on + off + ":" + exprStr(r.src) + ")/", nil
|
||||
}
|
||||
|
||||
func (a *attr) puppetType() (string, error) {
|
||||
var strs, res []string
|
||||
for _, v := range a.values {
|
||||
if v.re != nil {
|
||||
s, err := v.re.puppet()
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
res = append(res, s)
|
||||
continue
|
||||
}
|
||||
strs = append(strs, quote(v.display()))
|
||||
for _, al := range v.aliases {
|
||||
strs = append(strs, quote(al))
|
||||
}
|
||||
}
|
||||
var parts []string
|
||||
if slices.Contains(strs, "'true'") || slices.Contains(strs, "'false'") {
|
||||
parts = append(parts, "Boolean")
|
||||
}
|
||||
if len(strs) > 0 {
|
||||
parts = append(parts, "Enum["+strings.Join(strs, ", ")+"]")
|
||||
}
|
||||
if len(res) > 0 {
|
||||
parts = append(parts, "Pattern["+strings.Join(res, ", ")+"]")
|
||||
}
|
||||
switch len(parts) {
|
||||
case 0:
|
||||
return "Any", nil
|
||||
case 1:
|
||||
return parts[0], nil
|
||||
}
|
||||
return "Variant[" + strings.Join(parts, ", ") + "]", nil
|
||||
}
|
||||
|
||||
func (v *value) display() string { return strings.TrimPrefix(v.name, "\xff") }
|
||||
|
||||
func (a *attr) fullDoc() string {
|
||||
if a.raw {
|
||||
return strip(a.doc)
|
||||
}
|
||||
doc := a.doc
|
||||
if doc == "" && a.defaults {
|
||||
doc = "The basic property that the resource should be in."
|
||||
}
|
||||
var vals strings.Builder
|
||||
if len(a.strs) > 0 {
|
||||
names := make([]string, len(a.strs))
|
||||
for i, v := range a.strs {
|
||||
names[i] = "`" + v.display() + "`"
|
||||
if len(v.aliases) > 0 {
|
||||
names[i] += " (also called `" + strings.Join(v.aliases, ", ") + "`)"
|
||||
}
|
||||
}
|
||||
vals.WriteString("Valid values are " + strings.Join(names, ", ") + ". ")
|
||||
}
|
||||
if len(a.res) > 0 {
|
||||
res := make([]string, len(a.res))
|
||||
for i, v := range a.res {
|
||||
res[i] = v.re.inspect()
|
||||
}
|
||||
vals.WriteString("Values can match `" + strings.Join(res, "`, `") + "`.")
|
||||
}
|
||||
doc = scrub(doc) + "\n\n" + vals.String()
|
||||
if len(a.features) > 0 {
|
||||
doc += "\n\nRequires features " + strings.Join(a.features, " ") + "."
|
||||
}
|
||||
return strip(doc)
|
||||
}
|
||||
|
||||
func providerParam(typ string, providers []string) *attr {
|
||||
doc := "The specific backend to use for this `" + typ + "`\nresource. You will seldom need to specify this --- OpenVox will usually\ndiscover the appropriate provider for your platform.Available providers are:\n\n"
|
||||
for _, p := range slices.Sorted(slices.Values(providers)) {
|
||||
doc += p + "\n: \n\n"
|
||||
}
|
||||
return &attr{name: "provider", doc: doc, raw: true}
|
||||
}
|
||||
|
||||
func writeDoc(b *strings.Builder, doc, prefix string) {
|
||||
if doc == "" {
|
||||
return
|
||||
}
|
||||
for _, line := range strings.Split(doc, "\n") {
|
||||
b.WriteString(prefix + line + "\n")
|
||||
}
|
||||
}
|
||||
|
||||
func writeAttrs(b *strings.Builder, attrs []*attr) error {
|
||||
b.WriteString(" [\n")
|
||||
for i, a := range attrs {
|
||||
typ, err := a.puppetType()
|
||||
if err != nil {
|
||||
return fmt.Errorf("attribute %s: %w", a.name, err)
|
||||
}
|
||||
writeDoc(b, a.fullDoc(), " # ")
|
||||
b.WriteString(" Puppet::Resource::Param(" + typ + ", " + quote(a.name))
|
||||
if a.namevar {
|
||||
b.WriteString(", true")
|
||||
}
|
||||
b.WriteString(")")
|
||||
if i+1 < len(attrs) {
|
||||
b.WriteString(",\n\n")
|
||||
}
|
||||
}
|
||||
b.WriteString("\n ],\n")
|
||||
return nil
|
||||
}
|
||||
|
||||
func (t *rtype) titlePatterns() ([]pattern, error) {
|
||||
if t.custom {
|
||||
return t.patterns, nil
|
||||
}
|
||||
var keys []string
|
||||
for _, a := range t.params {
|
||||
if a.namevar || a.name == "name" {
|
||||
keys = append(keys, a.name)
|
||||
}
|
||||
}
|
||||
switch len(keys) {
|
||||
case 0:
|
||||
return nil, nil
|
||||
case 1:
|
||||
return []pattern{{re: regex{"(.*)", "m"}, names: keys}}, nil
|
||||
}
|
||||
return nil, fmt.Errorf("you must specify title patterns when there are two or more key attributes")
|
||||
}
|
||||
|
||||
func render(t *rtype, providers []string, now time.Time) (string, error) {
|
||||
params := t.params
|
||||
if len(providers) > 0 && !t.rsapi && !t.hasParam("provider") {
|
||||
params = append(params[:len(params):len(params)], providerParam(t.name, providers))
|
||||
}
|
||||
pats, err := t.titlePatterns()
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
var b strings.Builder
|
||||
b.WriteString("# This file was automatically generated on " + now.Format("2006-01-02 15:04:05 -0700") + ".\n")
|
||||
b.WriteString("# Use the 'puppet generate types' command to regenerate this file.\n\n")
|
||||
writeDoc(&b, strip(scrub(t.doc)), "# ")
|
||||
b.WriteString("Puppet::Resource::ResourceType3.new(\n " + quote(t.name) + ",\n")
|
||||
if err := writeAttrs(&b, t.props); err != nil {
|
||||
return "", err
|
||||
}
|
||||
if err := writeAttrs(&b, params); err != nil {
|
||||
return "", err
|
||||
}
|
||||
b.WriteString(" {\n")
|
||||
var keys, lines []string
|
||||
for _, p := range pats {
|
||||
re, err := p.re.puppet()
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
names := make([]string, len(p.names))
|
||||
for i, n := range p.names {
|
||||
names[i] = quote(n)
|
||||
}
|
||||
line := " " + re + " => [" + strings.Join(names, ", ") + "]"
|
||||
if i := slices.Index(keys, re); i >= 0 {
|
||||
lines[i] = line
|
||||
continue
|
||||
}
|
||||
keys, lines = append(keys, re), append(lines, line)
|
||||
}
|
||||
b.WriteString(strings.Join(lines, ",\n"))
|
||||
if len(lines) > 0 {
|
||||
b.WriteString("\n")
|
||||
}
|
||||
b.WriteString(" },\n true,\n false)\n")
|
||||
return b.String(), nil
|
||||
}
|
||||
|
||||
func (t *rtype) hasParam(name string) bool {
|
||||
for _, a := range t.params {
|
||||
if a.name == name {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
@@ -0,0 +1 @@
|
||||
modulepath = external_modules:modules:$basemodulepath
|
||||
@@ -0,0 +1,178 @@
|
||||
Copyright 2013 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
|
||||
+2
@@ -0,0 +1,2 @@
|
||||
Puppet::Type.type(:alternative_entry).provide(:chkconfig) do
|
||||
end
|
||||
+2
@@ -0,0 +1,2 @@
|
||||
Puppet::Type.type(:alternative_entry).provide(:dpkg) do
|
||||
end
|
||||
+2
@@ -0,0 +1,2 @@
|
||||
Puppet::Type.type(:alternatives).provide(:chkconfig) do
|
||||
end
|
||||
+2
@@ -0,0 +1,2 @@
|
||||
Puppet::Type.type(:alternatives).provide(:dpkg) do
|
||||
end
|
||||
Vendored
+68
@@ -0,0 +1,68 @@
|
||||
# frozen_string_literal: true
|
||||
|
||||
Puppet::Type.newtype(:alternative_entry) do
|
||||
ensurable
|
||||
|
||||
newparam(:name) do
|
||||
desc 'The path to the actual alternative'
|
||||
|
||||
isnamevar
|
||||
|
||||
validate do |path|
|
||||
raise ArgumentError, 'path must be a fully qualified path' unless absolute_path? path
|
||||
end
|
||||
end
|
||||
|
||||
newparam(:altlink) do
|
||||
desc 'The name of the generic symlink for this alternative entry'
|
||||
|
||||
isnamevar
|
||||
|
||||
validate do |path|
|
||||
raise ArgumentError, 'path must be a fully qualified path' unless absolute_path? path
|
||||
end
|
||||
end
|
||||
|
||||
newproperty(:altlink_ro, readonly: true) do
|
||||
desc 'The name of the generic symlink for this alternative entry as parameter. This is readonly.'
|
||||
end
|
||||
|
||||
newproperty(:altname) do
|
||||
desc 'The name of symlink in the alternatives directory'
|
||||
end
|
||||
|
||||
newproperty(:priority) do
|
||||
desc 'The value of the priority of this alternative'
|
||||
|
||||
validate do |prio|
|
||||
Integer(prio)
|
||||
rescue StandardError
|
||||
raise ArgumentError, 'priority must be an integer'
|
||||
end
|
||||
end
|
||||
|
||||
def self.title_patterns
|
||||
[
|
||||
[
|
||||
%r{^([^:]+)$},
|
||||
[
|
||||
[:name]
|
||||
]
|
||||
],
|
||||
[
|
||||
%r{^(.*):([a-z]:(/|\\).*)$}i,
|
||||
[
|
||||
[:name],
|
||||
[:altlink]
|
||||
]
|
||||
],
|
||||
[
|
||||
%r{^(.*):(.*)$},
|
||||
[
|
||||
[:name],
|
||||
[:altlink]
|
||||
]
|
||||
]
|
||||
]
|
||||
end
|
||||
end
|
||||
Vendored
+45
@@ -0,0 +1,45 @@
|
||||
# frozen_string_literal: true
|
||||
|
||||
Puppet::Type.newtype(:alternatives) do
|
||||
feature :mode, 'The alternative can provide auto and manual modes'
|
||||
|
||||
newparam(:name, isnamevar: true) do
|
||||
desc 'The name of the alternative.'
|
||||
end
|
||||
|
||||
newproperty(:path) do
|
||||
desc 'The path of the desired source for the given alternative. On RedHat, a family can be specified instead'
|
||||
|
||||
def insync?(is)
|
||||
if absolute_path? should
|
||||
is == should
|
||||
else
|
||||
provider.family == should
|
||||
end
|
||||
end
|
||||
|
||||
validate do |path|
|
||||
raise ArgumentError, 'path must be a fully qualified path' unless (absolute_path? path) || (Facter.value('os.family') == 'RedHat')
|
||||
end
|
||||
end
|
||||
|
||||
newproperty(:mode, required_features: [:mode]) do
|
||||
desc 'Use the automatic option for this alternative'
|
||||
|
||||
newvalue('auto')
|
||||
newvalue('manual')
|
||||
end
|
||||
|
||||
validate do
|
||||
case self[:mode]
|
||||
when :auto
|
||||
raise Puppet::Error, "Mode cannot be 'auto' if a path is given" if self[:path]
|
||||
when :manual
|
||||
raise Puppet::Error, "Mode cannot be 'manual' without a path" unless self[:path]
|
||||
end
|
||||
end
|
||||
|
||||
autorequire(:alternative_entry) do
|
||||
self[:path]
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,203 @@
|
||||
Copyright 2014 Bodeco Inc
|
||||
|
||||
Apache License
|
||||
Version 2.0, January 2004
|
||||
http://www.apache.org/licenses/
|
||||
|
||||
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
||||
|
||||
1. Definitions.
|
||||
|
||||
"License" shall mean the terms and conditions for use, reproduction,
|
||||
and distribution as defined by Sections 1 through 9 of this document.
|
||||
|
||||
"Licensor" shall mean the copyright owner or entity authorized by
|
||||
the copyright owner that is granting the License.
|
||||
|
||||
"Legal Entity" shall mean the union of the acting entity and all
|
||||
other entities that control, are controlled by, or are under common
|
||||
control with that entity. For the purposes of this definition,
|
||||
"control" means (i) the power, direct or indirect, to cause the
|
||||
direction or management of such entity, whether by contract or
|
||||
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
||||
outstanding shares, or (iii) beneficial ownership of such entity.
|
||||
|
||||
"You" (or "Your") shall mean an individual or Legal Entity
|
||||
exercising permissions granted by this License.
|
||||
|
||||
"Source" form shall mean the preferred form for making modifications,
|
||||
including but not limited to software source code, documentation
|
||||
source, and configuration files.
|
||||
|
||||
"Object" form shall mean any form resulting from mechanical
|
||||
transformation or translation of a Source form, including but
|
||||
not limited to compiled object code, generated documentation,
|
||||
and conversions to other media types.
|
||||
|
||||
"Work" shall mean the work of authorship, whether in Source or
|
||||
Object form, made available under the License, as indicated by a
|
||||
copyright notice that is included in or attached to the work
|
||||
(an example is provided in the Appendix below).
|
||||
|
||||
"Derivative Works" shall mean any work, whether in Source or Object
|
||||
form, that is based on (or derived from) the Work and for which the
|
||||
editorial revisions, annotations, elaborations, or other modifications
|
||||
represent, as a whole, an original work of authorship. For the purposes
|
||||
of this License, Derivative Works shall not include works that remain
|
||||
separable from, or merely link (or bind by name) to the interfaces of,
|
||||
the Work and Derivative Works thereof.
|
||||
|
||||
"Contribution" shall mean any work of authorship, including
|
||||
the original version of the Work and any modifications or additions
|
||||
to that Work or Derivative Works thereof, that is intentionally
|
||||
submitted to Licensor for inclusion in the Work by the copyright owner
|
||||
or by an individual or Legal Entity authorized to submit on behalf of
|
||||
the copyright owner. For the purposes of this definition, "submitted"
|
||||
means any form of electronic, verbal, or written communication sent
|
||||
to the Licensor or its representatives, including but not limited to
|
||||
communication on electronic mailing lists, source code control systems,
|
||||
and issue tracking systems that are managed by, or on behalf of, the
|
||||
Licensor for the purpose of discussing and improving the Work, but
|
||||
excluding communication that is conspicuously marked or otherwise
|
||||
designated in writing by the copyright owner as "Not a Contribution."
|
||||
|
||||
"Contributor" shall mean Licensor and any individual or Legal Entity
|
||||
on behalf of whom a Contribution has been received by Licensor and
|
||||
subsequently incorporated within the Work.
|
||||
|
||||
2. Grant of Copyright License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
copyright license to reproduce, prepare Derivative Works of,
|
||||
publicly display, publicly perform, sublicense, and distribute the
|
||||
Work and such Derivative Works in Source or Object form.
|
||||
|
||||
3. Grant of Patent License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
(except as stated in this section) patent license to make, have made,
|
||||
use, offer to sell, sell, import, and otherwise transfer the Work,
|
||||
where such license applies only to those patent claims licensable
|
||||
by such Contributor that are necessarily infringed by their
|
||||
Contribution(s) alone or by combination of their Contribution(s)
|
||||
with the Work to which such Contribution(s) was submitted. If You
|
||||
institute patent litigation against any entity (including a
|
||||
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
||||
or a Contribution incorporated within the Work constitutes direct
|
||||
or contributory patent infringement, then any patent licenses
|
||||
granted to You under this License for that Work shall terminate
|
||||
as of the date such litigation is filed.
|
||||
|
||||
4. Redistribution. You may reproduce and distribute copies of the
|
||||
Work or Derivative Works thereof in any medium, with or without
|
||||
modifications, and in Source or Object form, provided that You
|
||||
meet the following conditions:
|
||||
|
||||
(a) You must give any other recipients of the Work or
|
||||
Derivative Works a copy of this License; and
|
||||
|
||||
(b) You must cause any modified files to carry prominent notices
|
||||
stating that You changed the files; and
|
||||
|
||||
(c) You must retain, in the Source form of any Derivative Works
|
||||
that You distribute, all copyright, patent, trademark, and
|
||||
attribution notices from the Source form of the Work,
|
||||
excluding those notices that do not pertain to any part of
|
||||
the Derivative Works; and
|
||||
|
||||
(d) If the Work includes a "NOTICE" text file as part of its
|
||||
distribution, then any Derivative Works that You distribute must
|
||||
include a readable copy of the attribution notices contained
|
||||
within such NOTICE file, excluding those notices that do not
|
||||
pertain to any part of the Derivative Works, in at least one
|
||||
of the following places: within a NOTICE text file distributed
|
||||
as part of the Derivative Works; within the Source form or
|
||||
documentation, if provided along with the Derivative Works; or,
|
||||
within a display generated by the Derivative Works, if and
|
||||
wherever such third-party notices normally appear. The contents
|
||||
of the NOTICE file are for informational purposes only and
|
||||
do not modify the License. You may add Your own attribution
|
||||
notices within Derivative Works that You distribute, alongside
|
||||
or as an addendum to the NOTICE text from the Work, provided
|
||||
that such additional attribution notices cannot be construed
|
||||
as modifying the License.
|
||||
|
||||
You may add Your own copyright statement to Your modifications and
|
||||
may provide additional or different license terms and conditions
|
||||
for use, reproduction, or distribution of Your modifications, or
|
||||
for any such Derivative Works as a whole, provided Your use,
|
||||
reproduction, and distribution of the Work otherwise complies with
|
||||
the conditions stated in this License.
|
||||
|
||||
5. Submission of Contributions. Unless You explicitly state otherwise,
|
||||
any Contribution intentionally submitted for inclusion in the Work
|
||||
by You to the Licensor shall be under the terms and conditions of
|
||||
this License, without any additional terms or conditions.
|
||||
Notwithstanding the above, nothing herein shall supersede or modify
|
||||
the terms of any separate license agreement you may have executed
|
||||
with Licensor regarding such Contributions.
|
||||
|
||||
6. Trademarks. This License does not grant permission to use the trade
|
||||
names, trademarks, service marks, or product names of the Licensor,
|
||||
except as required for reasonable and customary use in describing the
|
||||
origin of the Work and reproducing the content of the NOTICE file.
|
||||
|
||||
7. Disclaimer of Warranty. Unless required by applicable law or
|
||||
agreed to in writing, Licensor provides the Work (and each
|
||||
Contributor provides its Contributions) on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
||||
implied, including, without limitation, any warranties or conditions
|
||||
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
||||
PARTICULAR PURPOSE. You are solely responsible for determining the
|
||||
appropriateness of using or redistributing the Work and assume any
|
||||
risks associated with Your exercise of permissions under this License.
|
||||
|
||||
8. Limitation of Liability. In no event and under no legal theory,
|
||||
whether in tort (including negligence), contract, or otherwise,
|
||||
unless required by applicable law (such as deliberate and grossly
|
||||
negligent acts) or agreed to in writing, shall any Contributor be
|
||||
liable to You for damages, including any direct, indirect, special,
|
||||
incidental, or consequential damages of any character arising as a
|
||||
result of this License or out of the use or inability to use the
|
||||
Work (including but not limited to damages for loss of goodwill,
|
||||
work stoppage, computer failure or malfunction, or any and all
|
||||
other commercial damages or losses), even if such Contributor
|
||||
has been advised of the possibility of such damages.
|
||||
|
||||
9. Accepting Warranty or Additional Liability. While redistributing
|
||||
the Work or Derivative Works thereof, You may choose to offer,
|
||||
and charge a fee for, acceptance of support, warranty, indemnity,
|
||||
or other liability obligations and/or rights consistent with this
|
||||
License. However, in accepting such obligations, You may act only
|
||||
on Your own behalf and on Your sole responsibility, not on behalf
|
||||
of any other Contributor, and only if You agree to indemnify,
|
||||
defend, and hold each Contributor harmless for any liability
|
||||
incurred by, or claims asserted against, such Contributor by reason
|
||||
of your accepting any such warranty or additional liability.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
APPENDIX: How to apply the Apache License to your work.
|
||||
|
||||
To apply the Apache License to your work, attach the following
|
||||
boilerplate notice, with the fields enclosed by brackets "[]"
|
||||
replaced with your own identifying information. (Don't include
|
||||
the brackets!) The text should be enclosed in the appropriate
|
||||
comment syntax for the file format. We also recommend that a
|
||||
file or class name and description of purpose be included on the
|
||||
same "printed page" as the copyright notice for easier
|
||||
identification within third-party archives.
|
||||
|
||||
Copyright [yyyy] [name of copyright owner]
|
||||
|
||||
Licensed under the Apache License, Version 2.0 (the "License");
|
||||
you may not use this file except in compliance with the License.
|
||||
You may obtain a copy of the License at
|
||||
|
||||
http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
||||
Unless required by applicable law or agreed to in writing, software
|
||||
distributed under the License is distributed on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
See the License for the specific language governing permissions and
|
||||
limitations under the License.
|
||||
Vendored
+2
@@ -0,0 +1,2 @@
|
||||
Puppet::Type.type(:archive).provide(:curl) do
|
||||
end
|
||||
Vendored
+2
@@ -0,0 +1,2 @@
|
||||
Puppet::Type.type(:archive).provide(:ruby) do
|
||||
end
|
||||
Vendored
+2
@@ -0,0 +1,2 @@
|
||||
Puppet::Type.type(:archive).provide(:wget) do
|
||||
end
|
||||
+283
@@ -0,0 +1,283 @@
|
||||
# frozen_string_literal: true
|
||||
|
||||
require 'pathname'
|
||||
require 'uri'
|
||||
require 'puppet/util'
|
||||
require 'puppet/parameter/boolean'
|
||||
|
||||
Puppet::Type.newtype(:archive) do
|
||||
@doc = 'Manage archive file download, extraction, and cleanup.'
|
||||
|
||||
ensurable do
|
||||
desc 'whether archive file should be present/absent (default: present)'
|
||||
|
||||
newvalue(:present) do
|
||||
provider.create
|
||||
end
|
||||
|
||||
newvalue(:absent) do
|
||||
provider.destroy
|
||||
end
|
||||
|
||||
defaultto(:present)
|
||||
|
||||
# The following changes allows us to notify if the resource is being replaced
|
||||
def is_to_s(value)
|
||||
return "(#{resource[:checksum_type]})#{provider.archive_checksum}" if provider.archive_checksum
|
||||
|
||||
super
|
||||
end
|
||||
|
||||
def should_to_s(value)
|
||||
return "(#{resource[:checksum_type]})#{resource[:checksum]}" if provider.archive_checksum
|
||||
|
||||
super
|
||||
end
|
||||
|
||||
def change_to_s(currentvalue, newvalue)
|
||||
if currentvalue == :absent || currentvalue.nil?
|
||||
extract = resource[:extract] == :true ? "and extracted in #{resource[:extract_path]}" : ''
|
||||
cleanup = resource[:cleanup] == :true ? 'with cleanup' : 'without cleanup'
|
||||
|
||||
if provider.archive_checksum
|
||||
"replace archive: #{provider.archive_filepath} from #{is_to_s(currentvalue)} to #{should_to_s(newvalue)}"
|
||||
else
|
||||
"download archive from #{resource[:source]} to #{provider.archive_filepath} #{extract} #{cleanup}"
|
||||
end
|
||||
elsif newvalue == :absent
|
||||
"remove archive: #{provider.archive_filepath} "
|
||||
else
|
||||
super
|
||||
end
|
||||
rescue StandardError
|
||||
super
|
||||
end
|
||||
end
|
||||
|
||||
newparam(:path, namevar: true) do
|
||||
desc 'namevar, archive file fully qualified file path.'
|
||||
validate do |value|
|
||||
raise ArgumentError, "archive path must be absolute: #{value}" unless Puppet::Util.absolute_path? value
|
||||
end
|
||||
end
|
||||
|
||||
newparam(:filename) do
|
||||
desc 'archive file name (derived from path).'
|
||||
end
|
||||
|
||||
newparam(:extract) do
|
||||
desc 'whether archive will be extracted after download (true|false).'
|
||||
newvalues(:true, :false)
|
||||
defaultto(:false)
|
||||
end
|
||||
|
||||
newparam(:extract_path) do
|
||||
desc 'target folder path to extract archive.'
|
||||
validate do |value|
|
||||
raise ArgumentError, "archive extract_path must be absolute: #{value}" unless Puppet::Util.absolute_path? value
|
||||
end
|
||||
end
|
||||
newparam(:target) do
|
||||
desc 'target folder path to extract archive. (this parameter is for camptocamp/archive compatibility)'
|
||||
validate do |value|
|
||||
raise ArgumentError, "archive extract_path must be absolute: #{value}" unless Puppet::Util.absolute_path? value
|
||||
end
|
||||
munge do |val|
|
||||
resource[:extract_path] = val
|
||||
end
|
||||
end
|
||||
|
||||
newparam(:extract_command) do
|
||||
desc "custom extraction command ('tar xvf example.tar.gz'), also support sprintf format ('tar xvf %s') which will be processed with the filename: sprintf('tar xvf %s', filename)"
|
||||
end
|
||||
|
||||
newparam(:temp_dir) do
|
||||
desc 'Specify an alternative temporary directory to use for copying files, if unset then the operating system default will be used.'
|
||||
validate do |value|
|
||||
raise ArgumentError, "Invalid temp_dir #{value}" unless Puppet::Util.absolute_path?(value)
|
||||
end
|
||||
end
|
||||
|
||||
newparam(:extract_flags) do
|
||||
desc "custom extraction options, this replaces the default flags. A string such as 'xvf' for a tar file would replace the default xf flag. A hash is useful when custom flags are needed for different platforms. {'tar' => 'xzf', '7z' => 'x -aot'}."
|
||||
defaultto(:undef)
|
||||
end
|
||||
|
||||
newproperty(:creates) do
|
||||
desc 'if file/directory exists, will not download/extract archive.'
|
||||
|
||||
def should_to_s(value)
|
||||
"extracting in #{resource[:extract_path]} to create #{value}"
|
||||
end
|
||||
end
|
||||
|
||||
newparam(:cleanup) do
|
||||
desc 'whether archive file will be removed after extraction (true|false).'
|
||||
newvalues(:true, :false)
|
||||
defaultto(:true)
|
||||
end
|
||||
|
||||
newparam(:source) do
|
||||
desc 'archive file source, supports puppet|http|https|ftp|file|s3|gs uri.'
|
||||
validate do |value|
|
||||
raise ArgumentError, "invalid source url: #{value}" unless value =~ %r{puppet|http|https|ftp|file|s3|gs} || Puppet::Util.absolute_path?(value)
|
||||
end
|
||||
end
|
||||
|
||||
newparam(:url) do
|
||||
desc 'archive file source, supports http|https|ftp|file uri.
|
||||
(for camptocamp/archive compatibility)'
|
||||
validate do |value|
|
||||
raise ArgumentError, "invalid source url: #{value}" unless value =~ %r{http|https|file|ftp}
|
||||
end
|
||||
munge do |val|
|
||||
resource[:source] = val
|
||||
end
|
||||
end
|
||||
|
||||
newparam(:cookie) do
|
||||
desc 'archive file download cookie.'
|
||||
end
|
||||
|
||||
newparam(:checksum) do
|
||||
desc 'archive file checksum (match checksum_type).'
|
||||
newvalues(%r{\b[0-9a-f]{5,128}\b}, :true, :false, :undef, nil, '')
|
||||
munge do |val|
|
||||
if val.nil? || val.empty? || val == :undef
|
||||
:false
|
||||
elsif %i[true false].include? val
|
||||
resource[:checksum_verify] = val
|
||||
else
|
||||
val
|
||||
end
|
||||
end
|
||||
end
|
||||
newparam(:digest_string) do
|
||||
desc 'archive file checksum (match checksum_type)
|
||||
(this parameter is for camptocamp/archive compatibility).'
|
||||
newvalues(%r{\b[0-9a-f]{5,128}\b})
|
||||
munge do |val|
|
||||
if !val.nil? && !val.empty?
|
||||
resource[:checksum] = val
|
||||
else
|
||||
val
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
newparam(:checksum_url) do
|
||||
desc 'archive file checksum source (instead of specifying checksum)'
|
||||
end
|
||||
newparam(:digest_url) do
|
||||
desc 'archive file checksum source (instead of specifying checksum)
|
||||
(this parameter is for camptocamp/archive compatibility)'
|
||||
munge do |val|
|
||||
resource[:checksum_url] = val
|
||||
end
|
||||
end
|
||||
|
||||
newparam(:checksum_type) do
|
||||
desc 'archive file checksum type (none|md5|sha1|sha2|sha256|sha384|sha512).'
|
||||
newvalues(:none, :md5, :sha1, :sha2, :sha256, :sha384, :sha512)
|
||||
defaultto(:none)
|
||||
end
|
||||
newparam(:digest_type) do
|
||||
desc 'archive file checksum type (none|md5|sha1|sha2|sha256|sha384|sha512)
|
||||
(this parameter is camptocamp/archive compatibility).'
|
||||
newvalues(:none, :md5, :sha1, :sha2, :sha256, :sha384, :sha512)
|
||||
munge do |val|
|
||||
resource[:checksum_type] = val
|
||||
end
|
||||
end
|
||||
|
||||
newparam(:checksum_verify) do
|
||||
desc 'whether checksum wil be verified (true|false).'
|
||||
newvalues(:true, :false)
|
||||
defaultto(:true)
|
||||
end
|
||||
|
||||
newparam(:username) do
|
||||
desc 'username to download source file.'
|
||||
end
|
||||
|
||||
newparam(:password) do
|
||||
desc 'password to download source file.'
|
||||
end
|
||||
|
||||
newparam(:headers) do
|
||||
desc 'optional header(s) to pass.'
|
||||
|
||||
validate do |val|
|
||||
raise ArgumentError, "headers must be an array: #{val}" unless val.is_a?(Array)
|
||||
end
|
||||
end
|
||||
|
||||
newparam(:user) do
|
||||
desc 'extract command user (using this option will configure the archive file permission to 0644 so the user can read the file).'
|
||||
end
|
||||
|
||||
newparam(:group) do
|
||||
desc 'extract command group (using this option will configure the archive file permisison to 0644 so the user can read the file).'
|
||||
end
|
||||
|
||||
newparam(:proxy_type) do
|
||||
desc 'proxy type (none|ftp|http|https)'
|
||||
newvalues(:none, :ftp, :http, :https)
|
||||
end
|
||||
|
||||
newparam(:proxy_server) do
|
||||
desc 'proxy address to use when accessing source'
|
||||
end
|
||||
|
||||
newparam(:allow_insecure, boolean: true, parent: Puppet::Parameter::Boolean) do
|
||||
desc 'ignore HTTPS certificate errors'
|
||||
defaultto :false
|
||||
end
|
||||
|
||||
newparam(:download_options) do
|
||||
desc 'provider download options (affects curl, wget, gs, and only s3 downloads for ruby provider)'
|
||||
|
||||
validate do |val|
|
||||
raise ArgumentError, "download_options should be String or Array: #{val}" unless val.is_a?(String) || val.is_a?(Array)
|
||||
end
|
||||
|
||||
munge do |val|
|
||||
case val
|
||||
when String
|
||||
[val]
|
||||
else
|
||||
val
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
autorequire(:file) do
|
||||
[
|
||||
Pathname.new(self[:path]).parent.to_s,
|
||||
self[:extract_path],
|
||||
'/root/.aws/config',
|
||||
'/root/.aws/credentials'
|
||||
].compact
|
||||
end
|
||||
|
||||
autorequire(:exec) do
|
||||
['install_aws_cli']
|
||||
end
|
||||
|
||||
autorequire(:exec) do
|
||||
['install_gsutil']
|
||||
end
|
||||
|
||||
validate do
|
||||
filepath = Pathname.new(self[:path])
|
||||
self[:filename] = filepath.basename.to_s
|
||||
raise ArgumentError, "invalid parameter: url (#{self[:url]}) and source (#{self[:source]}) are mutually exclusive." if !self[:source].nil? && !self[:url].nil? && self[:source] != self[:url]
|
||||
raise ArgumentError, "invalid parameter: checksum_url (#{self[:checksum_url]}) and digest_url (#{self[:digest_url]}) are mutually exclusive." if !self[:checksum_url].nil? && !self[:digest_url].nil? && self[:checksum_url] != self[:digest_url]
|
||||
|
||||
if self[:proxy_server]
|
||||
self[:proxy_type] ||= URI(self[:proxy_server]).scheme.to_sym
|
||||
else
|
||||
self[:proxy_type] = :none
|
||||
end
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,202 @@
|
||||
|
||||
Apache License
|
||||
Version 2.0, January 2004
|
||||
http://www.apache.org/licenses/
|
||||
|
||||
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
||||
|
||||
1. Definitions.
|
||||
|
||||
"License" shall mean the terms and conditions for use, reproduction,
|
||||
and distribution as defined by Sections 1 through 9 of this document.
|
||||
|
||||
"Licensor" shall mean the copyright owner or entity authorized by
|
||||
the copyright owner that is granting the License.
|
||||
|
||||
"Legal Entity" shall mean the union of the acting entity and all
|
||||
other entities that control, are controlled by, or are under common
|
||||
control with that entity. For the purposes of this definition,
|
||||
"control" means (i) the power, direct or indirect, to cause the
|
||||
direction or management of such entity, whether by contract or
|
||||
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
||||
outstanding shares, or (iii) beneficial ownership of such entity.
|
||||
|
||||
"You" (or "Your") shall mean an individual or Legal Entity
|
||||
exercising permissions granted by this License.
|
||||
|
||||
"Source" form shall mean the preferred form for making modifications,
|
||||
including but not limited to software source code, documentation
|
||||
source, and configuration files.
|
||||
|
||||
"Object" form shall mean any form resulting from mechanical
|
||||
transformation or translation of a Source form, including but
|
||||
not limited to compiled object code, generated documentation,
|
||||
and conversions to other media types.
|
||||
|
||||
"Work" shall mean the work of authorship, whether in Source or
|
||||
Object form, made available under the License, as indicated by a
|
||||
copyright notice that is included in or attached to the work
|
||||
(an example is provided in the Appendix below).
|
||||
|
||||
"Derivative Works" shall mean any work, whether in Source or Object
|
||||
form, that is based on (or derived from) the Work and for which the
|
||||
editorial revisions, annotations, elaborations, or other modifications
|
||||
represent, as a whole, an original work of authorship. For the purposes
|
||||
of this License, Derivative Works shall not include works that remain
|
||||
separable from, or merely link (or bind by name) to the interfaces of,
|
||||
the Work and Derivative Works thereof.
|
||||
|
||||
"Contribution" shall mean any work of authorship, including
|
||||
the original version of the Work and any modifications or additions
|
||||
to that Work or Derivative Works thereof, that is intentionally
|
||||
submitted to Licensor for inclusion in the Work by the copyright owner
|
||||
or by an individual or Legal Entity authorized to submit on behalf of
|
||||
the copyright owner. For the purposes of this definition, "submitted"
|
||||
means any form of electronic, verbal, or written communication sent
|
||||
to the Licensor or its representatives, including but not limited to
|
||||
communication on electronic mailing lists, source code control systems,
|
||||
and issue tracking systems that are managed by, or on behalf of, the
|
||||
Licensor for the purpose of discussing and improving the Work, but
|
||||
excluding communication that is conspicuously marked or otherwise
|
||||
designated in writing by the copyright owner as "Not a Contribution."
|
||||
|
||||
"Contributor" shall mean Licensor and any individual or Legal Entity
|
||||
on behalf of whom a Contribution has been received by Licensor and
|
||||
subsequently incorporated within the Work.
|
||||
|
||||
2. Grant of Copyright License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
copyright license to reproduce, prepare Derivative Works of,
|
||||
publicly display, publicly perform, sublicense, and distribute the
|
||||
Work and such Derivative Works in Source or Object form.
|
||||
|
||||
3. Grant of Patent License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
(except as stated in this section) patent license to make, have made,
|
||||
use, offer to sell, sell, import, and otherwise transfer the Work,
|
||||
where such license applies only to those patent claims licensable
|
||||
by such Contributor that are necessarily infringed by their
|
||||
Contribution(s) alone or by combination of their Contribution(s)
|
||||
with the Work to which such Contribution(s) was submitted. If You
|
||||
institute patent litigation against any entity (including a
|
||||
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
||||
or a Contribution incorporated within the Work constitutes direct
|
||||
or contributory patent infringement, then any patent licenses
|
||||
granted to You under this License for that Work shall terminate
|
||||
as of the date such litigation is filed.
|
||||
|
||||
4. Redistribution. You may reproduce and distribute copies of the
|
||||
Work or Derivative Works thereof in any medium, with or without
|
||||
modifications, and in Source or Object form, provided that You
|
||||
meet the following conditions:
|
||||
|
||||
(a) You must give any other recipients of the Work or
|
||||
Derivative Works a copy of this License; and
|
||||
|
||||
(b) You must cause any modified files to carry prominent notices
|
||||
stating that You changed the files; and
|
||||
|
||||
(c) You must retain, in the Source form of any Derivative Works
|
||||
that You distribute, all copyright, patent, trademark, and
|
||||
attribution notices from the Source form of the Work,
|
||||
excluding those notices that do not pertain to any part of
|
||||
the Derivative Works; and
|
||||
|
||||
(d) If the Work includes a "NOTICE" text file as part of its
|
||||
distribution, then any Derivative Works that You distribute must
|
||||
include a readable copy of the attribution notices contained
|
||||
within such NOTICE file, excluding those notices that do not
|
||||
pertain to any part of the Derivative Works, in at least one
|
||||
of the following places: within a NOTICE text file distributed
|
||||
as part of the Derivative Works; within the Source form or
|
||||
documentation, if provided along with the Derivative Works; or,
|
||||
within a display generated by the Derivative Works, if and
|
||||
wherever such third-party notices normally appear. The contents
|
||||
of the NOTICE file are for informational purposes only and
|
||||
do not modify the License. You may add Your own attribution
|
||||
notices within Derivative Works that You distribute, alongside
|
||||
or as an addendum to the NOTICE text from the Work, provided
|
||||
that such additional attribution notices cannot be construed
|
||||
as modifying the License.
|
||||
|
||||
You may add Your own copyright statement to Your modifications and
|
||||
may provide additional or different license terms and conditions
|
||||
for use, reproduction, or distribution of Your modifications, or
|
||||
for any such Derivative Works as a whole, provided Your use,
|
||||
reproduction, and distribution of the Work otherwise complies with
|
||||
the conditions stated in this License.
|
||||
|
||||
5. Submission of Contributions. Unless You explicitly state otherwise,
|
||||
any Contribution intentionally submitted for inclusion in the Work
|
||||
by You to the Licensor shall be under the terms and conditions of
|
||||
this License, without any additional terms or conditions.
|
||||
Notwithstanding the above, nothing herein shall supersede or modify
|
||||
the terms of any separate license agreement you may have executed
|
||||
with Licensor regarding such Contributions.
|
||||
|
||||
6. Trademarks. This License does not grant permission to use the trade
|
||||
names, trademarks, service marks, or product names of the Licensor,
|
||||
except as required for reasonable and customary use in describing the
|
||||
origin of the Work and reproducing the content of the NOTICE file.
|
||||
|
||||
7. Disclaimer of Warranty. Unless required by applicable law or
|
||||
agreed to in writing, Licensor provides the Work (and each
|
||||
Contributor provides its Contributions) on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
||||
implied, including, without limitation, any warranties or conditions
|
||||
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
||||
PARTICULAR PURPOSE. You are solely responsible for determining the
|
||||
appropriateness of using or redistributing the Work and assume any
|
||||
risks associated with Your exercise of permissions under this License.
|
||||
|
||||
8. Limitation of Liability. In no event and under no legal theory,
|
||||
whether in tort (including negligence), contract, or otherwise,
|
||||
unless required by applicable law (such as deliberate and grossly
|
||||
negligent acts) or agreed to in writing, shall any Contributor be
|
||||
liable to You for damages, including any direct, indirect, special,
|
||||
incidental, or consequential damages of any character arising as a
|
||||
result of this License or out of the use or inability to use the
|
||||
Work (including but not limited to damages for loss of goodwill,
|
||||
work stoppage, computer failure or malfunction, or any and all
|
||||
other commercial damages or losses), even if such Contributor
|
||||
has been advised of the possibility of such damages.
|
||||
|
||||
9. Accepting Warranty or Additional Liability. While redistributing
|
||||
the Work or Derivative Works thereof, You may choose to offer,
|
||||
and charge a fee for, acceptance of support, warranty, indemnity,
|
||||
or other liability obligations and/or rights consistent with this
|
||||
License. However, in accepting such obligations, You may act only
|
||||
on Your own behalf and on Your sole responsibility, not on behalf
|
||||
of any other Contributor, and only if You agree to indemnify,
|
||||
defend, and hold each Contributor harmless for any liability
|
||||
incurred by, or claims asserted against, such Contributor by reason
|
||||
of your accepting any such warranty or additional liability.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
APPENDIX: How to apply the Apache License to your work.
|
||||
|
||||
To apply the Apache License to your work, attach the following
|
||||
boilerplate notice, with the fields enclosed by brackets "[]"
|
||||
replaced with your own identifying information. (Don't include
|
||||
the brackets!) The text should be enclosed in the appropriate
|
||||
comment syntax for the file format. We also recommend that a
|
||||
file or class name and description of purpose be included on the
|
||||
same "printed page" as the copyright notice for easier
|
||||
identification within third-party archives.
|
||||
|
||||
Copyright [yyyy] [name of copyright owner]
|
||||
|
||||
Licensed under the Apache License, Version 2.0 (the "License");
|
||||
you may not use this file except in compliance with the License.
|
||||
You may obtain a copy of the License at
|
||||
|
||||
http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
||||
Unless required by applicable law or agreed to in writing, software
|
||||
distributed under the License is distributed on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
See the License for the specific language governing permissions and
|
||||
limitations under the License.
|
||||
@@ -0,0 +1,15 @@
|
||||
Puppet Module - puppetlabs-concat
|
||||
|
||||
Copyright 2018 Puppet, Inc.
|
||||
|
||||
Licensed under the Apache License, Version 2.0 (the "License");
|
||||
you may not use this file except in compliance with the License.
|
||||
You may obtain a copy of the License at
|
||||
|
||||
http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
||||
Unless required by applicable law or agreed to in writing, software
|
||||
distributed under the License is distributed on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
See the License for the specific language governing permissions and
|
||||
limitations under the License.
|
||||
+362
@@ -0,0 +1,362 @@
|
||||
# frozen_string_literal: true
|
||||
|
||||
require 'puppet/type/file/owner'
|
||||
require 'puppet/type/file/group'
|
||||
require 'puppet/type/file/mode'
|
||||
require 'puppet/util/checksums'
|
||||
|
||||
Puppet::Type.newtype(:concat_file) do
|
||||
@doc = <<-DOC
|
||||
@summary
|
||||
Generates a file with content from fragments sharing a common unique tag.
|
||||
|
||||
@example
|
||||
Concat_fragment <<| tag == 'unique_tag' |>>
|
||||
|
||||
concat_file { '/tmp/file':
|
||||
tag => 'unique_tag', # Optional. Default to undef
|
||||
path => '/tmp/file', # Optional. If given it overrides the resource name
|
||||
owner => 'root', # Optional. Default to undef
|
||||
group => 'root', # Optional. Default to undef
|
||||
mode => '0644' # Optional. Default to undef
|
||||
order => 'numeric' # Optional, Default to 'numeric'
|
||||
ensure_newline => false # Optional, Defaults to false
|
||||
}
|
||||
DOC
|
||||
|
||||
ensurable do
|
||||
desc <<-DOC
|
||||
Specifies whether the destination file should exist. Setting to 'absent' tells Puppet to delete the destination file if it exists, and
|
||||
negates the effect of any other parameters.
|
||||
DOC
|
||||
|
||||
defaultvalues
|
||||
|
||||
defaultto { :present }
|
||||
end
|
||||
|
||||
def exists?
|
||||
self[:ensure] == :present
|
||||
end
|
||||
|
||||
newparam(:tag) do
|
||||
desc 'Required. Specifies a unique tag reference to collect all concat_fragments with the same tag.'
|
||||
end
|
||||
|
||||
newparam(:path, namevar: true) do
|
||||
desc <<-DOC
|
||||
Specifies a destination file for the combined fragments. Valid options: a string containing an absolute path. Default value: the
|
||||
title of your declared resource.
|
||||
DOC
|
||||
|
||||
validate do |value|
|
||||
unless Puppet::Util.absolute_path?(value, :posix) || Puppet::Util.absolute_path?(value, :windows)
|
||||
raise ArgumentError, _("File paths must be fully qualified, not '%{_value}'") % { _value: value }
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
newparam(:owner, parent: Puppet::Type::File::Owner) do
|
||||
desc <<-DOC
|
||||
Specifies the owner of the destination file. Valid options: a string containing a username or integer containing a uid.
|
||||
DOC
|
||||
end
|
||||
|
||||
newparam(:group, parent: Puppet::Type::File::Group) do
|
||||
desc <<-DOC
|
||||
Specifies a permissions group for the destination file. Valid options: a string containing a group name or integer containing a
|
||||
gid.
|
||||
DOC
|
||||
end
|
||||
|
||||
newparam(:mode, parent: Puppet::Type::File::Mode) do
|
||||
desc <<-DOC
|
||||
Specifies the permissions mode of the destination file. Valid options: a string containing a permission mode value in octal notation.
|
||||
DOC
|
||||
end
|
||||
|
||||
newparam(:order) do
|
||||
desc <<-DOC
|
||||
Specifies a method for sorting your fragments by name within the destination file. You can override this setting for individual
|
||||
fragments by adjusting the order parameter in their concat::fragment declarations.
|
||||
DOC
|
||||
|
||||
newvalues(:alpha, :numeric)
|
||||
|
||||
defaultto :numeric
|
||||
end
|
||||
|
||||
newparam(:backup) do
|
||||
desc <<-DOC
|
||||
Specifies whether (and how) to back up the destination file before overwriting it. Your value gets passed on to Puppet's native file
|
||||
resource for execution. Valid options: true, false, or a string representing either a target filebucket or a filename extension
|
||||
beginning with ".".'
|
||||
DOC
|
||||
|
||||
validate do |value|
|
||||
raise ArgumentError, _('Backup must be a Boolean or String') unless [TrueClass, FalseClass, String].include?(value.class)
|
||||
end
|
||||
end
|
||||
|
||||
newparam(:replace, boolean: true, parent: Puppet::Parameter::Boolean) do
|
||||
desc 'Specifies whether to overwrite the destination file if it already exists.'
|
||||
defaultto true
|
||||
end
|
||||
|
||||
newparam(:validate_cmd) do
|
||||
desc <<-DOC
|
||||
Specifies a validation command to apply to the destination file. Requires Puppet version 3.5 or newer. Valid options: a string to
|
||||
be passed to a file resource.
|
||||
DOC
|
||||
|
||||
validate do |value|
|
||||
raise ArgumentError, _('Validate_cmd must be a String') unless value.is_a?(String)
|
||||
end
|
||||
end
|
||||
|
||||
newparam(:ensure_newline, boolean: true, parent: Puppet::Parameter::Boolean) do
|
||||
desc "Specifies whether to add a line break at the end of each fragment that doesn't already end in one."
|
||||
defaultto false
|
||||
end
|
||||
|
||||
newparam(:format) do
|
||||
desc <<-DOC
|
||||
Specify what data type to merge the fragments as. Valid options: 'plain', 'yaml', 'json', 'json-array', 'json-pretty', 'json-array-pretty'.
|
||||
DOC
|
||||
|
||||
newvalues(:plain, :yaml, :json, :'json-array', :'json-pretty', :'json-array-pretty')
|
||||
|
||||
defaultto :plain
|
||||
end
|
||||
|
||||
newparam(:force, boolean: true, parent: Puppet::Parameter::Boolean) do
|
||||
desc 'Specifies whether to merge data structures, keeping the values with higher order.'
|
||||
|
||||
defaultto false
|
||||
end
|
||||
|
||||
newparam(:selinux_ignore_defaults, boolean: true, parent: Puppet::Parameter::Boolean) do
|
||||
desc <<-DOC
|
||||
See the file type's selinux_ignore_defaults documentention:
|
||||
https://docs.puppetlabs.com/references/latest/type.html#file-attribute-selinux_ignore_defaults.
|
||||
DOC
|
||||
end
|
||||
|
||||
newparam(:selrange) do
|
||||
desc "See the file type's selrange documentation: https://docs.puppetlabs.com/references/latest/type.html#file-attribute-selrange"
|
||||
validate do |value|
|
||||
raise ArgumentError, _('Selrange must be a String') unless value.is_a?(String)
|
||||
end
|
||||
end
|
||||
|
||||
newparam(:selrole) do
|
||||
desc "See the file type's selrole documentation: https://docs.puppetlabs.com/references/latest/type.html#file-attribute-selrole"
|
||||
validate do |value|
|
||||
raise ArgumentError, _('Selrole must be a String') unless value.is_a?(String)
|
||||
end
|
||||
end
|
||||
|
||||
newparam(:seltype) do
|
||||
desc "See the file type's seltype documentation: https://docs.puppetlabs.com/references/latest/type.html#file-attribute-seltype"
|
||||
validate do |value|
|
||||
raise ArgumentError, _('Seltype must be a String') unless value.is_a?(String)
|
||||
end
|
||||
end
|
||||
|
||||
newparam(:seluser) do
|
||||
desc "See the file type's seluser documentation: https://docs.puppetlabs.com/references/latest/type.html#file-attribute-seluser"
|
||||
validate do |value|
|
||||
raise ArgumentError, _('Seluser must be a String') unless value.is_a?(String)
|
||||
end
|
||||
end
|
||||
|
||||
newparam(:show_diff, boolean: true, parent: Puppet::Parameter::Boolean) do
|
||||
desc <<-DOC
|
||||
Specifies whether to set the show_diff parameter for the file resource. Useful for hiding secrets stored in hiera from insecure
|
||||
reporting methods.
|
||||
DOC
|
||||
end
|
||||
|
||||
newparam(:create_empty_file, boolean: true, parent: Puppet::Parameter::Boolean) do
|
||||
desc 'Specifies whether to create an empty file if no fragments are defined.'
|
||||
defaultto true
|
||||
end
|
||||
|
||||
# Autorequire the file we are generating below
|
||||
# Why is this necessary ?
|
||||
autorequire(:file) do
|
||||
[self[:path]]
|
||||
end
|
||||
|
||||
def fragments
|
||||
# Collect fragments that target this resource by path, title or tag.
|
||||
@fragments ||= catalog.resources.map { |resource|
|
||||
next unless resource.is_a?(Puppet::Type.type(:concat_fragment))
|
||||
|
||||
if resource[:target] == self[:path] || resource[:target] == title ||
|
||||
(resource[:tag] && resource[:tag] == self[:tag])
|
||||
resource
|
||||
end
|
||||
}.compact
|
||||
end
|
||||
|
||||
def decompound(d)
|
||||
d.split('___', 2).map { |v| (v =~ %r{^\d+$}) ? v.to_i : v }
|
||||
end
|
||||
|
||||
def should_content
|
||||
return @generated_content if @generated_content
|
||||
|
||||
@generated_content = ''
|
||||
content_fragments = []
|
||||
|
||||
fragments.each do |r|
|
||||
content_fragments << ["#{r[:order]}___#{r[:name]}", fragment_content(r)]
|
||||
end
|
||||
|
||||
sorted = if self[:order] == :numeric
|
||||
content_fragments.sort do |a, b|
|
||||
decompound(a[0]) <=> decompound(b[0])
|
||||
end
|
||||
else
|
||||
content_fragments.sort_by do |a|
|
||||
a_order, a_name = a[0].split('__', 2)
|
||||
[a_order, a_name]
|
||||
end
|
||||
end
|
||||
|
||||
case self[:format]
|
||||
when :plain
|
||||
@generated_content = sorted.map { |cf| cf[1] }.join
|
||||
when :yaml
|
||||
content_array = sorted.map do |cf|
|
||||
YAML.safe_load(cf[1])
|
||||
end
|
||||
content_hash = content_array.reduce({}) do |memo, current|
|
||||
nested_merge(memo, current)
|
||||
end
|
||||
@generated_content = content_hash.to_yaml
|
||||
when :json, :'json-array', :'json-pretty', :'json-array-pretty'
|
||||
content_array = sorted.map do |cf|
|
||||
JSON.parse(cf[1])
|
||||
end
|
||||
|
||||
if [:json, :'json-pretty'].include?(self[:format])
|
||||
content_hash = content_array.reduce({}) do |memo, current|
|
||||
nested_merge(memo, current)
|
||||
end
|
||||
|
||||
@generated_content =
|
||||
if self[:format] == :json
|
||||
content_hash.to_json
|
||||
else
|
||||
JSON.pretty_generate(content_hash)
|
||||
end
|
||||
else
|
||||
@generated_content =
|
||||
if self[:format] == :'json-array'
|
||||
content_array.to_json
|
||||
else
|
||||
JSON.pretty_generate(content_array)
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
@generated_content
|
||||
end
|
||||
|
||||
def nested_merge(hash1, hash2)
|
||||
# If a hash is nil or empty, simply return the other
|
||||
return hash1 if hash2.nil? || hash2.empty?
|
||||
return hash2 if hash1.nil? || hash1.empty?
|
||||
|
||||
# Unique merge for arrays
|
||||
return (hash1 + hash2).uniq if hash1.is_a?(Array) && hash2.is_a?(Array)
|
||||
|
||||
# Deep-merge Hashes; higher order value is kept
|
||||
hash1.merge(hash2) do |k, v1, v2|
|
||||
if (v1.is_a?(Hash) && v2.is_a?(Hash)) || (v1.is_a?(Array) && v2.is_a?(Array))
|
||||
nested_merge(v1, v2)
|
||||
else
|
||||
# Fail if there are duplicate keys without force
|
||||
unless v1 == v2
|
||||
unless self[:force]
|
||||
err_message = [
|
||||
"Duplicate key '#{k}' found with values '#{v1}' and #{v2}'.",
|
||||
"Use 'force' attribute to merge keys.",
|
||||
]
|
||||
raise(_(err_message.join(' ')))
|
||||
end
|
||||
Puppet.debug("Key '#{k}': replacing '#{v2}' with '#{v1}'.")
|
||||
end
|
||||
v1
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
def fragment_content(r)
|
||||
if r[:content].nil? == false
|
||||
# Explicitly resolve deferred values.
|
||||
fragment_content = r[:content].respond_to?(:resolve) ? r[:content].resolve : r[:content]
|
||||
elsif r[:source].nil? == false
|
||||
@source = nil
|
||||
Array(r[:source]).each do |source|
|
||||
if Puppet::FileServing::Metadata.indirection.find(source)
|
||||
@source = source
|
||||
break
|
||||
end
|
||||
end
|
||||
raise _('Could not retrieve source(s) %{_array}') % { _array: Array(r[:source]).join(', ') } unless @source
|
||||
|
||||
tmp = Puppet::FileServing::Content.indirection.find(@source)
|
||||
fragment_content = tmp.content unless tmp.nil?
|
||||
end
|
||||
|
||||
if self[:ensure_newline]
|
||||
newline = Puppet::Util::Platform.windows? ? "\r\n" : "\n"
|
||||
fragment_content = fragment_content.dup << newline unless %r{#{newline}\Z}.match?(fragment_content)
|
||||
end
|
||||
|
||||
fragment_content
|
||||
end
|
||||
|
||||
def generate
|
||||
file_opts = {
|
||||
ensure: (self[:ensure] == :absent) ? :absent : :file
|
||||
}
|
||||
|
||||
[:path,
|
||||
:owner,
|
||||
:group,
|
||||
:mode,
|
||||
:replace,
|
||||
:backup,
|
||||
:selinux_ignore_defaults,
|
||||
:selrange,
|
||||
:selrole,
|
||||
:seltype,
|
||||
:seluser,
|
||||
:validate_cmd,
|
||||
:show_diff].each do |param|
|
||||
file_opts[param] = self[param] unless self[param].nil?
|
||||
end
|
||||
|
||||
excluded_metaparams = [:before, :notify, :require, :subscribe, :tag]
|
||||
|
||||
Puppet::Type.metaparams.each do |metaparam|
|
||||
file_opts[metaparam] = self[metaparam] unless self[metaparam].nil? || excluded_metaparams.include?(metaparam)
|
||||
end
|
||||
|
||||
[Puppet::Type.type(:file).new(file_opts)]
|
||||
end
|
||||
|
||||
def eval_generate
|
||||
content = should_content
|
||||
|
||||
catalog.resource("File[#{self[:path]}]")[:content] = content unless content.nil?
|
||||
|
||||
catalog.resource("File[#{self[:path]}]")[:ensure] = :absent if !self[:create_empty_file] && (content.nil? || content.empty?)
|
||||
|
||||
[catalog.resource("File[#{self[:path]}]")]
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,202 @@
|
||||
|
||||
Apache License
|
||||
Version 2.0, January 2004
|
||||
http://www.apache.org/licenses/
|
||||
|
||||
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
||||
|
||||
1. Definitions.
|
||||
|
||||
"License" shall mean the terms and conditions for use, reproduction,
|
||||
and distribution as defined by Sections 1 through 9 of this document.
|
||||
|
||||
"Licensor" shall mean the copyright owner or entity authorized by
|
||||
the copyright owner that is granting the License.
|
||||
|
||||
"Legal Entity" shall mean the union of the acting entity and all
|
||||
other entities that control, are controlled by, or are under common
|
||||
control with that entity. For the purposes of this definition,
|
||||
"control" means (i) the power, direct or indirect, to cause the
|
||||
direction or management of such entity, whether by contract or
|
||||
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
||||
outstanding shares, or (iii) beneficial ownership of such entity.
|
||||
|
||||
"You" (or "Your") shall mean an individual or Legal Entity
|
||||
exercising permissions granted by this License.
|
||||
|
||||
"Source" form shall mean the preferred form for making modifications,
|
||||
including but not limited to software source code, documentation
|
||||
source, and configuration files.
|
||||
|
||||
"Object" form shall mean any form resulting from mechanical
|
||||
transformation or translation of a Source form, including but
|
||||
not limited to compiled object code, generated documentation,
|
||||
and conversions to other media types.
|
||||
|
||||
"Work" shall mean the work of authorship, whether in Source or
|
||||
Object form, made available under the License, as indicated by a
|
||||
copyright notice that is included in or attached to the work
|
||||
(an example is provided in the Appendix below).
|
||||
|
||||
"Derivative Works" shall mean any work, whether in Source or Object
|
||||
form, that is based on (or derived from) the Work and for which the
|
||||
editorial revisions, annotations, elaborations, or other modifications
|
||||
represent, as a whole, an original work of authorship. For the purposes
|
||||
of this License, Derivative Works shall not include works that remain
|
||||
separable from, or merely link (or bind by name) to the interfaces of,
|
||||
the Work and Derivative Works thereof.
|
||||
|
||||
"Contribution" shall mean any work of authorship, including
|
||||
the original version of the Work and any modifications or additions
|
||||
to that Work or Derivative Works thereof, that is intentionally
|
||||
submitted to Licensor for inclusion in the Work by the copyright owner
|
||||
or by an individual or Legal Entity authorized to submit on behalf of
|
||||
the copyright owner. For the purposes of this definition, "submitted"
|
||||
means any form of electronic, verbal, or written communication sent
|
||||
to the Licensor or its representatives, including but not limited to
|
||||
communication on electronic mailing lists, source code control systems,
|
||||
and issue tracking systems that are managed by, or on behalf of, the
|
||||
Licensor for the purpose of discussing and improving the Work, but
|
||||
excluding communication that is conspicuously marked or otherwise
|
||||
designated in writing by the copyright owner as "Not a Contribution."
|
||||
|
||||
"Contributor" shall mean Licensor and any individual or Legal Entity
|
||||
on behalf of whom a Contribution has been received by Licensor and
|
||||
subsequently incorporated within the Work.
|
||||
|
||||
2. Grant of Copyright License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
copyright license to reproduce, prepare Derivative Works of,
|
||||
publicly display, publicly perform, sublicense, and distribute the
|
||||
Work and such Derivative Works in Source or Object form.
|
||||
|
||||
3. Grant of Patent License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
(except as stated in this section) patent license to make, have made,
|
||||
use, offer to sell, sell, import, and otherwise transfer the Work,
|
||||
where such license applies only to those patent claims licensable
|
||||
by such Contributor that are necessarily infringed by their
|
||||
Contribution(s) alone or by combination of their Contribution(s)
|
||||
with the Work to which such Contribution(s) was submitted. If You
|
||||
institute patent litigation against any entity (including a
|
||||
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
||||
or a Contribution incorporated within the Work constitutes direct
|
||||
or contributory patent infringement, then any patent licenses
|
||||
granted to You under this License for that Work shall terminate
|
||||
as of the date such litigation is filed.
|
||||
|
||||
4. Redistribution. You may reproduce and distribute copies of the
|
||||
Work or Derivative Works thereof in any medium, with or without
|
||||
modifications, and in Source or Object form, provided that You
|
||||
meet the following conditions:
|
||||
|
||||
(a) You must give any other recipients of the Work or
|
||||
Derivative Works a copy of this License; and
|
||||
|
||||
(b) You must cause any modified files to carry prominent notices
|
||||
stating that You changed the files; and
|
||||
|
||||
(c) You must retain, in the Source form of any Derivative Works
|
||||
that You distribute, all copyright, patent, trademark, and
|
||||
attribution notices from the Source form of the Work,
|
||||
excluding those notices that do not pertain to any part of
|
||||
the Derivative Works; and
|
||||
|
||||
(d) If the Work includes a "NOTICE" text file as part of its
|
||||
distribution, then any Derivative Works that You distribute must
|
||||
include a readable copy of the attribution notices contained
|
||||
within such NOTICE file, excluding those notices that do not
|
||||
pertain to any part of the Derivative Works, in at least one
|
||||
of the following places: within a NOTICE text file distributed
|
||||
as part of the Derivative Works; within the Source form or
|
||||
documentation, if provided along with the Derivative Works; or,
|
||||
within a display generated by the Derivative Works, if and
|
||||
wherever such third-party notices normally appear. The contents
|
||||
of the NOTICE file are for informational purposes only and
|
||||
do not modify the License. You may add Your own attribution
|
||||
notices within Derivative Works that You distribute, alongside
|
||||
or as an addendum to the NOTICE text from the Work, provided
|
||||
that such additional attribution notices cannot be construed
|
||||
as modifying the License.
|
||||
|
||||
You may add Your own copyright statement to Your modifications and
|
||||
may provide additional or different license terms and conditions
|
||||
for use, reproduction, or distribution of Your modifications, or
|
||||
for any such Derivative Works as a whole, provided Your use,
|
||||
reproduction, and distribution of the Work otherwise complies with
|
||||
the conditions stated in this License.
|
||||
|
||||
5. Submission of Contributions. Unless You explicitly state otherwise,
|
||||
any Contribution intentionally submitted for inclusion in the Work
|
||||
by You to the Licensor shall be under the terms and conditions of
|
||||
this License, without any additional terms or conditions.
|
||||
Notwithstanding the above, nothing herein shall supersede or modify
|
||||
the terms of any separate license agreement you may have executed
|
||||
with Licensor regarding such Contributions.
|
||||
|
||||
6. Trademarks. This License does not grant permission to use the trade
|
||||
names, trademarks, service marks, or product names of the Licensor,
|
||||
except as required for reasonable and customary use in describing the
|
||||
origin of the Work and reproducing the content of the NOTICE file.
|
||||
|
||||
7. Disclaimer of Warranty. Unless required by applicable law or
|
||||
agreed to in writing, Licensor provides the Work (and each
|
||||
Contributor provides its Contributions) on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
||||
implied, including, without limitation, any warranties or conditions
|
||||
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
||||
PARTICULAR PURPOSE. You are solely responsible for determining the
|
||||
appropriateness of using or redistributing the Work and assume any
|
||||
risks associated with Your exercise of permissions under this License.
|
||||
|
||||
8. Limitation of Liability. In no event and under no legal theory,
|
||||
whether in tort (including negligence), contract, or otherwise,
|
||||
unless required by applicable law (such as deliberate and grossly
|
||||
negligent acts) or agreed to in writing, shall any Contributor be
|
||||
liable to You for damages, including any direct, indirect, special,
|
||||
incidental, or consequential damages of any character arising as a
|
||||
result of this License or out of the use or inability to use the
|
||||
Work (including but not limited to damages for loss of goodwill,
|
||||
work stoppage, computer failure or malfunction, or any and all
|
||||
other commercial damages or losses), even if such Contributor
|
||||
has been advised of the possibility of such damages.
|
||||
|
||||
9. Accepting Warranty or Additional Liability. While redistributing
|
||||
the Work or Derivative Works thereof, You may choose to offer,
|
||||
and charge a fee for, acceptance of support, warranty, indemnity,
|
||||
or other liability obligations and/or rights consistent with this
|
||||
License. However, in accepting such obligations, You may act only
|
||||
on Your own behalf and on Your sole responsibility, not on behalf
|
||||
of any other Contributor, and only if You agree to indemnify,
|
||||
defend, and hold each Contributor harmless for any liability
|
||||
incurred by, or claims asserted against, such Contributor by reason
|
||||
of your accepting any such warranty or additional liability.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
APPENDIX: How to apply the Apache License to your work.
|
||||
|
||||
To apply the Apache License to your work, attach the following
|
||||
boilerplate notice, with the fields enclosed by brackets "[]"
|
||||
replaced with your own identifying information. (Don't include
|
||||
the brackets!) The text should be enclosed in the appropriate
|
||||
comment syntax for the file format. We also recommend that a
|
||||
file or class name and description of purpose be included on the
|
||||
same "printed page" as the copyright notice for easier
|
||||
identification within third-party archives.
|
||||
|
||||
Copyright [yyyy] [name of copyright owner]
|
||||
|
||||
Licensed under the Apache License, Version 2.0 (the "License");
|
||||
you may not use this file except in compliance with the License.
|
||||
You may obtain a copy of the License at
|
||||
|
||||
http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
||||
Unless required by applicable law or agreed to in writing, software
|
||||
distributed under the License is distributed on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
See the License for the specific language governing permissions and
|
||||
limitations under the License.
|
||||
@@ -0,0 +1,23 @@
|
||||
Puppet Module - puppetlabs-firewall
|
||||
|
||||
Copyright 2018 Puppet, Inc.
|
||||
Copyright 2011 Jonathan Boyett
|
||||
Copyright 2011 Media Temple, Inc.
|
||||
|
||||
Some of the iptables code was taken from puppet-iptables which was:
|
||||
|
||||
Copyright 2011 Bob.sh Limited
|
||||
Copyright 2008 Camptocamp Association
|
||||
Copyright 2007 Dmitri Priimak
|
||||
|
||||
Licensed under the Apache License, Version 2.0 (the "License");
|
||||
you may not use this file except in compliance with the License.
|
||||
You may obtain a copy of the License at
|
||||
|
||||
http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
||||
Unless required by applicable law or agreed to in writing, software
|
||||
distributed under the License is distributed on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
See the License for the specific language governing permissions and
|
||||
limitations under the License.
|
||||
Vendored
+2
@@ -0,0 +1,2 @@
|
||||
class Puppet::Provider::Firewall::Firewall
|
||||
end
|
||||
+2
@@ -0,0 +1,2 @@
|
||||
class Puppet::Provider::Firewallchain::Firewallchain
|
||||
end
|
||||
+1548
File diff suppressed because it is too large
Load Diff
+91
@@ -0,0 +1,91 @@
|
||||
# frozen_string_literal: true
|
||||
|
||||
# lib/puppet/type/firewallchain.rb
|
||||
require 'puppet/resource_api'
|
||||
|
||||
Puppet::ResourceApi.register_type(
|
||||
name: 'firewallchain',
|
||||
features: ['custom_generate', 'custom_insync'],
|
||||
docs: <<-DESC,
|
||||
This type provides the capability to manage rule chains for firewalls.
|
||||
|
||||
Currently this supports only iptables, ip6tables and ebtables on Linux. And
|
||||
provides support for setting the default policy on chains and tables that
|
||||
allow it.
|
||||
|
||||
#### Providers
|
||||
* iptables_chain is the only provider that supports firewallchain.
|
||||
|
||||
#### Features
|
||||
* iptables_chain: The provider provides iptables chain features.
|
||||
* policy: Default policy (inbuilt chains only).
|
||||
DESC
|
||||
attributes: {
|
||||
ensure: {
|
||||
type: 'Enum[present, absent]',
|
||||
default: 'present',
|
||||
desc: <<-DESC
|
||||
Whether this chain should be present or absent on the target system.
|
||||
Setting this to absent will first remove all rules associated with this chain and then delete the chain itself.
|
||||
Inbuilt chains however will merely remove any added rules and, if it has been changed, return their policy to the default.
|
||||
DESC
|
||||
},
|
||||
name: {
|
||||
type: 'Pattern[/^(?:\S+):(?:nat|mangle|filter|raw|rawpost|broute|security):(?:IP(?:v[46])?|ethernet)$/]',
|
||||
desc: 'The canonical name of the chain with the required format being `{chain}:{table}:{protocol}`.',
|
||||
behaviour: :namevar
|
||||
},
|
||||
policy: {
|
||||
type: "Optional[Enum['accept', 'drop', 'queue', 'return']]",
|
||||
desc: <<-DESC
|
||||
This action to take when the end of the chain is reached.
|
||||
This can only be set on inbuilt chains (i.e. INPUT, FORWARD, OUTPUT,
|
||||
PREROUTING, POSTROUTING) and can be one of:
|
||||
|
||||
* accept - the packet is accepted
|
||||
* drop - the packet is dropped
|
||||
* queue - the packet is passed userspace
|
||||
* return - the packet is returned to calling (jump) queue
|
||||
or the default of inbuilt chains
|
||||
DESC
|
||||
},
|
||||
purge: {
|
||||
type: 'Boolean',
|
||||
default: false,
|
||||
desc: 'Whether or not to purge unmanaged rules in this chain'
|
||||
},
|
||||
ignore: {
|
||||
type: 'Optional[Variant[String[1], Array[String[1]]]]',
|
||||
desc: <<-DESC
|
||||
Regex to perform on firewall rules to exempt unmanaged rules from purging.
|
||||
This is matched against the output of `iptables-save`.
|
||||
|
||||
This can be a single regex, or an array of them.
|
||||
To support flags, use the ruby inline flag mechanism.
|
||||
Meaning a regex such as
|
||||
/foo/i
|
||||
can be written as
|
||||
'(?i)foo' or '(?i:foo)'
|
||||
|
||||
Full example:
|
||||
```
|
||||
firewallchain { 'INPUT:filter:IPv4':
|
||||
purge => true,
|
||||
ignore => [
|
||||
'-j fail2ban-ssh', # ignore the fail2ban jump rule
|
||||
'--comment "[^"]*(?i:ignore)[^"]*"', # ignore any rules with "ignore" (case insensitive) in the comment in the rule
|
||||
],
|
||||
}
|
||||
```
|
||||
DESC
|
||||
},
|
||||
ignore_foreign: {
|
||||
type: 'Boolean',
|
||||
default: false,
|
||||
desc: <<-DESC
|
||||
Ignore rules that do not match the puppet title pattern "^\d+[[:graph:][:space:]]" when purging unmanaged firewall rules in this chain.
|
||||
This can be used to ignore rules that were not put in by puppet. Beware that nothing keeps other systems from configuring firewall rules with a comment that starts with digits, and is indistinguishable from puppet-configured rules.
|
||||
DESC
|
||||
}
|
||||
},
|
||||
)
|
||||
@@ -0,0 +1,201 @@
|
||||
Apache License
|
||||
Version 2.0, January 2004
|
||||
http://www.apache.org/licenses/
|
||||
|
||||
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
||||
|
||||
1. Definitions.
|
||||
|
||||
"License" shall mean the terms and conditions for use, reproduction,
|
||||
and distribution as defined by Sections 1 through 9 of this document.
|
||||
|
||||
"Licensor" shall mean the copyright owner or entity authorized by
|
||||
the copyright owner that is granting the License.
|
||||
|
||||
"Legal Entity" shall mean the union of the acting entity and all
|
||||
other entities that control, are controlled by, or are under common
|
||||
control with that entity. For the purposes of this definition,
|
||||
"control" means (i) the power, direct or indirect, to cause the
|
||||
direction or management of such entity, whether by contract or
|
||||
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
||||
outstanding shares, or (iii) beneficial ownership of such entity.
|
||||
|
||||
"You" (or "Your") shall mean an individual or Legal Entity
|
||||
exercising permissions granted by this License.
|
||||
|
||||
"Source" form shall mean the preferred form for making modifications,
|
||||
including but not limited to software source code, documentation
|
||||
source, and configuration files.
|
||||
|
||||
"Object" form shall mean any form resulting from mechanical
|
||||
transformation or translation of a Source form, including but
|
||||
not limited to compiled object code, generated documentation,
|
||||
and conversions to other media types.
|
||||
|
||||
"Work" shall mean the work of authorship, whether in Source or
|
||||
Object form, made available under the License, as indicated by a
|
||||
copyright notice that is included in or attached to the work
|
||||
(an example is provided in the Appendix below).
|
||||
|
||||
"Derivative Works" shall mean any work, whether in Source or Object
|
||||
form, that is based on (or derived from) the Work and for which the
|
||||
editorial revisions, annotations, elaborations, or other modifications
|
||||
represent, as a whole, an original work of authorship. For the purposes
|
||||
of this License, Derivative Works shall not include works that remain
|
||||
separable from, or merely link (or bind by name) to the interfaces of,
|
||||
the Work and Derivative Works thereof.
|
||||
|
||||
"Contribution" shall mean any work of authorship, including
|
||||
the original version of the Work and any modifications or additions
|
||||
to that Work or Derivative Works thereof, that is intentionally
|
||||
submitted to Licensor for inclusion in the Work by the copyright owner
|
||||
or by an individual or Legal Entity authorized to submit on behalf of
|
||||
the copyright owner. For the purposes of this definition, "submitted"
|
||||
means any form of electronic, verbal, or written communication sent
|
||||
to the Licensor or its representatives, including but not limited to
|
||||
communication on electronic mailing lists, source code control systems,
|
||||
and issue tracking systems that are managed by, or on behalf of, the
|
||||
Licensor for the purpose of discussing and improving the Work, but
|
||||
excluding communication that is conspicuously marked or otherwise
|
||||
designated in writing by the copyright owner as "Not a Contribution."
|
||||
|
||||
"Contributor" shall mean Licensor and any individual or Legal Entity
|
||||
on behalf of whom a Contribution has been received by Licensor and
|
||||
subsequently incorporated within the Work.
|
||||
|
||||
2. Grant of Copyright License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
copyright license to reproduce, prepare Derivative Works of,
|
||||
publicly display, publicly perform, sublicense, and distribute the
|
||||
Work and such Derivative Works in Source or Object form.
|
||||
|
||||
3. Grant of Patent License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
(except as stated in this section) patent license to make, have made,
|
||||
use, offer to sell, sell, import, and otherwise transfer the Work,
|
||||
where such license applies only to those patent claims licensable
|
||||
by such Contributor that are necessarily infringed by their
|
||||
Contribution(s) alone or by combination of their Contribution(s)
|
||||
with the Work to which such Contribution(s) was submitted. If You
|
||||
institute patent litigation against any entity (including a
|
||||
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
||||
or a Contribution incorporated within the Work constitutes direct
|
||||
or contributory patent infringement, then any patent licenses
|
||||
granted to You under this License for that Work shall terminate
|
||||
as of the date such litigation is filed.
|
||||
|
||||
4. Redistribution. You may reproduce and distribute copies of the
|
||||
Work or Derivative Works thereof in any medium, with or without
|
||||
modifications, and in Source or Object form, provided that You
|
||||
meet the following conditions:
|
||||
|
||||
(a) You must give any other recipients of the Work or
|
||||
Derivative Works a copy of this License; and
|
||||
|
||||
(b) You must cause any modified files to carry prominent notices
|
||||
stating that You changed the files; and
|
||||
|
||||
(c) You must retain, in the Source form of any Derivative Works
|
||||
that You distribute, all copyright, patent, trademark, and
|
||||
attribution notices from the Source form of the Work,
|
||||
excluding those notices that do not pertain to any part of
|
||||
the Derivative Works; and
|
||||
|
||||
(d) If the Work includes a "NOTICE" text file as part of its
|
||||
distribution, then any Derivative Works that You distribute must
|
||||
include a readable copy of the attribution notices contained
|
||||
within such NOTICE file, excluding those notices that do not
|
||||
pertain to any part of the Derivative Works, in at least one
|
||||
of the following places: within a NOTICE text file distributed
|
||||
as part of the Derivative Works; within the Source form or
|
||||
documentation, if provided along with the Derivative Works; or,
|
||||
within a display generated by the Derivative Works, if and
|
||||
wherever such third-party notices normally appear. The contents
|
||||
of the NOTICE file are for informational purposes only and
|
||||
do not modify the License. You may add Your own attribution
|
||||
notices within Derivative Works that You distribute, alongside
|
||||
or as an addendum to the NOTICE text from the Work, provided
|
||||
that such additional attribution notices cannot be construed
|
||||
as modifying the License.
|
||||
|
||||
You may add Your own copyright statement to Your modifications and
|
||||
may provide additional or different license terms and conditions
|
||||
for use, reproduction, or distribution of Your modifications, or
|
||||
for any such Derivative Works as a whole, provided Your use,
|
||||
reproduction, and distribution of the Work otherwise complies with
|
||||
the conditions stated in this License.
|
||||
|
||||
5. Submission of Contributions. Unless You explicitly state otherwise,
|
||||
any Contribution intentionally submitted for inclusion in the Work
|
||||
by You to the Licensor shall be under the terms and conditions of
|
||||
this License, without any additional terms or conditions.
|
||||
Notwithstanding the above, nothing herein shall supersede or modify
|
||||
the terms of any separate license agreement you may have executed
|
||||
with Licensor regarding such Contributions.
|
||||
|
||||
6. Trademarks. This License does not grant permission to use the trade
|
||||
names, trademarks, service marks, or product names of the Licensor,
|
||||
except as required for reasonable and customary use in describing the
|
||||
origin of the Work and reproducing the content of the NOTICE file.
|
||||
|
||||
7. Disclaimer of Warranty. Unless required by applicable law or
|
||||
agreed to in writing, Licensor provides the Work (and each
|
||||
Contributor provides its Contributions) on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
||||
implied, including, without limitation, any warranties or conditions
|
||||
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
||||
PARTICULAR PURPOSE. You are solely responsible for determining the
|
||||
appropriateness of using or redistributing the Work and assume any
|
||||
risks associated with Your exercise of permissions under this License.
|
||||
|
||||
8. Limitation of Liability. In no event and under no legal theory,
|
||||
whether in tort (including negligence), contract, or otherwise,
|
||||
unless required by applicable law (such as deliberate and grossly
|
||||
negligent acts) or agreed to in writing, shall any Contributor be
|
||||
liable to You for damages, including any direct, indirect, special,
|
||||
incidental, or consequential damages of any character arising as a
|
||||
result of this License or out of the use or inability to use the
|
||||
Work (including but not limited to damages for loss of goodwill,
|
||||
work stoppage, computer failure or malfunction, or any and all
|
||||
other commercial damages or losses), even if such Contributor
|
||||
has been advised of the possibility of such damages.
|
||||
|
||||
9. Accepting Warranty or Additional Liability. While redistributing
|
||||
the Work or Derivative Works thereof, You may choose to offer,
|
||||
and charge a fee for, acceptance of support, warranty, indemnity,
|
||||
or other liability obligations and/or rights consistent with this
|
||||
License. However, in accepting such obligations, You may act only
|
||||
on Your own behalf and on Your sole responsibility, not on behalf
|
||||
of any other Contributor, and only if You agree to indemnify,
|
||||
defend, and hold each Contributor harmless for any liability
|
||||
incurred by, or claims asserted against, such Contributor by reason
|
||||
of your accepting any such warranty or additional liability.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
APPENDIX: How to apply the Apache License to your work.
|
||||
|
||||
To apply the Apache License to your work, attach the following
|
||||
boilerplate notice, with the fields enclosed by brackets "{}"
|
||||
replaced with your own identifying information. (Don't include
|
||||
the brackets!) The text should be enclosed in the appropriate
|
||||
comment syntax for the file format. We also recommend that a
|
||||
file or class name and description of purpose be included on the
|
||||
same "printed page" as the copyright notice for easier
|
||||
identification within third-party archives.
|
||||
|
||||
Copyright {yyyy} {name of copyright owner}
|
||||
|
||||
Licensed under the Apache License, Version 2.0 (the "License");
|
||||
you may not use this file except in compliance with the License.
|
||||
You may obtain a copy of the License at
|
||||
|
||||
http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
||||
Unless required by applicable law or agreed to in writing, software
|
||||
distributed under the License is distributed on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
See the License for the specific language governing permissions and
|
||||
limitations under the License.
|
||||
+2
@@ -0,0 +1,2 @@
|
||||
Puppet::Type.type(:grafana_plugin).provide(:grafana_cli) do
|
||||
end
|
||||
+59
@@ -0,0 +1,59 @@
|
||||
# frozen_string_literal: true
|
||||
|
||||
Puppet::Type.newtype(:grafana_plugin) do
|
||||
desc <<~DESC
|
||||
manages grafana plugins
|
||||
|
||||
@example Install a grafana plugin
|
||||
grafana_plugin { 'grafana-simple-json-datasource': }
|
||||
|
||||
@example Install a grafana plugin from different repo
|
||||
grafana_plugin { 'grafana-simple-json-datasource':
|
||||
ensure => 'present',
|
||||
repo => 'https://nexus.company.com/grafana/plugins',
|
||||
}
|
||||
|
||||
@example Install a grafana plugin from a plugin url
|
||||
grafana_plugin { 'grafana-example-custom-plugin':
|
||||
ensure => 'present',
|
||||
plugin_url => 'https://github.com/example/example-custom-plugin/zipball/v1.0.0'
|
||||
}
|
||||
|
||||
@example Uninstall a grafana plugin
|
||||
grafana_plugin { 'grafana-simple-json-datasource':
|
||||
ensure => 'absent',
|
||||
}
|
||||
|
||||
@example Show resources
|
||||
$ puppet resource grafana_plugin
|
||||
DESC
|
||||
|
||||
ensurable do
|
||||
defaultto(:present)
|
||||
newvalue(:present) do
|
||||
provider.create
|
||||
end
|
||||
newvalue(:absent) do
|
||||
provider.destroy
|
||||
end
|
||||
end
|
||||
|
||||
newparam(:name, namevar: true) do
|
||||
desc 'The name of the plugin to enable'
|
||||
newvalues(%r{^\S+$})
|
||||
end
|
||||
|
||||
newparam(:repo) do
|
||||
desc 'The URL of an internal plugin server'
|
||||
validate do |value|
|
||||
raise ArgumentError, format('%s is not a valid URL', value) unless value =~ %r{^https?://}
|
||||
end
|
||||
end
|
||||
|
||||
newparam(:plugin_url) do
|
||||
desc 'Full url to the plugin zip file'
|
||||
validate do |value|
|
||||
raise ArgumentError, format('%s is not a valid URL', value) unless value =~ %r{^https?://}
|
||||
end
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,202 @@
|
||||
|
||||
Apache License
|
||||
Version 2.0, January 2004
|
||||
http://www.apache.org/licenses/
|
||||
|
||||
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
||||
|
||||
1. Definitions.
|
||||
|
||||
"License" shall mean the terms and conditions for use, reproduction,
|
||||
and distribution as defined by Sections 1 through 9 of this document.
|
||||
|
||||
"Licensor" shall mean the copyright owner or entity authorized by
|
||||
the copyright owner that is granting the License.
|
||||
|
||||
"Legal Entity" shall mean the union of the acting entity and all
|
||||
other entities that control, are controlled by, or are under common
|
||||
control with that entity. For the purposes of this definition,
|
||||
"control" means (i) the power, direct or indirect, to cause the
|
||||
direction or management of such entity, whether by contract or
|
||||
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
||||
outstanding shares, or (iii) beneficial ownership of such entity.
|
||||
|
||||
"You" (or "Your") shall mean an individual or Legal Entity
|
||||
exercising permissions granted by this License.
|
||||
|
||||
"Source" form shall mean the preferred form for making modifications,
|
||||
including but not limited to software source code, documentation
|
||||
source, and configuration files.
|
||||
|
||||
"Object" form shall mean any form resulting from mechanical
|
||||
transformation or translation of a Source form, including but
|
||||
not limited to compiled object code, generated documentation,
|
||||
and conversions to other media types.
|
||||
|
||||
"Work" shall mean the work of authorship, whether in Source or
|
||||
Object form, made available under the License, as indicated by a
|
||||
copyright notice that is included in or attached to the work
|
||||
(an example is provided in the Appendix below).
|
||||
|
||||
"Derivative Works" shall mean any work, whether in Source or Object
|
||||
form, that is based on (or derived from) the Work and for which the
|
||||
editorial revisions, annotations, elaborations, or other modifications
|
||||
represent, as a whole, an original work of authorship. For the purposes
|
||||
of this License, Derivative Works shall not include works that remain
|
||||
separable from, or merely link (or bind by name) to the interfaces of,
|
||||
the Work and Derivative Works thereof.
|
||||
|
||||
"Contribution" shall mean any work of authorship, including
|
||||
the original version of the Work and any modifications or additions
|
||||
to that Work or Derivative Works thereof, that is intentionally
|
||||
submitted to Licensor for inclusion in the Work by the copyright owner
|
||||
or by an individual or Legal Entity authorized to submit on behalf of
|
||||
the copyright owner. For the purposes of this definition, "submitted"
|
||||
means any form of electronic, verbal, or written communication sent
|
||||
to the Licensor or its representatives, including but not limited to
|
||||
communication on electronic mailing lists, source code control systems,
|
||||
and issue tracking systems that are managed by, or on behalf of, the
|
||||
Licensor for the purpose of discussing and improving the Work, but
|
||||
excluding communication that is conspicuously marked or otherwise
|
||||
designated in writing by the copyright owner as "Not a Contribution."
|
||||
|
||||
"Contributor" shall mean Licensor and any individual or Legal Entity
|
||||
on behalf of whom a Contribution has been received by Licensor and
|
||||
subsequently incorporated within the Work.
|
||||
|
||||
2. Grant of Copyright License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
copyright license to reproduce, prepare Derivative Works of,
|
||||
publicly display, publicly perform, sublicense, and distribute the
|
||||
Work and such Derivative Works in Source or Object form.
|
||||
|
||||
3. Grant of Patent License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
(except as stated in this section) patent license to make, have made,
|
||||
use, offer to sell, sell, import, and otherwise transfer the Work,
|
||||
where such license applies only to those patent claims licensable
|
||||
by such Contributor that are necessarily infringed by their
|
||||
Contribution(s) alone or by combination of their Contribution(s)
|
||||
with the Work to which such Contribution(s) was submitted. If You
|
||||
institute patent litigation against any entity (including a
|
||||
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
||||
or a Contribution incorporated within the Work constitutes direct
|
||||
or contributory patent infringement, then any patent licenses
|
||||
granted to You under this License for that Work shall terminate
|
||||
as of the date such litigation is filed.
|
||||
|
||||
4. Redistribution. You may reproduce and distribute copies of the
|
||||
Work or Derivative Works thereof in any medium, with or without
|
||||
modifications, and in Source or Object form, provided that You
|
||||
meet the following conditions:
|
||||
|
||||
(a) You must give any other recipients of the Work or
|
||||
Derivative Works a copy of this License; and
|
||||
|
||||
(b) You must cause any modified files to carry prominent notices
|
||||
stating that You changed the files; and
|
||||
|
||||
(c) You must retain, in the Source form of any Derivative Works
|
||||
that You distribute, all copyright, patent, trademark, and
|
||||
attribution notices from the Source form of the Work,
|
||||
excluding those notices that do not pertain to any part of
|
||||
the Derivative Works; and
|
||||
|
||||
(d) If the Work includes a "NOTICE" text file as part of its
|
||||
distribution, then any Derivative Works that You distribute must
|
||||
include a readable copy of the attribution notices contained
|
||||
within such NOTICE file, excluding those notices that do not
|
||||
pertain to any part of the Derivative Works, in at least one
|
||||
of the following places: within a NOTICE text file distributed
|
||||
as part of the Derivative Works; within the Source form or
|
||||
documentation, if provided along with the Derivative Works; or,
|
||||
within a display generated by the Derivative Works, if and
|
||||
wherever such third-party notices normally appear. The contents
|
||||
of the NOTICE file are for informational purposes only and
|
||||
do not modify the License. You may add Your own attribution
|
||||
notices within Derivative Works that You distribute, alongside
|
||||
or as an addendum to the NOTICE text from the Work, provided
|
||||
that such additional attribution notices cannot be construed
|
||||
as modifying the License.
|
||||
|
||||
You may add Your own copyright statement to Your modifications and
|
||||
may provide additional or different license terms and conditions
|
||||
for use, reproduction, or distribution of Your modifications, or
|
||||
for any such Derivative Works as a whole, provided Your use,
|
||||
reproduction, and distribution of the Work otherwise complies with
|
||||
the conditions stated in this License.
|
||||
|
||||
5. Submission of Contributions. Unless You explicitly state otherwise,
|
||||
any Contribution intentionally submitted for inclusion in the Work
|
||||
by You to the Licensor shall be under the terms and conditions of
|
||||
this License, without any additional terms or conditions.
|
||||
Notwithstanding the above, nothing herein shall supersede or modify
|
||||
the terms of any separate license agreement you may have executed
|
||||
with Licensor regarding such Contributions.
|
||||
|
||||
6. Trademarks. This License does not grant permission to use the trade
|
||||
names, trademarks, service marks, or product names of the Licensor,
|
||||
except as required for reasonable and customary use in describing the
|
||||
origin of the Work and reproducing the content of the NOTICE file.
|
||||
|
||||
7. Disclaimer of Warranty. Unless required by applicable law or
|
||||
agreed to in writing, Licensor provides the Work (and each
|
||||
Contributor provides its Contributions) on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
||||
implied, including, without limitation, any warranties or conditions
|
||||
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
||||
PARTICULAR PURPOSE. You are solely responsible for determining the
|
||||
appropriateness of using or redistributing the Work and assume any
|
||||
risks associated with Your exercise of permissions under this License.
|
||||
|
||||
8. Limitation of Liability. In no event and under no legal theory,
|
||||
whether in tort (including negligence), contract, or otherwise,
|
||||
unless required by applicable law (such as deliberate and grossly
|
||||
negligent acts) or agreed to in writing, shall any Contributor be
|
||||
liable to You for damages, including any direct, indirect, special,
|
||||
incidental, or consequential damages of any character arising as a
|
||||
result of this License or out of the use or inability to use the
|
||||
Work (including but not limited to damages for loss of goodwill,
|
||||
work stoppage, computer failure or malfunction, or any and all
|
||||
other commercial damages or losses), even if such Contributor
|
||||
has been advised of the possibility of such damages.
|
||||
|
||||
9. Accepting Warranty or Additional Liability. While redistributing
|
||||
the Work or Derivative Works thereof, You may choose to offer,
|
||||
and charge a fee for, acceptance of support, warranty, indemnity,
|
||||
or other liability obligations and/or rights consistent with this
|
||||
License. However, in accepting such obligations, You may act only
|
||||
on Your own behalf and on Your sole responsibility, not on behalf
|
||||
of any other Contributor, and only if You agree to indemnify,
|
||||
defend, and hold each Contributor harmless for any liability
|
||||
incurred by, or claims asserted against, such Contributor by reason
|
||||
of your accepting any such warranty or additional liability.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
APPENDIX: How to apply the Apache License to your work.
|
||||
|
||||
To apply the Apache License to your work, attach the following
|
||||
boilerplate notice, with the fields enclosed by brackets "[]"
|
||||
replaced with your own identifying information. (Don't include
|
||||
the brackets!) The text should be enclosed in the appropriate
|
||||
comment syntax for the file format. We also recommend that a
|
||||
file or class name and description of purpose be included on the
|
||||
same "printed page" as the copyright notice for easier
|
||||
identification within third-party archives.
|
||||
|
||||
Copyright [yyyy] [name of copyright owner]
|
||||
|
||||
Licensed under the Apache License, Version 2.0 (the "License");
|
||||
you may not use this file except in compliance with the License.
|
||||
You may obtain a copy of the License at
|
||||
|
||||
http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
||||
Unless required by applicable law or agreed to in writing, software
|
||||
distributed under the License is distributed on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
See the License for the specific language governing permissions and
|
||||
limitations under the License.
|
||||
@@ -0,0 +1,19 @@
|
||||
inifile puppet module
|
||||
|
||||
Copyright (C) 2012-2016 Puppet Labs, Inc.
|
||||
Copyright (C) 2012 Chris Price
|
||||
|
||||
Puppet Labs can be contacted at: info@puppetlabs.com
|
||||
|
||||
|
||||
Licensed under the Apache License, Version 2.0 (the "License");
|
||||
you may not use this file except in compliance with the License.
|
||||
You may obtain a copy of the License at
|
||||
|
||||
http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
||||
Unless required by applicable law or agreed to in writing, software
|
||||
distributed under the License is distributed on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
See the License for the specific language governing permissions and
|
||||
limitations under the License.
|
||||
Vendored
+2
@@ -0,0 +1,2 @@
|
||||
Puppet::Type.type(:ini_setting).provide(:ruby) do
|
||||
end
|
||||
+153
@@ -0,0 +1,153 @@
|
||||
# frozen_string_literal: true
|
||||
|
||||
require 'digest/md5'
|
||||
require 'puppet/parameter/boolean'
|
||||
|
||||
Puppet::Type.newtype(:ini_setting) do
|
||||
desc 'ini_settings is used to manage a single setting in an INI file'
|
||||
ensurable do
|
||||
desc 'Ensurable method handles modeling creation. It creates an ensure property'
|
||||
newvalue(:present) do
|
||||
provider.create
|
||||
end
|
||||
newvalue(:absent) do
|
||||
provider.destroy
|
||||
end
|
||||
def insync?(current)
|
||||
if @resource[:refreshonly]
|
||||
true
|
||||
else
|
||||
current == should
|
||||
end
|
||||
end
|
||||
defaultto :present
|
||||
end
|
||||
|
||||
def munge_boolean_md5(value)
|
||||
case value
|
||||
when true, :true, 'true', :yes, 'yes'
|
||||
:true
|
||||
when false, :false, 'false', :no, 'no'
|
||||
:false
|
||||
when :md5, 'md5'
|
||||
:md5
|
||||
else
|
||||
raise(_('expected a boolean value or :md5'))
|
||||
end
|
||||
end
|
||||
newparam(:name, namevar: true) do
|
||||
desc 'An arbitrary name used as the identity of the resource.'
|
||||
end
|
||||
|
||||
newparam(:section) do
|
||||
desc 'The name of the section in the ini file in which the setting should be defined.'
|
||||
defaultto('')
|
||||
end
|
||||
|
||||
newparam(:setting) do
|
||||
desc 'The name of the setting to be defined.'
|
||||
munge do |value|
|
||||
Puppet.warn('Settings should not have spaces in the value, we are going to strip the whitespace') if value.match?(%r{(^\s|\s$)})
|
||||
value.strip
|
||||
end
|
||||
end
|
||||
|
||||
newparam(:force_new_section_creation, boolean: true, parent: Puppet::Parameter::Boolean) do
|
||||
desc 'Create setting only if the section exists'
|
||||
defaultto(true)
|
||||
end
|
||||
|
||||
newparam(:path) do
|
||||
desc 'The ini file Puppet will ensure contains the specified setting.'
|
||||
validate do |value|
|
||||
raise(Puppet::Error, _("File paths must be fully qualified, not '%{value}'") % { value: value }) unless Puppet::Util.absolute_path?(value)
|
||||
end
|
||||
end
|
||||
|
||||
newparam(:show_diff) do
|
||||
desc 'Whether to display differences when the setting changes.'
|
||||
|
||||
defaultto :true
|
||||
|
||||
newvalues(:true, :md5, :false)
|
||||
|
||||
munge do |value|
|
||||
@resource.munge_boolean_md5(value)
|
||||
end
|
||||
end
|
||||
|
||||
newparam(:key_val_separator) do
|
||||
desc 'The separator string to use between each setting name and value.'
|
||||
defaultto(' = ')
|
||||
end
|
||||
|
||||
newproperty(:value) do
|
||||
desc 'The value of the setting to be defined.'
|
||||
|
||||
munge do |value|
|
||||
value = value.unwrap if value.respond_to?(:unwrap)
|
||||
if ([true, false].include? value) || value.is_a?(Numeric)
|
||||
value.to_s
|
||||
else
|
||||
value.strip.to_s
|
||||
end
|
||||
end
|
||||
|
||||
def should_to_s(newvalue)
|
||||
if @resource[:show_diff] == :true && Puppet[:show_diff]
|
||||
newvalue
|
||||
elsif @resource[:show_diff] == :md5 && Puppet[:show_diff]
|
||||
"{md5}#{Digest::MD5.hexdigest(newvalue.to_s)}"
|
||||
else
|
||||
'[redacted sensitive information]'
|
||||
end
|
||||
end
|
||||
|
||||
def is_to_s(value) # rubocop:disable Naming/PredicateName : Changing breaks the code (./.bundle/gems/gems/puppet-5.3.3-universal-darwin/lib/puppet/parameter.rb:525:in `to_s')
|
||||
should_to_s(value)
|
||||
end
|
||||
|
||||
def insync?(current)
|
||||
if @resource[:refreshonly]
|
||||
true
|
||||
else
|
||||
current == should
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
newparam(:section_prefix) do
|
||||
desc 'The prefix to the section name\'s header.'
|
||||
defaultto('[')
|
||||
end
|
||||
|
||||
newparam(:section_suffix) do
|
||||
desc 'The suffix to the section name\'s header.'
|
||||
defaultto(']')
|
||||
end
|
||||
|
||||
newparam(:indent_char) do
|
||||
desc 'The character to indent new settings with.'
|
||||
defaultto(' ')
|
||||
end
|
||||
|
||||
newparam(:indent_width) do
|
||||
desc 'The number of indent_chars to use to indent a new setting.'
|
||||
end
|
||||
|
||||
newparam(:refreshonly, boolean: true, parent: Puppet::Parameter::Boolean) do
|
||||
desc 'A flag indicating whether or not the ini_setting should be updated only when called as part of a refresh event'
|
||||
defaultto false
|
||||
end
|
||||
|
||||
def refresh
|
||||
return provider.destroy if self[:ensure] == :absent && self[:refreshonly]
|
||||
|
||||
# update the value in the provider, which will save the value to the ini file
|
||||
provider.value = self[:value] if self[:refreshonly]
|
||||
end
|
||||
|
||||
autorequire(:file) do
|
||||
Pathname.new(self[:path]).parent.to_s
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,13 @@
|
||||
Copyright (c) 2016-2017 Kogito UG <https://kogitoapp.com/>
|
||||
|
||||
Licensed under the Apache License, Version 2.0 (the "License");
|
||||
you may not use this file except in compliance with the License.
|
||||
You may obtain a copy of the License at
|
||||
|
||||
http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
||||
Unless required by applicable law or agreed to in writing, software
|
||||
distributed under the License is distributed on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
See the License for the specific language governing permissions and
|
||||
limitations under the License.
|
||||
+4
@@ -0,0 +1,4 @@
|
||||
require 'puppet/resource_api/simple_provider'
|
||||
|
||||
class Puppet::Provider::MinioClientAlias::MinioClientAlias < Puppet::ResourceApi::SimpleProvider
|
||||
end
|
||||
Vendored
+66
@@ -0,0 +1,66 @@
|
||||
# frozen_string_literal: true
|
||||
|
||||
require 'puppet/resource_api'
|
||||
|
||||
Puppet::ResourceApi.register_type(
|
||||
name: 'minio_client_alias',
|
||||
docs: <<-EOS,
|
||||
@summary Manages minio client aliases
|
||||
@example
|
||||
minio_client_alias { 'localminio':
|
||||
ensure => 'present',
|
||||
endpoint => 'http://localhost:9000',
|
||||
access_key => 'admin',
|
||||
secret_key => 'password',
|
||||
api_signature => 'S3v4',
|
||||
path_lookup_support =>'on',
|
||||
}
|
||||
|
||||
@example
|
||||
minio_client_alias { 'default':
|
||||
ensure => 'present',
|
||||
endpoint => 'http://localhost:9000',
|
||||
access_key => 'admin',
|
||||
secret_key => Sensitive('password'),
|
||||
}
|
||||
|
||||
**Autorequires**:
|
||||
* `File[/root/.minioclient]`
|
||||
EOS
|
||||
features: ['custom_insync'],
|
||||
attributes: {
|
||||
ensure: {
|
||||
type: 'Enum[present, absent]',
|
||||
desc: 'Whether this resource should be present or absent on the target system.',
|
||||
default: 'present',
|
||||
},
|
||||
name: {
|
||||
type: 'String',
|
||||
desc: 'The name of the resource you want to manage.',
|
||||
behaviour: :namevar,
|
||||
},
|
||||
endpoint: {
|
||||
type: 'String[1]',
|
||||
desc: 'The API endpoint url',
|
||||
},
|
||||
access_key: {
|
||||
type: 'Optional[String]',
|
||||
desc: 'The API access key',
|
||||
},
|
||||
secret_key: {
|
||||
type: 'Optional[Variant[Sensitive[String], String]]',
|
||||
desc: 'The API access secret',
|
||||
},
|
||||
api_signature: {
|
||||
type: "Optional[Enum['S3v4', 'S3v2']]",
|
||||
desc: 'The API signature',
|
||||
},
|
||||
path_lookup_support: {
|
||||
type: "Optional[Enum['on', 'off', 'auto']]",
|
||||
desc: 'Indicate whether dns or path style url requests are supported by the server.',
|
||||
},
|
||||
},
|
||||
autorequire: {
|
||||
file: '/root/.minioclient',
|
||||
},
|
||||
)
|
||||
@@ -0,0 +1,202 @@
|
||||
|
||||
Apache License
|
||||
Version 2.0, January 2004
|
||||
http://www.apache.org/licenses/
|
||||
|
||||
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
||||
|
||||
1. Definitions.
|
||||
|
||||
"License" shall mean the terms and conditions for use, reproduction,
|
||||
and distribution as defined by Sections 1 through 9 of this document.
|
||||
|
||||
"Licensor" shall mean the copyright owner or entity authorized by
|
||||
the copyright owner that is granting the License.
|
||||
|
||||
"Legal Entity" shall mean the union of the acting entity and all
|
||||
other entities that control, are controlled by, or are under common
|
||||
control with that entity. For the purposes of this definition,
|
||||
"control" means (i) the power, direct or indirect, to cause the
|
||||
direction or management of such entity, whether by contract or
|
||||
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
||||
outstanding shares, or (iii) beneficial ownership of such entity.
|
||||
|
||||
"You" (or "Your") shall mean an individual or Legal Entity
|
||||
exercising permissions granted by this License.
|
||||
|
||||
"Source" form shall mean the preferred form for making modifications,
|
||||
including but not limited to software source code, documentation
|
||||
source, and configuration files.
|
||||
|
||||
"Object" form shall mean any form resulting from mechanical
|
||||
transformation or translation of a Source form, including but
|
||||
not limited to compiled object code, generated documentation,
|
||||
and conversions to other media types.
|
||||
|
||||
"Work" shall mean the work of authorship, whether in Source or
|
||||
Object form, made available under the License, as indicated by a
|
||||
copyright notice that is included in or attached to the work
|
||||
(an example is provided in the Appendix below).
|
||||
|
||||
"Derivative Works" shall mean any work, whether in Source or Object
|
||||
form, that is based on (or derived from) the Work and for which the
|
||||
editorial revisions, annotations, elaborations, or other modifications
|
||||
represent, as a whole, an original work of authorship. For the purposes
|
||||
of this License, Derivative Works shall not include works that remain
|
||||
separable from, or merely link (or bind by name) to the interfaces of,
|
||||
the Work and Derivative Works thereof.
|
||||
|
||||
"Contribution" shall mean any work of authorship, including
|
||||
the original version of the Work and any modifications or additions
|
||||
to that Work or Derivative Works thereof, that is intentionally
|
||||
submitted to Licensor for inclusion in the Work by the copyright owner
|
||||
or by an individual or Legal Entity authorized to submit on behalf of
|
||||
the copyright owner. For the purposes of this definition, "submitted"
|
||||
means any form of electronic, verbal, or written communication sent
|
||||
to the Licensor or its representatives, including but not limited to
|
||||
communication on electronic mailing lists, source code control systems,
|
||||
and issue tracking systems that are managed by, or on behalf of, the
|
||||
Licensor for the purpose of discussing and improving the Work, but
|
||||
excluding communication that is conspicuously marked or otherwise
|
||||
designated in writing by the copyright owner as "Not a Contribution."
|
||||
|
||||
"Contributor" shall mean Licensor and any individual or Legal Entity
|
||||
on behalf of whom a Contribution has been received by Licensor and
|
||||
subsequently incorporated within the Work.
|
||||
|
||||
2. Grant of Copyright License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
copyright license to reproduce, prepare Derivative Works of,
|
||||
publicly display, publicly perform, sublicense, and distribute the
|
||||
Work and such Derivative Works in Source or Object form.
|
||||
|
||||
3. Grant of Patent License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
(except as stated in this section) patent license to make, have made,
|
||||
use, offer to sell, sell, import, and otherwise transfer the Work,
|
||||
where such license applies only to those patent claims licensable
|
||||
by such Contributor that are necessarily infringed by their
|
||||
Contribution(s) alone or by combination of their Contribution(s)
|
||||
with the Work to which such Contribution(s) was submitted. If You
|
||||
institute patent litigation against any entity (including a
|
||||
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
||||
or a Contribution incorporated within the Work constitutes direct
|
||||
or contributory patent infringement, then any patent licenses
|
||||
granted to You under this License for that Work shall terminate
|
||||
as of the date such litigation is filed.
|
||||
|
||||
4. Redistribution. You may reproduce and distribute copies of the
|
||||
Work or Derivative Works thereof in any medium, with or without
|
||||
modifications, and in Source or Object form, provided that You
|
||||
meet the following conditions:
|
||||
|
||||
(a) You must give any other recipients of the Work or
|
||||
Derivative Works a copy of this License; and
|
||||
|
||||
(b) You must cause any modified files to carry prominent notices
|
||||
stating that You changed the files; and
|
||||
|
||||
(c) You must retain, in the Source form of any Derivative Works
|
||||
that You distribute, all copyright, patent, trademark, and
|
||||
attribution notices from the Source form of the Work,
|
||||
excluding those notices that do not pertain to any part of
|
||||
the Derivative Works; and
|
||||
|
||||
(d) If the Work includes a "NOTICE" text file as part of its
|
||||
distribution, then any Derivative Works that You distribute must
|
||||
include a readable copy of the attribution notices contained
|
||||
within such NOTICE file, excluding those notices that do not
|
||||
pertain to any part of the Derivative Works, in at least one
|
||||
of the following places: within a NOTICE text file distributed
|
||||
as part of the Derivative Works; within the Source form or
|
||||
documentation, if provided along with the Derivative Works; or,
|
||||
within a display generated by the Derivative Works, if and
|
||||
wherever such third-party notices normally appear. The contents
|
||||
of the NOTICE file are for informational purposes only and
|
||||
do not modify the License. You may add Your own attribution
|
||||
notices within Derivative Works that You distribute, alongside
|
||||
or as an addendum to the NOTICE text from the Work, provided
|
||||
that such additional attribution notices cannot be construed
|
||||
as modifying the License.
|
||||
|
||||
You may add Your own copyright statement to Your modifications and
|
||||
may provide additional or different license terms and conditions
|
||||
for use, reproduction, or distribution of Your modifications, or
|
||||
for any such Derivative Works as a whole, provided Your use,
|
||||
reproduction, and distribution of the Work otherwise complies with
|
||||
the conditions stated in this License.
|
||||
|
||||
5. Submission of Contributions. Unless You explicitly state otherwise,
|
||||
any Contribution intentionally submitted for inclusion in the Work
|
||||
by You to the Licensor shall be under the terms and conditions of
|
||||
this License, without any additional terms or conditions.
|
||||
Notwithstanding the above, nothing herein shall supersede or modify
|
||||
the terms of any separate license agreement you may have executed
|
||||
with Licensor regarding such Contributions.
|
||||
|
||||
6. Trademarks. This License does not grant permission to use the trade
|
||||
names, trademarks, service marks, or product names of the Licensor,
|
||||
except as required for reasonable and customary use in describing the
|
||||
origin of the Work and reproducing the content of the NOTICE file.
|
||||
|
||||
7. Disclaimer of Warranty. Unless required by applicable law or
|
||||
agreed to in writing, Licensor provides the Work (and each
|
||||
Contributor provides its Contributions) on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
||||
implied, including, without limitation, any warranties or conditions
|
||||
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
||||
PARTICULAR PURPOSE. You are solely responsible for determining the
|
||||
appropriateness of using or redistributing the Work and assume any
|
||||
risks associated with Your exercise of permissions under this License.
|
||||
|
||||
8. Limitation of Liability. In no event and under no legal theory,
|
||||
whether in tort (including negligence), contract, or otherwise,
|
||||
unless required by applicable law (such as deliberate and grossly
|
||||
negligent acts) or agreed to in writing, shall any Contributor be
|
||||
liable to You for damages, including any direct, indirect, special,
|
||||
incidental, or consequential damages of any character arising as a
|
||||
result of this License or out of the use or inability to use the
|
||||
Work (including but not limited to damages for loss of goodwill,
|
||||
work stoppage, computer failure or malfunction, or any and all
|
||||
other commercial damages or losses), even if such Contributor
|
||||
has been advised of the possibility of such damages.
|
||||
|
||||
9. Accepting Warranty or Additional Liability. While redistributing
|
||||
the Work or Derivative Works thereof, You may choose to offer,
|
||||
and charge a fee for, acceptance of support, warranty, indemnity,
|
||||
or other liability obligations and/or rights consistent with this
|
||||
License. However, in accepting such obligations, You may act only
|
||||
on Your own behalf and on Your sole responsibility, not on behalf
|
||||
of any other Contributor, and only if You agree to indemnify,
|
||||
defend, and hold each Contributor harmless for any liability
|
||||
incurred by, or claims asserted against, such Contributor by reason
|
||||
of your accepting any such warranty or additional liability.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
APPENDIX: How to apply the Apache License to your work.
|
||||
|
||||
To apply the Apache License to your work, attach the following
|
||||
boilerplate notice, with the fields enclosed by brackets "[]"
|
||||
replaced with your own identifying information. (Don't include
|
||||
the brackets!) The text should be enclosed in the appropriate
|
||||
comment syntax for the file format. We also recommend that a
|
||||
file or class name and description of purpose be included on the
|
||||
same "printed page" as the copyright notice for easier
|
||||
identification within third-party archives.
|
||||
|
||||
Copyright [yyyy] [name of copyright owner]
|
||||
|
||||
Licensed under the Apache License, Version 2.0 (the "License");
|
||||
you may not use this file except in compliance with the License.
|
||||
You may obtain a copy of the License at
|
||||
|
||||
http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
||||
Unless required by applicable law or agreed to in writing, software
|
||||
distributed under the License is distributed on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
See the License for the specific language governing permissions and
|
||||
limitations under the License.
|
||||
@@ -0,0 +1,15 @@
|
||||
Puppet Module - puppetlabs-mysql
|
||||
|
||||
Copyright 2018 Puppet, Inc.
|
||||
|
||||
Licensed under the Apache License, Version 2.0 (the "License");
|
||||
you may not use this file except in compliance with the License.
|
||||
You may obtain a copy of the License at
|
||||
|
||||
http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
||||
Unless required by applicable law or agreed to in writing, software
|
||||
distributed under the License is distributed on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
See the License for the specific language governing permissions and
|
||||
limitations under the License.
|
||||
+2
@@ -0,0 +1,2 @@
|
||||
class Puppet::Provider::MysqlLoginPath::IniFile < Puppet::Provider
|
||||
end
|
||||
+4
@@ -0,0 +1,4 @@
|
||||
require 'puppet/resource_api/simple_provider'
|
||||
|
||||
class Puppet::Provider::MysqlLoginPath::MysqlLoginPath < Puppet::ResourceApi::SimpleProvider
|
||||
end
|
||||
+2
@@ -0,0 +1,2 @@
|
||||
class Puppet::Provider::MysqlLoginPath::Sensitive < Puppet::Pops::Types::PSensitiveType::Sensitive
|
||||
end
|
||||
+82
@@ -0,0 +1,82 @@
|
||||
# frozen_string_literal: true
|
||||
|
||||
require 'puppet/resource_api'
|
||||
|
||||
Puppet::ResourceApi.register_type(
|
||||
name: 'mysql_login_path',
|
||||
|
||||
docs: <<-DESCRIPTION,
|
||||
@summary Manage a MySQL login path.
|
||||
@see
|
||||
https://dev.mysql.com/doc/refman/8.0/en/mysql-config-editor.html
|
||||
@example
|
||||
mysql_login_path { 'local_socket':
|
||||
owner => 'root',
|
||||
host => 'localhost',
|
||||
user => 'root',
|
||||
password => Sensitive('secure'),
|
||||
socket => '/var/run/mysql/mysql.sock',
|
||||
ensure => present,
|
||||
}
|
||||
|
||||
mysql_login_path { 'local_tcp':
|
||||
owner => 'root',
|
||||
host => '127.0.0.1',
|
||||
user => 'root',
|
||||
password => Sensitive('more_secure'),
|
||||
port => 3306,
|
||||
ensure => present,
|
||||
}
|
||||
|
||||
This type provides Puppet with the capabilities to store authentication credentials in an obfuscated login path file
|
||||
named .mylogin.cnf created with the mysql_config_editor utility. Supports only MySQL Community Edition > v5.6.6.
|
||||
DESCRIPTION
|
||||
features: ['simple_get_filter', 'canonicalize'],
|
||||
title_patterns: [
|
||||
{
|
||||
pattern: %r{^(?<name>.*[^-])-(?<owner>.*)$},
|
||||
desc: 'Where the name of the and the owner are provided with a hyphen seperator'
|
||||
},
|
||||
{
|
||||
pattern: %r{^(?<name>.*)$},
|
||||
desc: 'Where only the name is provided'
|
||||
},
|
||||
],
|
||||
attributes: {
|
||||
ensure: {
|
||||
type: 'Enum[present, absent]',
|
||||
desc: 'Whether this resource should be present or absent on the target system.'
|
||||
},
|
||||
name: {
|
||||
type: 'String',
|
||||
desc: 'Name of the login path you want to manage.',
|
||||
behaviour: :namevar
|
||||
},
|
||||
owner: {
|
||||
type: 'String',
|
||||
desc: 'The user to whom the logon path should belong.',
|
||||
behaviour: :namevar,
|
||||
default: 'root'
|
||||
},
|
||||
host: {
|
||||
type: 'Optional[String]',
|
||||
desc: 'Host name to be entered into the login path.'
|
||||
},
|
||||
user: {
|
||||
type: 'Optional[String]',
|
||||
desc: 'Username to be entered into the login path.'
|
||||
},
|
||||
password: {
|
||||
type: 'Optional[Sensitive[String[1]]]',
|
||||
desc: 'Password to be entered into login path'
|
||||
},
|
||||
socket: {
|
||||
type: 'Optional[String]',
|
||||
desc: 'Socket path to be entered into login path'
|
||||
},
|
||||
port: {
|
||||
type: 'Optional[Integer[0,65535]]',
|
||||
desc: 'Port number to be entered into login path.'
|
||||
}
|
||||
},
|
||||
)
|
||||
@@ -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
|
||||
+2
@@ -0,0 +1,2 @@
|
||||
Puppet::Type.type(:network_config).provide(:interfaces) do
|
||||
end
|
||||
internal/gentypes/testdata/env/external_modules/network/lib/puppet/provider/network_config/redhat.rb
Vendored
+2
@@ -0,0 +1,2 @@
|
||||
Puppet::Type.type(:network_config).provide(:redhat) do
|
||||
end
|
||||
Vendored
+2
@@ -0,0 +1,2 @@
|
||||
Puppet::Type.type(:network_config).provide(:sles) do
|
||||
end
|
||||
+155
@@ -0,0 +1,155 @@
|
||||
require 'puppet/property/boolean'
|
||||
|
||||
begin
|
||||
require 'ipaddr'
|
||||
rescue LoadError
|
||||
Puppet.warning("#{__FILE__}:#{__LINE__}: ipaddr gem was not found")
|
||||
end
|
||||
|
||||
Puppet::Type.newtype(:network_config) do
|
||||
@doc = 'Manage non-volatile network 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
|
||||
|
||||
feature :hotpluggable, 'The system can hotplug interfaces'
|
||||
|
||||
feature :reconfigurable, <<-EOD
|
||||
The provider can update live interface configuration after the non-volatile
|
||||
network configuration is updated. This may entail a momentary network
|
||||
disruption as it may mean bringing down the interface for a short period.
|
||||
EOD
|
||||
|
||||
feature :startmode, 'The system can define startmode of an interface'
|
||||
|
||||
ensurable
|
||||
|
||||
newparam(:name) do
|
||||
isnamevar
|
||||
desc 'The name of the physical or logical network device'
|
||||
end
|
||||
|
||||
newproperty(:ipaddress) do
|
||||
desc 'The IP address of the network interfaces'
|
||||
if defined? IPAddr
|
||||
validate do |value|
|
||||
IPAddr.new value
|
||||
rescue IPAddr::InvalidAddressError
|
||||
raise ArgumentError, "#{self.class} requires a valid ipaddress for the ipaddress property"
|
||||
# provider.validate
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
newproperty(:netmask) do
|
||||
desc 'The subnet mask to apply to the interface'
|
||||
if defined? IPAddr
|
||||
validate do |value|
|
||||
ipa = IPAddr.new '127.0.0.1'
|
||||
ipa.mask(value)
|
||||
rescue IPAddr::InvalidAddressError
|
||||
begin
|
||||
ipz = IPAddr.new '::1'
|
||||
ipz.mask(value)
|
||||
rescue IPAddr::InvalidAddressError
|
||||
raise ArgumentError, "#{self.class} requires a valid netmask for the netmask property"
|
||||
end
|
||||
# provider.validate
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
newproperty(:method) do
|
||||
desc 'The method for determining an IP address for the interface'
|
||||
newvalues(:static, :manual, :dhcp, :loopback)
|
||||
|
||||
# Redhat systems frequently use 'none' in place of 'static', although
|
||||
# ultimately any values but dhcp or bootp are ignored and the interface
|
||||
# is static
|
||||
aliasvalue(:none, :static)
|
||||
|
||||
defaultto :dhcp
|
||||
end
|
||||
|
||||
newproperty(:family) do
|
||||
desc 'The address family to use for the interface'
|
||||
newvalues(:inet, :inet6)
|
||||
aliasvalue(:inet4, :inet)
|
||||
defaultto :inet
|
||||
end
|
||||
|
||||
newproperty(:onboot, parent: Puppet::Property::Boolean) do
|
||||
desc 'Whether to bring the interface up on boot'
|
||||
defaultto :true
|
||||
end
|
||||
|
||||
newproperty(:hotplug, required_features: :hotpluggable, parent: Puppet::Property::Boolean) do
|
||||
desc 'Allow/disallow hotplug support for this interface'
|
||||
defaultto :true
|
||||
end
|
||||
|
||||
newproperty(:startmode, required_features: :startmode) do
|
||||
desc 'Allow/disallow startmode support for this interface'
|
||||
defaultto :auto
|
||||
end
|
||||
|
||||
newparam(:reconfigure, required_features: :reconfigurable, parent: Puppet::Property::Boolean) do
|
||||
desc 'Reconfigure the interface after the configuration has been updated'
|
||||
end
|
||||
|
||||
newproperty(:mtu) do
|
||||
desc 'The Maximum Transmission Unit size to use for the interface'
|
||||
validate do |value|
|
||||
# reject floating point and negative integers
|
||||
# XXX this lets 1500.0 pass
|
||||
if value.is_a? Numeric
|
||||
raise ArgumentError, "#{value} is not a valid mtu (must be a positive integer)" unless value.integer?
|
||||
else
|
||||
raise ArgumentError, "#{value} is not a valid mtu (must be a positive integer)" unless value =~ %r{^\d+$}
|
||||
end
|
||||
|
||||
# Intel 82598 & 82599 chips support MTUs up to 16110; is there any
|
||||
# hardware in the wild that supports larger frames?
|
||||
#
|
||||
# It appears loopback devices routinely have large MTU values; Eg. 65536
|
||||
#
|
||||
# Frames small than 64bytes are discarded as runts. Smallest valid MTU
|
||||
# is 42 with a 802.1q header and 46 without.
|
||||
min_mtu = 42
|
||||
max_mtu = 65_536
|
||||
raise ArgumentError, "#{value} is not in the valid mtu range (#{min_mtu} .. #{max_mtu})" unless (min_mtu..max_mtu).cover?(value.to_i)
|
||||
end
|
||||
end
|
||||
|
||||
newproperty(:mode) do
|
||||
desc 'The exclusive mode the interface should operate in'
|
||||
# :bond and :bridge may be added in the future
|
||||
newvalues(:raw, :vlan)
|
||||
|
||||
defaultto :raw
|
||||
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'
|
||||
|
||||
def s?(hash = @is)
|
||||
hash.keys.sort.map { |key| "#{key} => #{hash[key]}" }.join(', ')
|
||||
end
|
||||
|
||||
def should_to_s(hash = @should)
|
||||
hash.keys.sort.map { |key| "#{key} => #{hash[key]}" }.join(', ')
|
||||
end
|
||||
|
||||
defaultto {}
|
||||
|
||||
validate do |value|
|
||||
raise ArgumentError, "#{self.class} requires a hash for the 'options' parameter" unless value.is_a? Hash
|
||||
# provider.validate
|
||||
end
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,202 @@
|
||||
|
||||
Apache License
|
||||
Version 2.0, January 2004
|
||||
http://www.apache.org/licenses/
|
||||
|
||||
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
||||
|
||||
1. Definitions.
|
||||
|
||||
"License" shall mean the terms and conditions for use, reproduction,
|
||||
and distribution as defined by Sections 1 through 9 of this document.
|
||||
|
||||
"Licensor" shall mean the copyright owner or entity authorized by
|
||||
the copyright owner that is granting the License.
|
||||
|
||||
"Legal Entity" shall mean the union of the acting entity and all
|
||||
other entities that control, are controlled by, or are under common
|
||||
control with that entity. For the purposes of this definition,
|
||||
"control" means (i) the power, direct or indirect, to cause the
|
||||
direction or management of such entity, whether by contract or
|
||||
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
||||
outstanding shares, or (iii) beneficial ownership of such entity.
|
||||
|
||||
"You" (or "Your") shall mean an individual or Legal Entity
|
||||
exercising permissions granted by this License.
|
||||
|
||||
"Source" form shall mean the preferred form for making modifications,
|
||||
including but not limited to software source code, documentation
|
||||
source, and configuration files.
|
||||
|
||||
"Object" form shall mean any form resulting from mechanical
|
||||
transformation or translation of a Source form, including but
|
||||
not limited to compiled object code, generated documentation,
|
||||
and conversions to other media types.
|
||||
|
||||
"Work" shall mean the work of authorship, whether in Source or
|
||||
Object form, made available under the License, as indicated by a
|
||||
copyright notice that is included in or attached to the work
|
||||
(an example is provided in the Appendix below).
|
||||
|
||||
"Derivative Works" shall mean any work, whether in Source or Object
|
||||
form, that is based on (or derived from) the Work and for which the
|
||||
editorial revisions, annotations, elaborations, or other modifications
|
||||
represent, as a whole, an original work of authorship. For the purposes
|
||||
of this License, Derivative Works shall not include works that remain
|
||||
separable from, or merely link (or bind by name) to the interfaces of,
|
||||
the Work and Derivative Works thereof.
|
||||
|
||||
"Contribution" shall mean any work of authorship, including
|
||||
the original version of the Work and any modifications or additions
|
||||
to that Work or Derivative Works thereof, that is intentionally
|
||||
submitted to Licensor for inclusion in the Work by the copyright owner
|
||||
or by an individual or Legal Entity authorized to submit on behalf of
|
||||
the copyright owner. For the purposes of this definition, "submitted"
|
||||
means any form of electronic, verbal, or written communication sent
|
||||
to the Licensor or its representatives, including but not limited to
|
||||
communication on electronic mailing lists, source code control systems,
|
||||
and issue tracking systems that are managed by, or on behalf of, the
|
||||
Licensor for the purpose of discussing and improving the Work, but
|
||||
excluding communication that is conspicuously marked or otherwise
|
||||
designated in writing by the copyright owner as "Not a Contribution."
|
||||
|
||||
"Contributor" shall mean Licensor and any individual or Legal Entity
|
||||
on behalf of whom a Contribution has been received by Licensor and
|
||||
subsequently incorporated within the Work.
|
||||
|
||||
2. Grant of Copyright License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
copyright license to reproduce, prepare Derivative Works of,
|
||||
publicly display, publicly perform, sublicense, and distribute the
|
||||
Work and such Derivative Works in Source or Object form.
|
||||
|
||||
3. Grant of Patent License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
(except as stated in this section) patent license to make, have made,
|
||||
use, offer to sell, sell, import, and otherwise transfer the Work,
|
||||
where such license applies only to those patent claims licensable
|
||||
by such Contributor that are necessarily infringed by their
|
||||
Contribution(s) alone or by combination of their Contribution(s)
|
||||
with the Work to which such Contribution(s) was submitted. If You
|
||||
institute patent litigation against any entity (including a
|
||||
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
||||
or a Contribution incorporated within the Work constitutes direct
|
||||
or contributory patent infringement, then any patent licenses
|
||||
granted to You under this License for that Work shall terminate
|
||||
as of the date such litigation is filed.
|
||||
|
||||
4. Redistribution. You may reproduce and distribute copies of the
|
||||
Work or Derivative Works thereof in any medium, with or without
|
||||
modifications, and in Source or Object form, provided that You
|
||||
meet the following conditions:
|
||||
|
||||
(a) You must give any other recipients of the Work or
|
||||
Derivative Works a copy of this License; and
|
||||
|
||||
(b) You must cause any modified files to carry prominent notices
|
||||
stating that You changed the files; and
|
||||
|
||||
(c) You must retain, in the Source form of any Derivative Works
|
||||
that You distribute, all copyright, patent, trademark, and
|
||||
attribution notices from the Source form of the Work,
|
||||
excluding those notices that do not pertain to any part of
|
||||
the Derivative Works; and
|
||||
|
||||
(d) If the Work includes a "NOTICE" text file as part of its
|
||||
distribution, then any Derivative Works that You distribute must
|
||||
include a readable copy of the attribution notices contained
|
||||
within such NOTICE file, excluding those notices that do not
|
||||
pertain to any part of the Derivative Works, in at least one
|
||||
of the following places: within a NOTICE text file distributed
|
||||
as part of the Derivative Works; within the Source form or
|
||||
documentation, if provided along with the Derivative Works; or,
|
||||
within a display generated by the Derivative Works, if and
|
||||
wherever such third-party notices normally appear. The contents
|
||||
of the NOTICE file are for informational purposes only and
|
||||
do not modify the License. You may add Your own attribution
|
||||
notices within Derivative Works that You distribute, alongside
|
||||
or as an addendum to the NOTICE text from the Work, provided
|
||||
that such additional attribution notices cannot be construed
|
||||
as modifying the License.
|
||||
|
||||
You may add Your own copyright statement to Your modifications and
|
||||
may provide additional or different license terms and conditions
|
||||
for use, reproduction, or distribution of Your modifications, or
|
||||
for any such Derivative Works as a whole, provided Your use,
|
||||
reproduction, and distribution of the Work otherwise complies with
|
||||
the conditions stated in this License.
|
||||
|
||||
5. Submission of Contributions. Unless You explicitly state otherwise,
|
||||
any Contribution intentionally submitted for inclusion in the Work
|
||||
by You to the Licensor shall be under the terms and conditions of
|
||||
this License, without any additional terms or conditions.
|
||||
Notwithstanding the above, nothing herein shall supersede or modify
|
||||
the terms of any separate license agreement you may have executed
|
||||
with Licensor regarding such Contributions.
|
||||
|
||||
6. Trademarks. This License does not grant permission to use the trade
|
||||
names, trademarks, service marks, or product names of the Licensor,
|
||||
except as required for reasonable and customary use in describing the
|
||||
origin of the Work and reproducing the content of the NOTICE file.
|
||||
|
||||
7. Disclaimer of Warranty. Unless required by applicable law or
|
||||
agreed to in writing, Licensor provides the Work (and each
|
||||
Contributor provides its Contributions) on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
||||
implied, including, without limitation, any warranties or conditions
|
||||
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
||||
PARTICULAR PURPOSE. You are solely responsible for determining the
|
||||
appropriateness of using or redistributing the Work and assume any
|
||||
risks associated with Your exercise of permissions under this License.
|
||||
|
||||
8. Limitation of Liability. In no event and under no legal theory,
|
||||
whether in tort (including negligence), contract, or otherwise,
|
||||
unless required by applicable law (such as deliberate and grossly
|
||||
negligent acts) or agreed to in writing, shall any Contributor be
|
||||
liable to You for damages, including any direct, indirect, special,
|
||||
incidental, or consequential damages of any character arising as a
|
||||
result of this License or out of the use or inability to use the
|
||||
Work (including but not limited to damages for loss of goodwill,
|
||||
work stoppage, computer failure or malfunction, or any and all
|
||||
other commercial damages or losses), even if such Contributor
|
||||
has been advised of the possibility of such damages.
|
||||
|
||||
9. Accepting Warranty or Additional Liability. While redistributing
|
||||
the Work or Derivative Works thereof, You may choose to offer,
|
||||
and charge a fee for, acceptance of support, warranty, indemnity,
|
||||
or other liability obligations and/or rights consistent with this
|
||||
License. However, in accepting such obligations, You may act only
|
||||
on Your own behalf and on Your sole responsibility, not on behalf
|
||||
of any other Contributor, and only if You agree to indemnify,
|
||||
defend, and hold each Contributor harmless for any liability
|
||||
incurred by, or claims asserted against, such Contributor by reason
|
||||
of your accepting any such warranty or additional liability.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
APPENDIX: How to apply the Apache License to your work.
|
||||
|
||||
To apply the Apache License to your work, attach the following
|
||||
boilerplate notice, with the fields enclosed by brackets "[]"
|
||||
replaced with your own identifying information. (Don't include
|
||||
the brackets!) The text should be enclosed in the appropriate
|
||||
comment syntax for the file format. We also recommend that a
|
||||
file or class name and description of purpose be included on the
|
||||
same "printed page" as the copyright notice for easier
|
||||
identification within third-party archives.
|
||||
|
||||
Copyright [yyyy] [name of copyright owner]
|
||||
|
||||
Licensed under the Apache License, Version 2.0 (the "License");
|
||||
you may not use this file except in compliance with the License.
|
||||
You may obtain a copy of the License at
|
||||
|
||||
http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
||||
Unless required by applicable law or agreed to in writing, software
|
||||
distributed under the License is distributed on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
See the License for the specific language governing permissions and
|
||||
limitations under the License.
|
||||
@@ -0,0 +1,15 @@
|
||||
Puppet Module - puppetlabs-reboot
|
||||
|
||||
Copyright 2013 - 2018 Puppet, Inc.
|
||||
|
||||
Licensed under the Apache License, Version 2.0 (the "License");
|
||||
you may not use this file except in compliance with the License.
|
||||
You may obtain a copy of the License at
|
||||
|
||||
http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
||||
Unless required by applicable law or agreed to in writing, software
|
||||
distributed under the License is distributed on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
See the License for the specific language governing permissions and
|
||||
limitations under the License.
|
||||
+2
@@ -0,0 +1,2 @@
|
||||
Puppet::Type.type(:reboot).provide(:linux) do
|
||||
end
|
||||
+2
@@ -0,0 +1,2 @@
|
||||
Puppet::Type.type(:reboot).provide(:posix) do
|
||||
end
|
||||
Vendored
+2
@@ -0,0 +1,2 @@
|
||||
Puppet::Type.type(:reboot).provide(:windows) do
|
||||
end
|
||||
+214
@@ -0,0 +1,214 @@
|
||||
# frozen_string_literal: true
|
||||
|
||||
Puppet::Type.newtype(:reboot) do
|
||||
@doc = _(<<-'EOT',
|
||||
Manages system reboots. The `reboot` type is typically
|
||||
used in situations where a resource performs a change, e.g.
|
||||
package install, and a reboot is required to complete
|
||||
installation. Only if the package is installed should the
|
||||
reboot be triggered.
|
||||
|
||||
Sample usage:
|
||||
|
||||
package { 'Microsoft .NET Framework 4.5':
|
||||
ensure => installed,
|
||||
source => '\\server\share\dotnetfx45_full_x86_x64.exe',
|
||||
install_options => ['/Passive', '/NoRestart'],
|
||||
provider => windows,
|
||||
}
|
||||
reboot { 'after':
|
||||
subscribe => Package['Microsoft .NET Framework 4.5'],
|
||||
}
|
||||
|
||||
A reboot resource can also check if the system is in a
|
||||
reboot pending state, and if so, reboot the system. For
|
||||
example, if you have a package that cannot be installed
|
||||
while a reboot is pending.
|
||||
|
||||
Sample usage:
|
||||
|
||||
reboot { 'before':
|
||||
when => pending,
|
||||
}
|
||||
package { 'Microsoft .NET Framework 4.5':
|
||||
ensure => installed,
|
||||
source => '\\server\share\dotnetfx45_full_x86_x64.exe',
|
||||
install_options => ['/Passive', '/NoRestart'],
|
||||
provider => windows,
|
||||
require => Reboot['before'],
|
||||
}
|
||||
|
||||
A reboot resource can also finish the run and then reboot the system. For
|
||||
example, if you have a few packages that all require reboots but will not block
|
||||
each other during the run.
|
||||
|
||||
Sample usage:
|
||||
|
||||
package { 'Microsoft .NET Framework 4.5':
|
||||
ensure => installed,
|
||||
source => '\\server\share\dotnetfx45_full_x86_x64.exe',
|
||||
install_options => ['/Passive', '/NoRestart'],
|
||||
provider => windows,
|
||||
}
|
||||
reboot { 'after_run':
|
||||
apply => finished,
|
||||
subscribe => Package['Microsoft .NET Framework 4.5'],
|
||||
}
|
||||
|
||||
On windows we can limit the reasons for a pending reboot.
|
||||
|
||||
Sample usage:
|
||||
|
||||
reboot { 'renames only':
|
||||
when => pending,
|
||||
onlyif => 'pending_rename_file_operations',
|
||||
}
|
||||
EOT
|
||||
)
|
||||
|
||||
feature :manages_reboot_pending, _('The provider can detect if a reboot is pending, and reboot as needed.')
|
||||
|
||||
newparam(:name) do
|
||||
desc _('The name of the reboot resource. Used for uniqueness.')
|
||||
isnamevar
|
||||
end
|
||||
|
||||
newproperty(:when) do
|
||||
desc "When to check for, and if needed, perform a reboot. If `pending`,
|
||||
then the provider will check if a reboot is pending, and only
|
||||
if needed, reboot the system. If `refreshed` then the reboot
|
||||
will only be performed in response to a refresh event from
|
||||
another resource, e.g. `package`."
|
||||
newvalue(:refreshed)
|
||||
newvalue(:pending, required_features: :manages_reboot_pending)
|
||||
defaultto :refreshed
|
||||
|
||||
def insync?(is)
|
||||
case should
|
||||
when :refreshed
|
||||
true # we're always insync
|
||||
else
|
||||
super
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
newparam(:onlyif, required_features: [:manages_reboot_pending]) do
|
||||
desc "For pending reboots, only reboot if the reboot is pending
|
||||
for one of the supplied reasons."
|
||||
|
||||
possible_values = [
|
||||
:reboot_required, :component_based_servicing, :windows_auto_update,
|
||||
:pending_file_rename_operations, :package_installer,
|
||||
:pending_computer_rename, :pending_dsc_reboot, :pending_ccm_reboot, :pending_domain_join
|
||||
]
|
||||
|
||||
validate do |values|
|
||||
raise ArgumentError, _('There must be at least one element in the list') if values == []
|
||||
|
||||
values = [values] unless values.is_a?(Array)
|
||||
|
||||
values.each do |value|
|
||||
value = value.to_sym if value.is_a?(String)
|
||||
|
||||
raise ArgumentError, _("value must be one of %{possible_values.join(', ')}") % { possible_values: 'translateable' } unless possible_values.include?(value)
|
||||
end
|
||||
end
|
||||
|
||||
munge do |values|
|
||||
values = [values] unless values.is_a?(Array)
|
||||
|
||||
values.map(&:to_sym)
|
||||
end
|
||||
end
|
||||
|
||||
newparam(:unless, required_features: [:manages_reboot_pending]) do
|
||||
desc 'For pending reboots, ignore the supplied reasons when checking pennding reboot'
|
||||
|
||||
possible_values = [
|
||||
:reboot_required, :component_based_servicing, :windows_auto_update,
|
||||
:pending_file_rename_operations, :package_installer,
|
||||
:pending_computer_rename, :pending_dsc_reboot, :pending_ccm_reboot, :pending_domain_join
|
||||
]
|
||||
|
||||
validate do |values|
|
||||
raise ArgumentError, _('There must be at least one element in the list') if values == []
|
||||
|
||||
values = [values] unless values.is_a?(Array)
|
||||
|
||||
values.each do |value|
|
||||
value = value.to_sym if value.is_a?(String)
|
||||
|
||||
raise ArgumentError, _("value must be one of %{possible_values.join(', ')}") % { possible_values: 'translateable' } unless possible_values.include?(value)
|
||||
end
|
||||
end
|
||||
|
||||
munge do |values|
|
||||
values = [values] unless values.is_a?(Array)
|
||||
|
||||
values.map(&:to_sym)
|
||||
end
|
||||
end
|
||||
|
||||
newparam(:apply) do
|
||||
desc "When to apply the reboot. If `immediately`, then the provider
|
||||
will stop applying additional resources and apply the reboot once
|
||||
puppet has finished syncing. If `finished`, it will continue
|
||||
applying resources and then perform a reboot at the end of the
|
||||
run. The default is `immediately`."
|
||||
newvalues(:immediately, :finished)
|
||||
defaultto :immediately
|
||||
end
|
||||
|
||||
newparam(:message) do
|
||||
desc _('The message to log when the reboot is performed.')
|
||||
|
||||
validate do |value|
|
||||
raise ArgumentError, _('A non-empty message must be specified.') if value.nil? || value == ''
|
||||
|
||||
# Maximum command line length in Windows is 8191 characters, so this is
|
||||
# an approximation based on the other parts of the shutdown command
|
||||
raise ArgumentError, _('The given message must not exceed 8000 characters.') if value.length > 8000
|
||||
end
|
||||
|
||||
defaultto 'Puppet is rebooting the computer'
|
||||
end
|
||||
|
||||
newparam(:timeout) do
|
||||
desc "The amount of time in seconds to wait between the time the reboot
|
||||
is requested and when the reboot is performed. The default timeout
|
||||
is 60 seconds. Note that this time starts once puppet has exited the
|
||||
current run."
|
||||
|
||||
validate do |value|
|
||||
raise ArgumentError, _('The timeout must be an integer.') unless %r{^\d+$}.match?(value.to_s)
|
||||
end
|
||||
|
||||
defaultto 60
|
||||
end
|
||||
|
||||
@rebooting = false
|
||||
|
||||
class << self
|
||||
attr_reader :rebooting
|
||||
end
|
||||
|
||||
class << self
|
||||
attr_writer :rebooting
|
||||
end
|
||||
|
||||
def refresh
|
||||
case self[:when]
|
||||
when :refreshed
|
||||
if self.class.rebooting
|
||||
Puppet.debug('Reboot already scheduled; skipping')
|
||||
else
|
||||
self.class.rebooting = true
|
||||
Puppet.notice("Scheduling system reboot with message: \"#{self[:message]}\"")
|
||||
provider.reboot
|
||||
end
|
||||
else
|
||||
Puppet.debug('Skipping reboot')
|
||||
end
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,202 @@
|
||||
|
||||
Apache License
|
||||
Version 2.0, January 2004
|
||||
http://www.apache.org/licenses/
|
||||
|
||||
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
||||
|
||||
1. Definitions.
|
||||
|
||||
"License" shall mean the terms and conditions for use, reproduction,
|
||||
and distribution as defined by Sections 1 through 9 of this document.
|
||||
|
||||
"Licensor" shall mean the copyright owner or entity authorized by
|
||||
the copyright owner that is granting the License.
|
||||
|
||||
"Legal Entity" shall mean the union of the acting entity and all
|
||||
other entities that control, are controlled by, or are under common
|
||||
control with that entity. For the purposes of this definition,
|
||||
"control" means (i) the power, direct or indirect, to cause the
|
||||
direction or management of such entity, whether by contract or
|
||||
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
||||
outstanding shares, or (iii) beneficial ownership of such entity.
|
||||
|
||||
"You" (or "Your") shall mean an individual or Legal Entity
|
||||
exercising permissions granted by this License.
|
||||
|
||||
"Source" form shall mean the preferred form for making modifications,
|
||||
including but not limited to software source code, documentation
|
||||
source, and configuration files.
|
||||
|
||||
"Object" form shall mean any form resulting from mechanical
|
||||
transformation or translation of a Source form, including but
|
||||
not limited to compiled object code, generated documentation,
|
||||
and conversions to other media types.
|
||||
|
||||
"Work" shall mean the work of authorship, whether in Source or
|
||||
Object form, made available under the License, as indicated by a
|
||||
copyright notice that is included in or attached to the work
|
||||
(an example is provided in the Appendix below).
|
||||
|
||||
"Derivative Works" shall mean any work, whether in Source or Object
|
||||
form, that is based on (or derived from) the Work and for which the
|
||||
editorial revisions, annotations, elaborations, or other modifications
|
||||
represent, as a whole, an original work of authorship. For the purposes
|
||||
of this License, Derivative Works shall not include works that remain
|
||||
separable from, or merely link (or bind by name) to the interfaces of,
|
||||
the Work and Derivative Works thereof.
|
||||
|
||||
"Contribution" shall mean any work of authorship, including
|
||||
the original version of the Work and any modifications or additions
|
||||
to that Work or Derivative Works thereof, that is intentionally
|
||||
submitted to Licensor for inclusion in the Work by the copyright owner
|
||||
or by an individual or Legal Entity authorized to submit on behalf of
|
||||
the copyright owner. For the purposes of this definition, "submitted"
|
||||
means any form of electronic, verbal, or written communication sent
|
||||
to the Licensor or its representatives, including but not limited to
|
||||
communication on electronic mailing lists, source code control systems,
|
||||
and issue tracking systems that are managed by, or on behalf of, the
|
||||
Licensor for the purpose of discussing and improving the Work, but
|
||||
excluding communication that is conspicuously marked or otherwise
|
||||
designated in writing by the copyright owner as "Not a Contribution."
|
||||
|
||||
"Contributor" shall mean Licensor and any individual or Legal Entity
|
||||
on behalf of whom a Contribution has been received by Licensor and
|
||||
subsequently incorporated within the Work.
|
||||
|
||||
2. Grant of Copyright License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
copyright license to reproduce, prepare Derivative Works of,
|
||||
publicly display, publicly perform, sublicense, and distribute the
|
||||
Work and such Derivative Works in Source or Object form.
|
||||
|
||||
3. Grant of Patent License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
(except as stated in this section) patent license to make, have made,
|
||||
use, offer to sell, sell, import, and otherwise transfer the Work,
|
||||
where such license applies only to those patent claims licensable
|
||||
by such Contributor that are necessarily infringed by their
|
||||
Contribution(s) alone or by combination of their Contribution(s)
|
||||
with the Work to which such Contribution(s) was submitted. If You
|
||||
institute patent litigation against any entity (including a
|
||||
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
||||
or a Contribution incorporated within the Work constitutes direct
|
||||
or contributory patent infringement, then any patent licenses
|
||||
granted to You under this License for that Work shall terminate
|
||||
as of the date such litigation is filed.
|
||||
|
||||
4. Redistribution. You may reproduce and distribute copies of the
|
||||
Work or Derivative Works thereof in any medium, with or without
|
||||
modifications, and in Source or Object form, provided that You
|
||||
meet the following conditions:
|
||||
|
||||
(a) You must give any other recipients of the Work or
|
||||
Derivative Works a copy of this License; and
|
||||
|
||||
(b) You must cause any modified files to carry prominent notices
|
||||
stating that You changed the files; and
|
||||
|
||||
(c) You must retain, in the Source form of any Derivative Works
|
||||
that You distribute, all copyright, patent, trademark, and
|
||||
attribution notices from the Source form of the Work,
|
||||
excluding those notices that do not pertain to any part of
|
||||
the Derivative Works; and
|
||||
|
||||
(d) If the Work includes a "NOTICE" text file as part of its
|
||||
distribution, then any Derivative Works that You distribute must
|
||||
include a readable copy of the attribution notices contained
|
||||
within such NOTICE file, excluding those notices that do not
|
||||
pertain to any part of the Derivative Works, in at least one
|
||||
of the following places: within a NOTICE text file distributed
|
||||
as part of the Derivative Works; within the Source form or
|
||||
documentation, if provided along with the Derivative Works; or,
|
||||
within a display generated by the Derivative Works, if and
|
||||
wherever such third-party notices normally appear. The contents
|
||||
of the NOTICE file are for informational purposes only and
|
||||
do not modify the License. You may add Your own attribution
|
||||
notices within Derivative Works that You distribute, alongside
|
||||
or as an addendum to the NOTICE text from the Work, provided
|
||||
that such additional attribution notices cannot be construed
|
||||
as modifying the License.
|
||||
|
||||
You may add Your own copyright statement to Your modifications and
|
||||
may provide additional or different license terms and conditions
|
||||
for use, reproduction, or distribution of Your modifications, or
|
||||
for any such Derivative Works as a whole, provided Your use,
|
||||
reproduction, and distribution of the Work otherwise complies with
|
||||
the conditions stated in this License.
|
||||
|
||||
5. Submission of Contributions. Unless You explicitly state otherwise,
|
||||
any Contribution intentionally submitted for inclusion in the Work
|
||||
by You to the Licensor shall be under the terms and conditions of
|
||||
this License, without any additional terms or conditions.
|
||||
Notwithstanding the above, nothing herein shall supersede or modify
|
||||
the terms of any separate license agreement you may have executed
|
||||
with Licensor regarding such Contributions.
|
||||
|
||||
6. Trademarks. This License does not grant permission to use the trade
|
||||
names, trademarks, service marks, or product names of the Licensor,
|
||||
except as required for reasonable and customary use in describing the
|
||||
origin of the Work and reproducing the content of the NOTICE file.
|
||||
|
||||
7. Disclaimer of Warranty. Unless required by applicable law or
|
||||
agreed to in writing, Licensor provides the Work (and each
|
||||
Contributor provides its Contributions) on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
||||
implied, including, without limitation, any warranties or conditions
|
||||
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
||||
PARTICULAR PURPOSE. You are solely responsible for determining the
|
||||
appropriateness of using or redistributing the Work and assume any
|
||||
risks associated with Your exercise of permissions under this License.
|
||||
|
||||
8. Limitation of Liability. In no event and under no legal theory,
|
||||
whether in tort (including negligence), contract, or otherwise,
|
||||
unless required by applicable law (such as deliberate and grossly
|
||||
negligent acts) or agreed to in writing, shall any Contributor be
|
||||
liable to You for damages, including any direct, indirect, special,
|
||||
incidental, or consequential damages of any character arising as a
|
||||
result of this License or out of the use or inability to use the
|
||||
Work (including but not limited to damages for loss of goodwill,
|
||||
work stoppage, computer failure or malfunction, or any and all
|
||||
other commercial damages or losses), even if such Contributor
|
||||
has been advised of the possibility of such damages.
|
||||
|
||||
9. Accepting Warranty or Additional Liability. While redistributing
|
||||
the Work or Derivative Works thereof, You may choose to offer,
|
||||
and charge a fee for, acceptance of support, warranty, indemnity,
|
||||
or other liability obligations and/or rights consistent with this
|
||||
License. However, in accepting such obligations, You may act only
|
||||
on Your own behalf and on Your sole responsibility, not on behalf
|
||||
of any other Contributor, and only if You agree to indemnify,
|
||||
defend, and hold each Contributor harmless for any liability
|
||||
incurred by, or claims asserted against, such Contributor by reason
|
||||
of your accepting any such warranty or additional liability.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
APPENDIX: How to apply the Apache License to your work.
|
||||
|
||||
To apply the Apache License to your work, attach the following
|
||||
boilerplate notice, with the fields enclosed by brackets "[]"
|
||||
replaced with your own identifying information. (Don't include
|
||||
the brackets!) The text should be enclosed in the appropriate
|
||||
comment syntax for the file format. We also recommend that a
|
||||
file or class name and description of purpose be included on the
|
||||
same "printed page" as the copyright notice for easier
|
||||
identification within third-party archives.
|
||||
|
||||
Copyright [yyyy] [name of copyright owner]
|
||||
|
||||
Licensed under the Apache License, Version 2.0 (the "License");
|
||||
you may not use this file except in compliance with the License.
|
||||
You may obtain a copy of the License at
|
||||
|
||||
http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
||||
Unless required by applicable law or agreed to in writing, software
|
||||
distributed under the License is distributed on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
See the License for the specific language governing permissions and
|
||||
limitations under the License.
|
||||
@@ -0,0 +1,23 @@
|
||||
stdlib puppet module
|
||||
|
||||
Copyright (C) 2011-2016 Puppet Labs, Inc.
|
||||
|
||||
and some parts:
|
||||
|
||||
Copyright (C) 2011 Krzysztof Wilczynski
|
||||
|
||||
|
||||
Puppet Labs can be contacted at: info@puppetlabs.com
|
||||
|
||||
|
||||
Licensed under the Apache License, Version 2.0 (the "License");
|
||||
you may not use this file except in compliance with the License.
|
||||
You may obtain a copy of the License at
|
||||
|
||||
http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
||||
Unless required by applicable law or agreed to in writing, software
|
||||
distributed under the License is distributed on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
See the License for the specific language governing permissions and
|
||||
limitations under the License.
|
||||
Vendored
+2
@@ -0,0 +1,2 @@
|
||||
Puppet::Type.type(:file_line).provide(:ruby) do
|
||||
end
|
||||
+54
@@ -0,0 +1,54 @@
|
||||
# frozen_string_literal: true
|
||||
|
||||
Puppet::Type.newtype(:anchor) do
|
||||
desc <<-DOC
|
||||
@summary
|
||||
A simple resource type intended to be used as an anchor in a composite class.
|
||||
|
||||
> Note: this has been replaced by core puppet `contain()` method. Please see https://puppet.com/docs/puppet/latest/lang_containment.html for more information.
|
||||
|
||||
In Puppet 2.6, when a class declares another class, the resources in the
|
||||
interior class are not contained by the exterior class. This interacts badly
|
||||
with the pattern of composing complex modules from smaller classes, as it
|
||||
makes it impossible for end users to specify order relationships between the
|
||||
exterior class and other modules.
|
||||
|
||||
The anchor type lets you work around this. By sandwiching any interior
|
||||
classes between two no-op resources that _are_ contained by the exterior
|
||||
class, you can ensure that all resources in the module are contained.
|
||||
|
||||
```
|
||||
class ntp {
|
||||
# These classes will have the correct order relationship with each
|
||||
# other. However, without anchors, they won't have any order
|
||||
# relationship to Class['ntp'].
|
||||
class { 'ntp::package': }
|
||||
-> class { 'ntp::config': }
|
||||
-> class { 'ntp::service': }
|
||||
|
||||
# These two resources "anchor" the composed classes within the ntp
|
||||
# class.
|
||||
anchor { 'ntp::begin': } -> Class['ntp::package']
|
||||
Class['ntp::service'] -> anchor { 'ntp::end': }
|
||||
}
|
||||
```
|
||||
|
||||
This allows the end user of the ntp module to establish require and before
|
||||
relationships with Class['ntp']:
|
||||
|
||||
```
|
||||
class { 'ntp': } -> class { 'mcollective': }
|
||||
class { 'mcollective': } -> class { 'ntp': }
|
||||
```
|
||||
|
||||
DOC
|
||||
|
||||
newparam :name do
|
||||
desc 'The name of the anchor resource.'
|
||||
end
|
||||
def refresh
|
||||
# We don't do anything with them, but we need this to
|
||||
# show that we are "refresh aware" and not break the
|
||||
# chain of propagation.
|
||||
end
|
||||
end
|
||||
+194
@@ -0,0 +1,194 @@
|
||||
# frozen_string_literal: true
|
||||
|
||||
Puppet::Type.newtype(:file_line) do
|
||||
desc <<-DOC
|
||||
@summary
|
||||
Ensures that a given line is contained within a file.
|
||||
|
||||
The implementation matches the full line, including whitespace at the
|
||||
beginning and end. If the line is not contained in the given file, Puppet
|
||||
will append the line to the end of the file to ensure the desired state.
|
||||
Multiple resources may be declared to manage multiple lines in the same file.
|
||||
|
||||
* Ensure Example
|
||||
```
|
||||
file_line { 'sudo_rule':
|
||||
path => '/etc/sudoers',
|
||||
line => '%sudo ALL=(ALL) ALL',
|
||||
}
|
||||
|
||||
file_line { 'sudo_rule_nopw':
|
||||
path => '/etc/sudoers',
|
||||
line => '%sudonopw ALL=(ALL) NOPASSWD: ALL',
|
||||
}
|
||||
```
|
||||
In this example, Puppet will ensure both of the specified lines are
|
||||
contained in the file /etc/sudoers.
|
||||
|
||||
* Match Example
|
||||
|
||||
```
|
||||
file_line { 'bashrc_proxy':
|
||||
ensure => present,
|
||||
path => '/etc/bashrc',
|
||||
line => 'export HTTP_PROXY=http://squid.puppetlabs.vm:3128',
|
||||
match => '^export HTTP_PROXY=',
|
||||
}
|
||||
```
|
||||
|
||||
In this code example match will look for a line beginning with export
|
||||
followed by HTTP_PROXY and replace it with the value in line.
|
||||
|
||||
* Examples With `ensure => absent`:
|
||||
|
||||
This type has two behaviors when `ensure => absent` is set.
|
||||
|
||||
One possibility is to set `match => ...` and `match_for_absence => true`,
|
||||
as in the following example:
|
||||
|
||||
```
|
||||
file_line { 'bashrc_proxy':
|
||||
ensure => absent,
|
||||
path => '/etc/bashrc',
|
||||
match => '^export HTTP_PROXY=',
|
||||
match_for_absence => true,
|
||||
}
|
||||
```
|
||||
|
||||
In this code example match will look for a line beginning with export
|
||||
followed by HTTP_PROXY and delete it. If multiple lines match, an
|
||||
error will be raised unless the `multiple => true` parameter is set.
|
||||
|
||||
Note that the `line => ...` parameter would be accepted BUT IGNORED in
|
||||
the above example.
|
||||
|
||||
The second way of using `ensure => absent` is to specify a `line => ...`,
|
||||
and no match:
|
||||
|
||||
```
|
||||
file_line { 'bashrc_proxy':
|
||||
ensure => absent,
|
||||
path => '/etc/bashrc',
|
||||
line => 'export HTTP_PROXY=http://squid.puppetlabs.vm:3128',
|
||||
}
|
||||
```
|
||||
|
||||
> *Note:*
|
||||
When ensuring lines are absent this way, the default behavior
|
||||
this time is to always remove all lines matching, and this behavior
|
||||
can't be disabled.
|
||||
|
||||
* Encoding example:
|
||||
|
||||
```
|
||||
file_line { "XScreenSaver":
|
||||
ensure => present,
|
||||
path => '/root/XScreenSaver',
|
||||
line => "*lock: 10:00:00",
|
||||
match => '^*lock:',
|
||||
encoding => "iso-8859-1",
|
||||
}
|
||||
```
|
||||
|
||||
Files with special characters that are not valid UTF-8 will give the
|
||||
error message "invalid byte sequence in UTF-8". In this case, determine
|
||||
the correct file encoding and specify the correct encoding using the
|
||||
encoding attribute, the value of which needs to be a valid Ruby character
|
||||
encoding.
|
||||
|
||||
**Autorequires:** If Puppet is managing the file that will contain the line
|
||||
being managed, the file_line resource will autorequire that file.
|
||||
DOC
|
||||
|
||||
ensurable do
|
||||
desc 'Manage the state of this type.'
|
||||
defaultvalues
|
||||
defaultto :present
|
||||
end
|
||||
|
||||
newparam(:name, namevar: true) do
|
||||
desc 'An arbitrary name used as the identity of the resource.'
|
||||
end
|
||||
|
||||
newparam(:match) do
|
||||
desc 'An optional ruby regular expression to run against existing lines in the file.
|
||||
If a match is found, we replace that line rather than adding a new line.
|
||||
A regex comparison is performed against the line value and if it does not
|
||||
match an exception will be raised.'
|
||||
end
|
||||
|
||||
newparam(:match_for_absence) do
|
||||
desc 'An optional value to determine if match should be applied when ensure => absent.
|
||||
If set to true and match is set, the line that matches match will be deleted.
|
||||
If set to false (the default), match is ignored when ensure => absent.
|
||||
When `ensure => present`, match_for_absence is ignored.'
|
||||
newvalues(true, false)
|
||||
defaultto false
|
||||
end
|
||||
|
||||
newparam(:multiple) do
|
||||
desc 'An optional value to determine if match can change multiple lines.
|
||||
If set to false, an exception will be raised if more than one line matches'
|
||||
newvalues(true, false)
|
||||
end
|
||||
|
||||
newparam(:after) do
|
||||
desc 'An optional value used to specify the line after which we will add any new lines. (Existing lines are added in place)
|
||||
This is also takes a regex.'
|
||||
end
|
||||
|
||||
# The line property never changes; the type only ever performs a create() or
|
||||
# destroy(). line is a property in order to allow it to correctly handle
|
||||
# Sensitive type values. Because it is a property which will never change,
|
||||
# it should never be considered out of sync.
|
||||
newproperty(:line) do
|
||||
desc 'The line to be appended to the file or used to replace matches found by the match attribute.'
|
||||
|
||||
def retrieve
|
||||
@resource[:line]
|
||||
end
|
||||
end
|
||||
|
||||
newparam(:path) do
|
||||
desc 'The file Puppet will ensure contains the line specified by the line parameter.'
|
||||
validate do |value|
|
||||
raise Puppet::Error, "File paths must be fully qualified, not '#{value}'" unless Puppet::Util.absolute_path?(value)
|
||||
end
|
||||
end
|
||||
|
||||
newparam(:replace) do
|
||||
desc 'If true, replace line that matches. If false, do not write line if a match is found'
|
||||
newvalues(true, false)
|
||||
defaultto true
|
||||
end
|
||||
|
||||
newparam(:replace_all_matches_not_matching_line) do
|
||||
desc 'Configures the behavior of replacing all lines in a file which match the `match` parameter regular expression, regardless of whether the specified line is already present in the file.'
|
||||
|
||||
newvalues(true, false)
|
||||
defaultto false
|
||||
end
|
||||
|
||||
newparam(:encoding) do
|
||||
desc 'For files that are not UTF-8 encoded, specify encoding such as iso-8859-1'
|
||||
defaultto 'UTF-8'
|
||||
end
|
||||
|
||||
newparam(:append_on_no_match) do
|
||||
desc 'If true, append line if match is not found. If false, do not append line if a match is not found'
|
||||
newvalues(true, false)
|
||||
defaultto true
|
||||
end
|
||||
|
||||
# Autorequire the file resource if it's being managed
|
||||
autorequire(:file) do
|
||||
self[:path]
|
||||
end
|
||||
validate do
|
||||
raise(Puppet::Error, 'multiple must be true when replace_all_matches_not_matching_line is true') if self[:replace_all_matches_not_matching_line].to_s == 'true' && self[:multiple].to_s == 'false'
|
||||
raise(Puppet::Error, 'replace must be true when replace_all_matches_not_matching_line is true') if self[:replace_all_matches_not_matching_line].to_s == 'true' && self[:replace].to_s == 'false'
|
||||
|
||||
raise(Puppet::Error, 'line is a required attribute') if !self[:line] && !((self[:ensure].to_s == 'absent') && (self[:match_for_absence].to_s == 'true') && self[:match])
|
||||
raise(Puppet::Error, 'path is a required attribute') unless self[:path]
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,201 @@
|
||||
Apache License
|
||||
Version 2.0, January 2004
|
||||
http://www.apache.org/licenses/
|
||||
|
||||
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
||||
|
||||
1. Definitions.
|
||||
|
||||
"License" shall mean the terms and conditions for use, reproduction,
|
||||
and distribution as defined by Sections 1 through 9 of this document.
|
||||
|
||||
"Licensor" shall mean the copyright owner or entity authorized by
|
||||
the copyright owner that is granting the License.
|
||||
|
||||
"Legal Entity" shall mean the union of the acting entity and all
|
||||
other entities that control, are controlled by, or are under common
|
||||
control with that entity. For the purposes of this definition,
|
||||
"control" means (i) the power, direct or indirect, to cause the
|
||||
direction or management of such entity, whether by contract or
|
||||
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
||||
outstanding shares, or (iii) beneficial ownership of such entity.
|
||||
|
||||
"You" (or "Your") shall mean an individual or Legal Entity
|
||||
exercising permissions granted by this License.
|
||||
|
||||
"Source" form shall mean the preferred form for making modifications,
|
||||
including but not limited to software source code, documentation
|
||||
source, and configuration files.
|
||||
|
||||
"Object" form shall mean any form resulting from mechanical
|
||||
transformation or translation of a Source form, including but
|
||||
not limited to compiled object code, generated documentation,
|
||||
and conversions to other media types.
|
||||
|
||||
"Work" shall mean the work of authorship, whether in Source or
|
||||
Object form, made available under the License, as indicated by a
|
||||
copyright notice that is included in or attached to the work
|
||||
(an example is provided in the Appendix below).
|
||||
|
||||
"Derivative Works" shall mean any work, whether in Source or Object
|
||||
form, that is based on (or derived from) the Work and for which the
|
||||
editorial revisions, annotations, elaborations, or other modifications
|
||||
represent, as a whole, an original work of authorship. For the purposes
|
||||
of this License, Derivative Works shall not include works that remain
|
||||
separable from, or merely link (or bind by name) to the interfaces of,
|
||||
the Work and Derivative Works thereof.
|
||||
|
||||
"Contribution" shall mean any work of authorship, including
|
||||
the original version of the Work and any modifications or additions
|
||||
to that Work or Derivative Works thereof, that is intentionally
|
||||
submitted to Licensor for inclusion in the Work by the copyright owner
|
||||
or by an individual or Legal Entity authorized to submit on behalf of
|
||||
the copyright owner. For the purposes of this definition, "submitted"
|
||||
means any form of electronic, verbal, or written communication sent
|
||||
to the Licensor or its representatives, including but not limited to
|
||||
communication on electronic mailing lists, source code control systems,
|
||||
and issue tracking systems that are managed by, or on behalf of, the
|
||||
Licensor for the purpose of discussing and improving the Work, but
|
||||
excluding communication that is conspicuously marked or otherwise
|
||||
designated in writing by the copyright owner as "Not a Contribution."
|
||||
|
||||
"Contributor" shall mean Licensor and any individual or Legal Entity
|
||||
on behalf of whom a Contribution has been received by Licensor and
|
||||
subsequently incorporated within the Work.
|
||||
|
||||
2. Grant of Copyright License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
copyright license to reproduce, prepare Derivative Works of,
|
||||
publicly display, publicly perform, sublicense, and distribute the
|
||||
Work and such Derivative Works in Source or Object form.
|
||||
|
||||
3. Grant of Patent License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
(except as stated in this section) patent license to make, have made,
|
||||
use, offer to sell, sell, import, and otherwise transfer the Work,
|
||||
where such license applies only to those patent claims licensable
|
||||
by such Contributor that are necessarily infringed by their
|
||||
Contribution(s) alone or by combination of their Contribution(s)
|
||||
with the Work to which such Contribution(s) was submitted. If You
|
||||
institute patent litigation against any entity (including a
|
||||
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
||||
or a Contribution incorporated within the Work constitutes direct
|
||||
or contributory patent infringement, then any patent licenses
|
||||
granted to You under this License for that Work shall terminate
|
||||
as of the date such litigation is filed.
|
||||
|
||||
4. Redistribution. You may reproduce and distribute copies of the
|
||||
Work or Derivative Works thereof in any medium, with or without
|
||||
modifications, and in Source or Object form, provided that You
|
||||
meet the following conditions:
|
||||
|
||||
(a) You must give any other recipients of the Work or
|
||||
Derivative Works a copy of this License; and
|
||||
|
||||
(b) You must cause any modified files to carry prominent notices
|
||||
stating that You changed the files; and
|
||||
|
||||
(c) You must retain, in the Source form of any Derivative Works
|
||||
that You distribute, all copyright, patent, trademark, and
|
||||
attribution notices from the Source form of the Work,
|
||||
excluding those notices that do not pertain to any part of
|
||||
the Derivative Works; and
|
||||
|
||||
(d) If the Work includes a "NOTICE" text file as part of its
|
||||
distribution, then any Derivative Works that You distribute must
|
||||
include a readable copy of the attribution notices contained
|
||||
within such NOTICE file, excluding those notices that do not
|
||||
pertain to any part of the Derivative Works, in at least one
|
||||
of the following places: within a NOTICE text file distributed
|
||||
as part of the Derivative Works; within the Source form or
|
||||
documentation, if provided along with the Derivative Works; or,
|
||||
within a display generated by the Derivative Works, if and
|
||||
wherever such third-party notices normally appear. The contents
|
||||
of the NOTICE file are for informational purposes only and
|
||||
do not modify the License. You may add Your own attribution
|
||||
notices within Derivative Works that You distribute, alongside
|
||||
or as an addendum to the NOTICE text from the Work, provided
|
||||
that such additional attribution notices cannot be construed
|
||||
as modifying the License.
|
||||
|
||||
You may add Your own copyright statement to Your modifications and
|
||||
may provide additional or different license terms and conditions
|
||||
for use, reproduction, or distribution of Your modifications, or
|
||||
for any such Derivative Works as a whole, provided Your use,
|
||||
reproduction, and distribution of the Work otherwise complies with
|
||||
the conditions stated in this License.
|
||||
|
||||
5. Submission of Contributions. Unless You explicitly state otherwise,
|
||||
any Contribution intentionally submitted for inclusion in the Work
|
||||
by You to the Licensor shall be under the terms and conditions of
|
||||
this License, without any additional terms or conditions.
|
||||
Notwithstanding the above, nothing herein shall supersede or modify
|
||||
the terms of any separate license agreement you may have executed
|
||||
with Licensor regarding such Contributions.
|
||||
|
||||
6. Trademarks. This License does not grant permission to use the trade
|
||||
names, trademarks, service marks, or product names of the Licensor,
|
||||
except as required for reasonable and customary use in describing the
|
||||
origin of the Work and reproducing the content of the NOTICE file.
|
||||
|
||||
7. Disclaimer of Warranty. Unless required by applicable law or
|
||||
agreed to in writing, Licensor provides the Work (and each
|
||||
Contributor provides its Contributions) on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
||||
implied, including, without limitation, any warranties or conditions
|
||||
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
||||
PARTICULAR PURPOSE. You are solely responsible for determining the
|
||||
appropriateness of using or redistributing the Work and assume any
|
||||
risks associated with Your exercise of permissions under this License.
|
||||
|
||||
8. Limitation of Liability. In no event and under no legal theory,
|
||||
whether in tort (including negligence), contract, or otherwise,
|
||||
unless required by applicable law (such as deliberate and grossly
|
||||
negligent acts) or agreed to in writing, shall any Contributor be
|
||||
liable to You for damages, including any direct, indirect, special,
|
||||
incidental, or consequential damages of any character arising as a
|
||||
result of this License or out of the use or inability to use the
|
||||
Work (including but not limited to damages for loss of goodwill,
|
||||
work stoppage, computer failure or malfunction, or any and all
|
||||
other commercial damages or losses), even if such Contributor
|
||||
has been advised of the possibility of such damages.
|
||||
|
||||
9. Accepting Warranty or Additional Liability. While redistributing
|
||||
the Work or Derivative Works thereof, You may choose to offer,
|
||||
and charge a fee for, acceptance of support, warranty, indemnity,
|
||||
or other liability obligations and/or rights consistent with this
|
||||
License. However, in accepting such obligations, You may act only
|
||||
on Your own behalf and on Your sole responsibility, not on behalf
|
||||
of any other Contributor, and only if You agree to indemnify,
|
||||
defend, and hold each Contributor harmless for any liability
|
||||
incurred by, or claims asserted against, such Contributor by reason
|
||||
of your accepting any such warranty or additional liability.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
APPENDIX: How to apply the Apache License to your work.
|
||||
|
||||
To apply the Apache License to your work, attach the following
|
||||
boilerplate notice, with the fields enclosed by brackets "[]"
|
||||
replaced with your own identifying information. (Don't include
|
||||
the brackets!) The text should be enclosed in the appropriate
|
||||
comment syntax for the file format. We also recommend that a
|
||||
file or class name and description of purpose be included on the
|
||||
same "printed page" as the copyright notice for easier
|
||||
identification within third-party archives.
|
||||
|
||||
Copyright [yyyy] [name of copyright owner]
|
||||
|
||||
Licensed under the Apache License, Version 2.0 (the "License");
|
||||
you may not use this file except in compliance with the License.
|
||||
You may obtain a copy of the License at
|
||||
|
||||
http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
||||
Unless required by applicable law or agreed to in writing, software
|
||||
distributed under the License is distributed on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
See the License for the specific language governing permissions and
|
||||
limitations under the License.
|
||||
Vendored
+2
@@ -0,0 +1,2 @@
|
||||
Puppet::Type.type(:yumrepo).provide(:inifile) do
|
||||
end
|
||||
+462
@@ -0,0 +1,462 @@
|
||||
require 'uri'
|
||||
|
||||
Puppet::Type.newtype(:yumrepo) do
|
||||
@doc = <<-'EOT'
|
||||
@summary The client-side description of a yum repository.
|
||||
|
||||
Repository configurations are found by parsing `/etc/yum.conf` and the files
|
||||
indicated by the `reposdir` option in that file (see `yum.conf(5)` for
|
||||
details).
|
||||
|
||||
Most parameters are identical to the ones documented
|
||||
in the `yum.conf(5)` man page.
|
||||
|
||||
Continuation lines that yum supports (for the `baseurl`, for example)
|
||||
are not supported. This type does not attempt to read or verify the
|
||||
existence of files listed in the `include` attribute."
|
||||
|
||||
EOT
|
||||
|
||||
# Ensure yumrepos can be removed too.
|
||||
ensurable
|
||||
# Doc string for properties that can be made 'absent'
|
||||
ABSENT_DOC = 'Set this to `absent` to remove it from the file completely.'.freeze
|
||||
# False can be false/0/no and True can be true/1/yes in yum.
|
||||
YUM_BOOLEAN = %r{^(true|false|0|1|no|yes)$}.freeze
|
||||
YUM_BOOLEAN_DOC = 'Valid values are: false/0/no or true/1/yes.'.freeze
|
||||
|
||||
# Common munge logic for YUM_BOOLEAN values. Munges for two requirements:
|
||||
# 1) Because of how regex validation works in Puppet::Parameter::Value,
|
||||
# Boolean false and lowercase false will not be considered invalid. However,
|
||||
# if the user specified false (or true), they meant False (or True).
|
||||
# 2) In order for parameter removal to work correctly, when absent is passed
|
||||
# as a string it needs to be munged back to a symbol.
|
||||
munge_yum_bool = proc do |val|
|
||||
(val.to_s == 'absent') ? :absent : val.to_s.capitalize
|
||||
end
|
||||
|
||||
VALID_SCHEMES = ['file', 'http', 'https', 'ftp'].freeze
|
||||
|
||||
newparam(:name, namevar: true) do
|
||||
desc "The name of the repository. This corresponds to the
|
||||
`repositoryid` parameter in `yum.conf(5)`."
|
||||
end
|
||||
|
||||
newparam(:target) do
|
||||
desc 'The filepath of the local repository file, can be either relative or absolute. If a valid filepath is not specified, the target is created as a new section in `yum.conf(5)`'
|
||||
|
||||
defaultto :absent
|
||||
end
|
||||
|
||||
newproperty(:descr) do
|
||||
desc "A human-readable description of the repository.
|
||||
This corresponds to the name parameter in `yum.conf(5)`.
|
||||
#{ABSENT_DOC}"
|
||||
|
||||
newvalues(%r{.*}, :absent)
|
||||
end
|
||||
|
||||
newproperty(:mirrorlist) do
|
||||
desc "The URL that holds the list of mirrors for this repository.
|
||||
#{ABSENT_DOC}"
|
||||
|
||||
newvalues(%r{.*}, :absent)
|
||||
validate do |value|
|
||||
next if value.to_s == 'absent'
|
||||
parsed = URI.parse(value)
|
||||
|
||||
unless VALID_SCHEMES.include?(parsed.scheme)
|
||||
raise _('Must be a valid URL')
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
newproperty(:baseurl) do
|
||||
desc "The URL for this repository. #{ABSENT_DOC}"
|
||||
|
||||
newvalues(%r{.*}, :absent)
|
||||
validate do |value|
|
||||
next if value.to_s == 'absent'
|
||||
|
||||
value.split(%r{\s+}).each do |uri|
|
||||
parsed = URI.parse(uri)
|
||||
|
||||
unless VALID_SCHEMES.include?(parsed.scheme)
|
||||
raise _('Must be a valid URL')
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
newproperty(:enabled) do
|
||||
desc "Whether this repository is enabled.
|
||||
#{YUM_BOOLEAN_DOC}
|
||||
#{ABSENT_DOC}"
|
||||
|
||||
newvalues(YUM_BOOLEAN, :absent)
|
||||
munge(&munge_yum_bool)
|
||||
end
|
||||
|
||||
newproperty(:gpgcheck) do
|
||||
desc "Whether to check the GPG signature on packages installed
|
||||
from this repository.
|
||||
#{YUM_BOOLEAN_DOC}
|
||||
#{ABSENT_DOC}"
|
||||
|
||||
newvalues(YUM_BOOLEAN, :absent)
|
||||
munge(&munge_yum_bool)
|
||||
end
|
||||
|
||||
newproperty(:payload_gpgcheck) do
|
||||
desc "Whether to check the GPG signature of the packages payload.
|
||||
#{YUM_BOOLEAN_DOC}
|
||||
#{ABSENT_DOC}"
|
||||
|
||||
newvalues(YUM_BOOLEAN, :absent)
|
||||
munge(&munge_yum_bool)
|
||||
end
|
||||
|
||||
newproperty(:repo_gpgcheck) do
|
||||
desc "Whether to check the GPG signature on repodata.
|
||||
#{YUM_BOOLEAN_DOC}
|
||||
#{ABSENT_DOC}"
|
||||
|
||||
newvalues(YUM_BOOLEAN, :absent)
|
||||
munge(&munge_yum_bool)
|
||||
end
|
||||
|
||||
newproperty(:gpgkey) do
|
||||
desc "The URL for the GPG key with which packages from this
|
||||
repository are signed. #{ABSENT_DOC}"
|
||||
|
||||
newvalues(%r{.*}, :absent)
|
||||
validate do |value|
|
||||
next if value.to_s == 'absent'
|
||||
|
||||
value.split(%r{\s+}).each do |uri|
|
||||
parsed = URI.parse(uri)
|
||||
|
||||
unless VALID_SCHEMES.include?(parsed.scheme)
|
||||
raise _('Must be a valid URL')
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
newproperty(:mirrorlist_expire) do
|
||||
desc "Time (in seconds) after which the mirrorlist locally cached
|
||||
will expire.\n#{ABSENT_DOC}"
|
||||
|
||||
newvalues(%r{^[0-9]+$}, :absent)
|
||||
end
|
||||
|
||||
newproperty(:include) do
|
||||
desc "The URL of a remote file containing additional yum configuration
|
||||
settings. Puppet does not check for this file's existence or validity.
|
||||
#{ABSENT_DOC}"
|
||||
|
||||
newvalues(%r{.*}, :absent)
|
||||
validate do |value|
|
||||
next if value.to_s == 'absent'
|
||||
parsed = URI.parse(value)
|
||||
|
||||
unless VALID_SCHEMES.include?(parsed.scheme)
|
||||
raise _('Must be a valid URL')
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
newproperty(:exclude) do
|
||||
desc "The string of package names or shell globs separated by spaces to exclude.
|
||||
Packages that match the package name given or shell globs will never be
|
||||
considered in updates or installs for this repo.
|
||||
#{ABSENT_DOC}"
|
||||
|
||||
newvalues(%r{.*}, :absent)
|
||||
end
|
||||
|
||||
newproperty(:gpgcakey) do
|
||||
desc "The URL for the GPG CA key for this repository. #{ABSENT_DOC}"
|
||||
|
||||
newvalues(%r{.*}, :absent)
|
||||
validate do |value|
|
||||
next if value.to_s == 'absent'
|
||||
parsed = URI.parse(value)
|
||||
|
||||
unless VALID_SCHEMES.include?(parsed.scheme)
|
||||
raise _('Must be a valid URL')
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
newproperty(:includepkgs) do
|
||||
desc "The string of package names or shell globs separated by spaces to
|
||||
include. If this is set, only packages matching one of the package
|
||||
names or shell globs will be considered for update or install
|
||||
from this repository. #{ABSENT_DOC}"
|
||||
|
||||
newvalues(%r{.*}, :absent)
|
||||
end
|
||||
|
||||
newproperty(:enablegroups) do
|
||||
desc "Whether yum will allow the use of package groups for this
|
||||
repository.
|
||||
#{YUM_BOOLEAN_DOC}
|
||||
#{ABSENT_DOC}"
|
||||
|
||||
newvalues(YUM_BOOLEAN, :absent)
|
||||
munge(&munge_yum_bool)
|
||||
end
|
||||
|
||||
newproperty(:module_hotfixes) do
|
||||
desc "Whether packages from this repo can be installed into modules.
|
||||
#{YUM_BOOLEAN_DOC}
|
||||
#{ABSENT_DOC}"
|
||||
|
||||
newvalues(YUM_BOOLEAN, :absent)
|
||||
munge(&munge_yum_bool)
|
||||
end
|
||||
|
||||
newproperty(:failovermethod) do
|
||||
desc "The failover method for this repository; should be either
|
||||
`roundrobin` or `priority`. #{ABSENT_DOC}"
|
||||
|
||||
newvalues(%r{^roundrobin|priority$}, :absent)
|
||||
end
|
||||
|
||||
newproperty(:keepalive) do
|
||||
desc "Whether HTTP/1.1 keepalive should be used with this repository.
|
||||
#{YUM_BOOLEAN_DOC}
|
||||
#{ABSENT_DOC}"
|
||||
|
||||
newvalues(YUM_BOOLEAN, :absent)
|
||||
munge(&munge_yum_bool)
|
||||
end
|
||||
|
||||
newproperty(:retries) do
|
||||
desc "Set the number of times any attempt to retrieve a file should
|
||||
retry before returning an error. Setting this to `0` makes yum
|
||||
try forever.\n#{ABSENT_DOC}"
|
||||
|
||||
newvalues(%r{^[0-9]+$}, :absent)
|
||||
end
|
||||
|
||||
newproperty(:http_caching) do
|
||||
desc "What to cache from this repository. #{ABSENT_DOC}"
|
||||
|
||||
newvalues(%r{^(packages|all|none)$}, :absent)
|
||||
end
|
||||
|
||||
newproperty(:timeout) do
|
||||
desc "Number of seconds to wait for a connection before timing
|
||||
out. #{ABSENT_DOC}"
|
||||
|
||||
newvalues(%r{^\d+$}, :absent)
|
||||
end
|
||||
|
||||
newproperty(:metadata_expire) do
|
||||
desc "Number of seconds after which the metadata will expire.
|
||||
#{ABSENT_DOC}"
|
||||
|
||||
newvalues(%r{^([0-9]+[dhm]?|never)$}, :absent)
|
||||
end
|
||||
|
||||
newproperty(:protect) do
|
||||
desc "Enable or disable protection for this repository. Requires
|
||||
that the `protectbase` plugin is installed and enabled.
|
||||
#{YUM_BOOLEAN_DOC}
|
||||
#{ABSENT_DOC}"
|
||||
|
||||
newvalues(YUM_BOOLEAN, :absent)
|
||||
munge(&munge_yum_bool)
|
||||
end
|
||||
|
||||
newproperty(:priority) do
|
||||
desc "Priority of this repository. Can be any integer value
|
||||
(including negative). Requires that the `priorities` plugin
|
||||
is installed and enabled.
|
||||
#{ABSENT_DOC}"
|
||||
|
||||
newvalues(%r{^-?\d+$}, :absent)
|
||||
end
|
||||
|
||||
newproperty(:minrate) do
|
||||
desc "Sets the low speed threshold in bytes per second.
|
||||
If the server is sending data slower than this for at least
|
||||
`timeout` seconds, Yum aborts the connection. The default is
|
||||
`1000`.
|
||||
#{ABSENT_DOC}"
|
||||
|
||||
newvalues(%r{^\d+$}, :absent)
|
||||
end
|
||||
|
||||
newproperty(:throttle) do
|
||||
desc "Enable bandwidth throttling for downloads. This option
|
||||
can be expressed as a absolute data rate in bytes/sec or a
|
||||
percentage `60%`. An SI prefix (k, M or G) may be appended
|
||||
to the data rate values.\n#{ABSENT_DOC}"
|
||||
|
||||
newvalues(%r{^\d+[kMG%]?$}, :absent)
|
||||
end
|
||||
|
||||
newproperty(:bandwidth) do
|
||||
desc "Use to specify the maximum available network bandwidth
|
||||
in bytes/second. Used with the `throttle` option. If `throttle`
|
||||
is a percentage and `bandwidth` is `0` then bandwidth throttling
|
||||
will be disabled. If `throttle` is expressed as a data rate then
|
||||
this option is ignored.\n#{ABSENT_DOC}"
|
||||
|
||||
newvalues(%r{^\d+[kMG]?$}, :absent)
|
||||
end
|
||||
|
||||
newproperty(:cost) do
|
||||
desc "Cost of this repository. #{ABSENT_DOC}"
|
||||
|
||||
newvalues(%r{^\d+$}, :absent)
|
||||
end
|
||||
|
||||
newproperty(:proxy) do
|
||||
desc "URL of a proxy server that Yum should use when accessing this repository.
|
||||
This attribute can also be set to '_none_' (or '' for EL >= 8 only),
|
||||
which will make Yum bypass any global proxy settings when accessing this repository.
|
||||
#{ABSENT_DOC}"
|
||||
|
||||
newvalues(%r{.*}, :absent)
|
||||
validate do |value|
|
||||
next if %r{^(absent|_none_)$}.match?(value.to_s)
|
||||
next if value.to_s.empty? && Facter.value('os.release.major').to_i >= 8
|
||||
|
||||
parsed = URI.parse(value)
|
||||
unless VALID_SCHEMES.include?(parsed.scheme)
|
||||
raise _('Must be a valid URL')
|
||||
end
|
||||
end
|
||||
|
||||
munge do |value|
|
||||
return '' if Facter.value('os.distro.release.major').to_i >= 8 && value.to_s == '_none_'
|
||||
super(value)
|
||||
end
|
||||
end
|
||||
|
||||
newproperty(:proxy_username) do
|
||||
desc "Username for this proxy. #{ABSENT_DOC}"
|
||||
|
||||
newvalues(%r{.*}, :absent)
|
||||
end
|
||||
|
||||
newproperty(:proxy_password) do
|
||||
desc "Password for this proxy. #{ABSENT_DOC}"
|
||||
|
||||
newvalues(%r{.*}, :absent)
|
||||
end
|
||||
|
||||
newproperty(:s3_enabled) do
|
||||
desc "Access the repository via S3.
|
||||
#{YUM_BOOLEAN_DOC}
|
||||
#{ABSENT_DOC}"
|
||||
|
||||
newvalues(YUM_BOOLEAN, :absent)
|
||||
munge(&munge_yum_bool)
|
||||
end
|
||||
|
||||
newproperty(:sslcacert) do
|
||||
desc "Path to the directory containing the databases of the
|
||||
certificate authorities yum should use to verify SSL certificates.
|
||||
#{ABSENT_DOC}"
|
||||
|
||||
newvalues(%r{.*}, :absent)
|
||||
end
|
||||
|
||||
newproperty(:sslverify) do
|
||||
desc "Should yum verify SSL certificates/hosts at all.
|
||||
#{YUM_BOOLEAN_DOC}
|
||||
#{ABSENT_DOC}"
|
||||
|
||||
newvalues(YUM_BOOLEAN, :absent)
|
||||
munge(&munge_yum_bool)
|
||||
end
|
||||
|
||||
newproperty(:sslclientcert) do
|
||||
desc "Path to the SSL client certificate yum should use to connect
|
||||
to repositories/remote sites. #{ABSENT_DOC}"
|
||||
|
||||
newvalues(%r{.*}, :absent)
|
||||
end
|
||||
|
||||
newproperty(:sslclientkey) do
|
||||
desc "Path to the SSL client key yum should use to connect
|
||||
to repositories/remote sites. #{ABSENT_DOC}"
|
||||
|
||||
newvalues(%r{.*}, :absent)
|
||||
end
|
||||
|
||||
newproperty(:metalink) do
|
||||
desc "Metalink for mirrors. #{ABSENT_DOC}"
|
||||
|
||||
newvalues(%r{.*}, :absent)
|
||||
validate do |value|
|
||||
next if value.to_s == 'absent'
|
||||
parsed = URI.parse(value)
|
||||
|
||||
unless VALID_SCHEMES.include?(parsed.scheme)
|
||||
raise _('Must be a valid URL')
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
newproperty(:skip_if_unavailable) do
|
||||
desc "Should yum skip this repository if unable to reach it.
|
||||
#{YUM_BOOLEAN_DOC}
|
||||
#{ABSENT_DOC}"
|
||||
|
||||
newvalues(YUM_BOOLEAN, :absent)
|
||||
munge(&munge_yum_bool)
|
||||
end
|
||||
|
||||
newproperty(:assumeyes) do
|
||||
desc "Determines if yum prompts for confirmation of critical actions.
|
||||
#{YUM_BOOLEAN_DOC}
|
||||
#{ABSENT_DOC}"
|
||||
|
||||
newvalues(YUM_BOOLEAN, :absent)
|
||||
munge(&munge_yum_bool)
|
||||
end
|
||||
|
||||
newproperty(:deltarpm_percentage) do
|
||||
desc "Percentage value that determines when to use deltas for this repository.
|
||||
When the delta is larger than this percentage value of the package, the
|
||||
delta is not used.
|
||||
#{ABSENT_DOC}"
|
||||
|
||||
newvalues(%r{^\d+$}, :absent)
|
||||
end
|
||||
|
||||
newproperty(:deltarpm_metadata_percentage) do
|
||||
desc "Percentage value that determines when to download deltarpm metadata.
|
||||
When the deltarpm metadata is larger than this percentage value of the
|
||||
package, deltarpm metadata is not downloaded.
|
||||
#{ABSENT_DOC}"
|
||||
|
||||
newvalues(%r{^\d+$}, :absent)
|
||||
end
|
||||
|
||||
newproperty(:username) do
|
||||
desc "Username to use for basic authentication to a repo or really any url.
|
||||
#{ABSENT_DOC}"
|
||||
newvalues(%r{.*}, :absent)
|
||||
end
|
||||
|
||||
newproperty(:password) do
|
||||
desc "Password to use with the username for basic authentication.
|
||||
#{ABSENT_DOC}"
|
||||
newvalues(%r{.*}, :absent)
|
||||
end
|
||||
|
||||
private
|
||||
|
||||
def set_sensitive_parameters(sensitive_parameters)
|
||||
parameter(:password).sensitive = true if parameter(:password)
|
||||
parameter(:proxy_password).sensitive = true if parameter(:proxy_password)
|
||||
super(sensitive_parameters)
|
||||
end
|
||||
end
|
||||
+2
@@ -0,0 +1,2 @@
|
||||
Puppet::Type.type(:private_ensure).provide(:p) do
|
||||
end
|
||||
+10
@@ -0,0 +1,10 @@
|
||||
Puppet::Type.newtype(:implicit_ensure) do
|
||||
@doc = 'implicit'
|
||||
newproperty(:a)
|
||||
newparam(:name, namevar: true)
|
||||
def exists?; end
|
||||
def create
|
||||
true
|
||||
end
|
||||
def destroy; end
|
||||
end
|
||||
@@ -0,0 +1,61 @@
|
||||
require_relative '../../puppet_x/probe/inert'
|
||||
Puppet::Type.newtype(:inert) do
|
||||
desc 'everything inert'
|
||||
Puppet.warning('loading inert')
|
||||
Puppet.debug 'x'
|
||||
include PuppetX::Probe::Inert
|
||||
feature :f1, 'Feature doc', methods: [:m1]
|
||||
feature :f2,
|
||||
"multi
|
||||
line"
|
||||
@state = false
|
||||
@hdr = <<~EOS
|
||||
header
|
||||
EOS
|
||||
helper = proc do |v|
|
||||
v
|
||||
end
|
||||
other = lambda { |v| v }
|
||||
LIST = %w[a b].freeze
|
||||
class << self
|
||||
attr_accessor :state
|
||||
end
|
||||
validate do
|
||||
raise 'x' unless self[:name]
|
||||
end
|
||||
autorequire(:file) { ['/a'] }
|
||||
autobefore(:file) do
|
||||
[]
|
||||
end
|
||||
autonotify(:service) { [] }
|
||||
autosubscribe(:package) { [] }
|
||||
newparam(:name, namevar: true) do
|
||||
desc 'n'
|
||||
possible = [:a, :b]
|
||||
rx = %r{^x$}
|
||||
validate do |v|
|
||||
raise ArgumentError unless possible.include?(v)
|
||||
end
|
||||
munge(&helper)
|
||||
unmunge { |v| v }
|
||||
isrequired
|
||||
attr_accessor :latest
|
||||
def insync?(is)
|
||||
is == should
|
||||
end
|
||||
if defined? IPAddr
|
||||
validate do |v|
|
||||
IPAddr.new(v)
|
||||
end
|
||||
end
|
||||
end
|
||||
newproperty(:p) do
|
||||
sensitive true
|
||||
defaultto :x
|
||||
newvalues(:x, :y)
|
||||
defaultto { :y }
|
||||
end
|
||||
def refresh; end
|
||||
private
|
||||
def exists?; end
|
||||
end
|
||||
@@ -0,0 +1,25 @@
|
||||
Puppet::Type.newtype(:literals) do
|
||||
@doc = "Type doc with escapes: \101\x42\u0043 \u{44 45} tab\there \e end"
|
||||
newparam(:name, namevar: true)
|
||||
newparam(:ints) do
|
||||
desc 'Single \n quoted \\ and \' only'
|
||||
newvalues(0x1f, 0X1F, 1_000, 0o17, 0O17, 017, 0_17, 0b101, 0B11, 0d12, 0D19, -0x10, 0, 00, -0, 12345678901234567890)
|
||||
end
|
||||
newparam(:floats) do
|
||||
newvalues(1e3, 1E3, 1.5, 1.5e-5, 1e15, 1e14, 999999999999999.0, 0.0001, 0.00001, 1_0.5, 1e+3, 100.0, -0.0, -2.5, 123456789.123456789, 5e-324)
|
||||
end
|
||||
newparam(:dq) do
|
||||
desc "Double \"quoted\"\s\a\b doc"
|
||||
newvalues("\101", "\x41", "\x4", "\u00e9", "\u{41 42 43}", "\e", "\cA", "\C-b", "\c?", "\1", "\18", "\12", "\1234", "\q", "\8", "a\
|
||||
b", "\#{x}", "\0", "tab\t", "nl\n", "\s", "\$x")
|
||||
end
|
||||
newparam(:sq) do
|
||||
newvalues('a\nb', 'a\\b', 'a\'b', %q(a\)b\(c), %q{x\}y}, :"x\101", :'y\101', %s(z\101))
|
||||
end
|
||||
newparam(:re) do
|
||||
newvalues(/é/, /\u00e9/, /\u{e9}/, /[\u{41}]/, /\u0041/, /\p{L}/, /\P{Alpha}/, /\x41/, /a b/x, /(?i)x/, /\//m, /a\/b/, %r{a/b}, %r{a\/b}, %r!a\!b!, %r|a\|b|, %r{a\}b}, %r(a\)b), %r,a\,b,, /\h\R\X/, /[[:alpha:]]/, /é/i, /a#b/, /\\/, /\e/, /x/o)
|
||||
end
|
||||
newparam(:re2) do
|
||||
newvalues(/a b/, /c/)
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,5 @@
|
||||
require_relative '../../puppet_x/probe/trio'
|
||||
Puppet::Type.newtype(:mixin_ensure) do
|
||||
newparam(:name, namevar: true)
|
||||
include PuppetX::Probe::Trio
|
||||
end
|
||||
+7
@@ -0,0 +1,7 @@
|
||||
Puppet::Type.newtype(:private_ensure) do
|
||||
newparam(:name, namevar: true)
|
||||
def exists?; end
|
||||
def create; end
|
||||
private
|
||||
def destroy; end
|
||||
end
|
||||
+11
@@ -0,0 +1,11 @@
|
||||
require 'puppet/resource_api'
|
||||
Puppet::ResourceApi.register_type(
|
||||
name: 'rsapi_behavior',
|
||||
docs: 'rsapi',
|
||||
attributes: {
|
||||
name: { type: 'String', desc: 'n', behavior: :namevar },
|
||||
ro: { type: 'String', desc: 'r', behavior: :read_only },
|
||||
p: { type: 'Boolean', desc: 'p', behavior: :parameter },
|
||||
ensure: { type: 'Enum[present, absent]', desc: 'e' },
|
||||
},
|
||||
)
|
||||
@@ -0,0 +1,13 @@
|
||||
module PuppetX
|
||||
module Probe
|
||||
module Inert
|
||||
def self.try
|
||||
yield
|
||||
end
|
||||
|
||||
private
|
||||
|
||||
def create; end
|
||||
end
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,11 @@
|
||||
module PuppetX
|
||||
module Probe
|
||||
module Trio
|
||||
MAX = 3
|
||||
def self.helper; end
|
||||
def exists?; end
|
||||
def create; end
|
||||
def destroy; end
|
||||
end
|
||||
end
|
||||
end
|
||||
+2
@@ -0,0 +1,2 @@
|
||||
class Puppet::Provider::RProvClass
|
||||
end
|
||||
+3
@@ -0,0 +1,3 @@
|
||||
Puppet::Type.type(:r_prov_name).provide(:other) do
|
||||
desc ''
|
||||
end
|
||||
+2
@@ -0,0 +1,2 @@
|
||||
Puppet::Type.type(:r_prov_parent).provide(:a) do
|
||||
end
|
||||
+3
@@ -0,0 +1,3 @@
|
||||
require 'json'
|
||||
Puppet::Type.type(:r_prov_parent).provide :b, parent: :a do
|
||||
end
|
||||
Vendored
+2
@@ -0,0 +1,2 @@
|
||||
Puppet::Type.type(:r_prov_parent_missing).provide(:a, parent: :nope) do
|
||||
end
|
||||
@@ -0,0 +1,3 @@
|
||||
Type.newtype(:r_bare) do
|
||||
newparam(:name, namevar: true)
|
||||
end
|
||||
@@ -0,0 +1,10 @@
|
||||
begin
|
||||
require 'ipaddr'
|
||||
rescue LoadError => e
|
||||
Puppet.warning("#{__FILE__}: #{e}")
|
||||
end
|
||||
DOC = 'Literal doc.'.freeze
|
||||
Puppet::Type.newtype(:r_begin) do
|
||||
@doc = DOC
|
||||
newparam(:name, namevar: true)
|
||||
end
|
||||
@@ -0,0 +1,4 @@
|
||||
X = File.join('a', 'b')
|
||||
Puppet::Type.newtype(:r_const_call) do
|
||||
newparam(:name, namevar: true)
|
||||
end
|
||||
@@ -0,0 +1,4 @@
|
||||
Puppet::Type.newtype(:r_dollar) do
|
||||
newparam(:name, namevar: true)
|
||||
end
|
||||
$
|
||||
@@ -0,0 +1,5 @@
|
||||
Puppet::Type.newtype(:r_dup_ensure) do
|
||||
newparam(:name, namevar: true)
|
||||
ensurable
|
||||
newproperty(:ensure)
|
||||
end
|
||||
@@ -0,0 +1,5 @@
|
||||
Puppet::Type.newtype(:r_dup_param) do
|
||||
newparam(:name, namevar: true)
|
||||
newparam(:a)
|
||||
newparam(:a)
|
||||
end
|
||||
@@ -0,0 +1,5 @@
|
||||
Puppet::Type.newtype(:r_dup_prop) do
|
||||
newparam(:name, namevar: true)
|
||||
newproperty(:a)
|
||||
newproperty(:a)
|
||||
end
|
||||
+4
@@ -0,0 +1,4 @@
|
||||
Puppet::Type.newtype(:r_feature_const) do
|
||||
feature :x, 'doc', methods: [RNope]
|
||||
newparam(:name, namevar: true)
|
||||
end
|
||||
@@ -0,0 +1,9 @@
|
||||
module RHelper
|
||||
def self.add(type)
|
||||
type.newparam(:extra)
|
||||
end
|
||||
end
|
||||
Puppet::Type.newtype(:r_helper) do
|
||||
newparam(:name, namevar: true)
|
||||
end
|
||||
RHelper.add(Puppet::Type.type(:r_helper))
|
||||
+4
@@ -0,0 +1,4 @@
|
||||
Puppet::Type.newtype(:r_include_noreq) do
|
||||
include PuppetX::Review::Mix
|
||||
newparam(:name, namevar: true)
|
||||
end
|
||||
+6
@@ -0,0 +1,6 @@
|
||||
require 'puppet_x/review/mix'
|
||||
Puppet::Type.newtype(:r_include_req) do
|
||||
include PuppetX::Review::Mix
|
||||
newparam(:name, namevar: true)
|
||||
newproperty(:a)
|
||||
end
|
||||
+4
@@ -0,0 +1,4 @@
|
||||
Puppet::Type.newtype(:r_inline_provide) do
|
||||
newparam(:name, namevar: true)
|
||||
end
|
||||
Puppet::Type.type(:r_inline_provide).provide(:inline) {}
|
||||
+5
@@ -0,0 +1,5 @@
|
||||
module Puppet::RCompact
|
||||
Type.newtype(:r_mod_compact) do
|
||||
newparam(:name, namevar: true)
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,5 @@
|
||||
module RFoo
|
||||
Type.newtype(:r_mod_foo) do
|
||||
newparam(:name, namevar: true)
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,5 @@
|
||||
module Puppet
|
||||
Type.newtype(:r_mod_puppet) do
|
||||
newparam(:name, namevar: true)
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,5 @@
|
||||
Puppet::Type.newtype(:r_param_prop) do
|
||||
newparam(:name, namevar: true)
|
||||
newparam(:a)
|
||||
newproperty(:a)
|
||||
end
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user