76 Commits

Author SHA1 Message Date
unkin-agent 8a8c30878b Name resource_api title pattern groups as Regexp#names does (#20)
resource_api names title-pattern captures with `Regexp.new(pattern).names`, which counts only real named groups. w10k matched `(?<name>` anywhere in the source, so an escaped paren, a character class or a comment added names puppet never emits.

- scan patterns as Onigmo does: escapes, nested character classes, `(?#...)` and extended-mode comments hold no groups; names stay unique in first-appearance order
- skip a pattern whose names or back references fall outside what w10k models (Unicode or hyphenated names, `\g`, forward `\k`)
- bump gentypes.Version to 14

Reviewed-on: #20
Co-authored-by: unkin-agent <unkin-agent@unkin.net>
Co-committed-by: unkin-agent <unkin-agent@unkin.net>
2026-11-14 18:10:51 +11:00
unkin-agent 126e7593b2 Name resource_api title pattern groups as Regexp#names does (#20)
resource_api names title-pattern captures with `Regexp.new(pattern).names`, which counts only real named groups. w10k matched `(?<name>` anywhere in the source, so an escaped paren, a character class or a comment added names puppet never emits.

- scan patterns as Onigmo does: escapes, nested character classes, `(?#...)` and extended-mode comments hold no groups; names stay unique in first-appearance order
- skip a pattern whose names or back references fall outside what w10k models (Unicode or hyphenated names, `\g`, forward `\k`)
- bump gentypes.Version to 14

Reviewed-on: #20
Co-authored-by: unkin-agent <unkin-agent@unkin.net>
Co-committed-by: unkin-agent <unkin-agent@unkin.net>
2026-11-14 18:01:08 +11:00
benvin 9dd08d5360 Merge pull request 'Generate shellvar through block-setter calls and guarded raises' (#19) from benvin/gentypes-shellvar into main
Reviewed-on: #19
2026-11-10 21:45:39 +11:00
unkin-agent 6622d409cc Merge remote-tracking branch 'origin/main' into benvin/gentypes-shellvar
ci/woodpecker/pr/build Pipeline was successful
ci/woodpecker/pr/test Pipeline was successful
ci/woodpecker/pr/pre-commit Pipeline was successful
ci/woodpecker/pr/lint Pipeline was successful
2026-11-10 00:15:28 +11:00
benvin 24d543417a Merge pull request 'Generate augeas types through module features and core mixins' (#18) from benvin/gentypes-augeas into main
Reviewed-on: #18
2026-11-09 23:49:30 +11:00
unkin-agent 081ea12714 Join File.join parts in linear time
ci/woodpecker/pr/build Pipeline was successful
ci/woodpecker/pr/test Pipeline was successful
ci/woodpecker/pr/pre-commit Pipeline was successful
ci/woodpecker/pr/lint Pipeline was successful
2026-11-09 23:11:58 +11:00
unkin-agent fb3d2f2d0d Merge remote-tracking branch 'origin/benvin/gentypes-augeas' into benvin/gentypes-shellvar 2026-11-09 23:11:03 +11:00
unkin-agent 7b692cbbbf Merge remote-tracking branch 'origin/main' into benvin/gentypes-augeas
ci/woodpecker/pr/build Pipeline was successful
ci/woodpecker/pr/test Pipeline was successful
ci/woodpecker/pr/pre-commit Pipeline was successful
ci/woodpecker/pr/lint Pipeline was successful
2026-11-09 23:10:54 +11:00
unkin-agent 87568da152 Run block-setter class methods and guarded raises
A class method called with a block runs when its parameters are optional
literals and its body only branches on them and stores ivars puppet never
reads. A top-level raise runs only when its if/unless condition holds, nil?
is evaluated, and a statement guarded by block_given? outside a method never
runs. Generates shellvar.
2026-11-09 23:10:27 +11:00
benvin 8bba3aac5e Merge pull request 'Generate openldap types through trailing-dot chains and File.join arrays' (#17) from benvin/gentypes-openldap into main
Reviewed-on: #17
2026-11-09 23:01:15 +11:00
benvin fd0460eedc Merge pull request 'Generate ceph types through cross-type loads and title_patterns locals' (#16) from benvin/gentypes-ceph into main
Reviewed-on: #16
2026-11-09 22:56:25 +11:00
benvin 7b3f38ece9 Merge pull request 'Generate zpool through type-file classes and user attribute parents' (#15) from benvin/gentypes-zpool into main
Reviewed-on: #15
2026-11-09 22:53:52 +11:00
benvin 69ceccf110 Merge pull request 'Generate network_config and network_route through filemapper hooks' (#14) from benvin/gentypes-network into main
Reviewed-on: #14
2026-11-09 22:50:05 +11:00
benvin 41dcfba0c7 Merge pull request 'Evaluate provider load-time code in a bounded subset' (#13) from benvin/gentypes-evaluator into main
Reviewed-on: #13
2026-11-09 22:49:46 +11:00
benvin fc72ad62d8 Merge pull request 'Render provider docs as openvox 9.3.0 does' (#12) from benvin/gentypes-provider-docs into main
Reviewed-on: #12
2026-11-09 22:42:36 +11:00
unkin-agent 01ecc8f421 Evaluate module features and core mixins
ci/woodpecker/pr/build Pipeline was successful
ci/woodpecker/pr/test Pipeline was successful
ci/woodpecker/pr/pre-commit Pipeline was successful
ci/woodpecker/pr/lint Pipeline was successful
Puppet.features.<name>? autoloads the module's puppet/feature file and is true
when each of its libs loads, gems only when declared; openvox's own features
depend on the host and skip. Includes of hook-free openvox modules, private
:name in mixins and block parameters on attribute blocks are accepted.
Generates augeas and augeasprovider.
2026-11-09 22:41:54 +11:00
benvin 282c5ab8ba Merge pull request 'Generate grafana_ldap_config with a declared toml gem' (#11) from benvin/gentypes-grafana-ldap into main
Reviewed-on: #11
2026-11-09 22:40:25 +11:00
benvin 13679ff780 Merge pull request 'Skip types whose provider or library loads w10k cannot prove' (#10) from benvin/gentypes-fidelity into main
Reviewed-on: #10
2026-11-09 22:34:08 +11:00
unkin-agent d0b6a12bc4 Continue lines after a trailing dot and join File.join arrays
ci/woodpecker/pr/build Pipeline was successful
ci/woodpecker/pr/test Pipeline was successful
ci/woodpecker/pr/lint Pipeline was successful
ci/woodpecker/pr/pre-commit Pipeline was successful
Ruby continues a statement whose line ends in a method-call dot, and File.join
joins array arguments recursively with its own separator rules. Generates the
seven openldap types.
2026-11-09 22:27:14 +11:00
unkin-agent c8fba92811 Load types through Puppet::Type.type and evaluate title_patterns locals
ci/woodpecker/pr/build Pipeline was successful
ci/woodpecker/pr/test Pipeline was successful
ci/woodpecker/pr/lint Pipeline was successful
ci/woodpecker/pr/pre-commit Pipeline was successful
Puppet::Type.type(:x) loads x's module type file with its providers, whose
classes .provider(:n) returns as a parent; a nil parent is Puppet::Provider.
title_patterns binds locals, including Regexp.new copies. Generates ceph_config,
ceph_fs and ceph_pool.
2026-11-09 22:18:00 +11:00
unkin-agent ce90a7a3a7 Load type-file classes and user attribute parents as Ruby does
ci/woodpecker/pr/build Pipeline was successful
ci/woodpecker/pr/test Pipeline was successful
ci/woodpecker/pr/pre-commit Pipeline was successful
ci/woodpecker/pr/lint Pipeline was successful
2026-11-09 01:22:34 +11:00
unkin-agent f2d3112d60 Evaluate mixin included hooks and interpolated regexes
ci/woodpecker/pr/build Pipeline was successful
ci/woodpecker/pr/test Pipeline was successful
ci/woodpecker/pr/pre-commit Pipeline was successful
ci/woodpecker/pr/lint Pipeline was successful
Run a module's self.included on the including provider: extend adds singleton
methods, a super-wrapping initvars resets defaults and commands where called,
and inlined define loops add property methods. Compose interpolated regex
literals and accept them only when an Onigmo subset check passes. Generates
network_config and network_route.
2026-11-09 00:53:42 +11:00
unkin-agent 60e34561e2 Merge benvin/gentypes-provider-docs into benvin/gentypes-evaluator
ci/woodpecker/pr/build Pipeline was successful
ci/woodpecker/pr/test Pipeline was successful
ci/woodpecker/pr/pre-commit Pipeline was successful
ci/woodpecker/pr/lint Pipeline was successful
Provider classes keep #12's desc, defaultfor, commands and features alongside the
evaluator's singleton methods, constants and provide-block bindings in one classCtx.
Goldens for yumrepo, patroni_dcs_config and zfs are regenerated with openvox 9.3.0,
and gentypes.Version is 7.
2026-11-09 00:19:34 +11:00
unkin-agent f10800bd06 Evaluate provider load-time code in a bounded subset
ci/woodpecker/pr/build Pipeline was successful
ci/woodpecker/pr/test Pipeline was successful
ci/woodpecker/pr/pre-commit Pipeline was successful
ci/woodpecker/pr/lint Pipeline was successful
- add an evaluator for constants, locals, define loops, inlined singleton methods and own-type validproperties
- cap inline depth, world steps and allocation
- model puppet/util/inifile's classes and %i symbols
- vendor patroni and zfs_core fixtures and the full yumrepo provider
2026-11-09 00:08:09 +11:00
unkin-agent eef359dd75 Render provider docs as openvox 9.3.0 does
ci/woodpecker/pr/build Pipeline was successful
ci/woodpecker/pr/test Pipeline was successful
ci/woodpecker/pr/pre-commit Pipeline was successful
ci/woodpecker/pr/lint Pipeline was successful
- record each provider class's own desc, @doc, defaultfor, commands and has_features
- render the commands, defaults and features dochooks into the provider param doc
- detect method-backed features from public provider methods, skipping when unprovable
- reject provider DSL calls before initvars in plain provider subclasses
- read %i word arrays as symbols
- compare comments in TestGolden's external env mode
2026-11-08 23:57:35 +11:00
unkin-agent a04351cfa1 Model the toml gem's load for declared w10k.gems
ci/woodpecker/pr/build Pipeline was successful
ci/woodpecker/pr/test Pipeline was successful
ci/woodpecker/pr/pre-commit Pipeline was successful
ci/woodpecker/pr/lint Pipeline was successful
Generate grafana_ldap_config when r10k.yaml declares toml; a module copy of a gem path, an unmodelled gem file or a module opening a gem namespace still skips.
2026-11-08 23:09:07 +11:00
unkin-agent 169a3be7ad Merge remote-tracking branch 'origin/main' into benvin/gentypes-fidelity
ci/woodpecker/pr/build Pipeline was successful
ci/woodpecker/pr/lint Pipeline was successful
ci/woodpecker/pr/test Pipeline was successful
ci/woodpecker/pr/pre-commit Pipeline was successful
2026-11-08 22:48:59 +11:00
unkin-agent 0db5808687 Drop .resource_types seeding; a skipped type gets no .pp 2026-11-08 22:48:59 +11:00
unkin-agent 8f60f9a5d4 Restrict libraries that reopen puppet's own classes to nesting new ones
ci/woodpecker/pr/build Pipeline was successful
ci/woodpecker/pr/test Pipeline was successful
ci/woodpecker/pr/pre-commit Pipeline was successful
ci/woodpecker/pr/lint Pipeline was successful
2026-11-08 22:21:54 +11:00
unkin-agent 92efabd123 Skip types whose provider or library loads w10k cannot prove
ci/woodpecker/pr/build Pipeline was successful
ci/woodpecker/pr/pre-commit Pipeline was successful
ci/woodpecker/pr/test Pipeline was successful
ci/woodpecker/pr/lint Pipeline was successful
- analyse provider files and required libraries with the type-file allowlist
- resolve requires with puppet core, gems and stdlib ahead of module lib dirs
- read mixins from the file that was required; skip paths several modules provide
- resolve constants by lexical scope
- mirror resource_api schema raises, Variant flattening and float lexing
- seed .resource_types from the live worktree so skipped types keep their .pp
2026-11-08 22:15:07 +11:00
benvin cf1aca3cf8 Merge pull request 'Add environment aliases' (#8) from benvin/aliases into main
Reviewed-on: #8
2026-11-08 22:13:00 +11:00
unkin-agent 3b143d6550 Merge origin/main; aliases share the skipped-set purge
ci/woodpecker/pr/build Pipeline was successful
ci/woodpecker/pr/test Pipeline was successful
ci/woodpecker/pr/lint Pipeline was successful
ci/woodpecker/pr/pre-commit Pipeline was successful
2026-11-08 22:00:36 +11:00
benvin 3249b5067f Merge pull request 'Keep live envs on corrected-name collisions, cap forge metadata reads' (#9) from benvin/collision-forge-cap into main
Reviewed-on: #9
2026-11-08 21:59:36 +11:00
unkin-agent 9babc26a05 Merge origin/main 2026-11-08 21:58:45 +11:00
unkin-agent 93202f2980 Merge origin/main; purge keeps names only skipped branches claim
ci/woodpecker/pr/build Pipeline was successful
ci/woodpecker/pr/test Pipeline was successful
ci/woodpecker/pr/pre-commit Pipeline was successful
ci/woodpecker/pr/lint Pipeline was successful
2026-11-08 21:57:52 +11:00
benvin f105326b6a Merge pull request 'Add --timings phase logs and named-env deploys' (#3) from benvin/timings into main
Reviewed-on: #3
2026-11-08 21:55:07 +11:00
unkin-agent 77259d507d Keep live envs whose name only corrected branches collide on, cap forge metadata reads
ci/woodpecker/pr/build Pipeline was successful
ci/woodpecker/pr/test Pipeline was successful
ci/woodpecker/pr/pre-commit Pipeline was successful
ci/woodpecker/pr/lint Pipeline was successful
2026-11-08 21:52:10 +11:00
unkin-agent df0d8ff9f3 Merge remote-tracking branch 'origin/benvin/timings' into benvin/timings
ci/woodpecker/pr/build Pipeline was successful
ci/woodpecker/pr/pre-commit Pipeline was successful
ci/woodpecker/pr/test Pipeline was successful
ci/woodpecker/pr/lint Pipeline was successful
# Conflicts:
#	internal/deploy/deploy.go
2026-11-08 21:47:44 +11:00
benvin 00199db589 Merge pull request 'Scope named deploys to their environments' (#4) from benvin/named-deploy into benvin/timings
ci/woodpecker/pr/build Pipeline was successful
ci/woodpecker/pr/test Pipeline was successful
ci/woodpecker/pr/pre-commit Pipeline was successful
ci/woodpecker/pr/lint Pipeline was successful
Reviewed-on: #4
2026-11-08 21:46:15 +11:00
unkin-agent 1ff7d9e547 Merge remote-tracking branch 'origin/benvin/scaffold' into benvin/aliases
ci/woodpecker/pr/build Pipeline was successful
ci/woodpecker/pr/test Pipeline was successful
ci/woodpecker/pr/pre-commit Pipeline was successful
ci/woodpecker/pr/lint Pipeline was successful
# Conflicts:
#	internal/deploy/deploy.go
#	internal/deploy/deploy_test.go
2026-11-08 21:44:17 +11:00
unkin-agent 94c73ed1e1 Merge remote-tracking branch 'origin/main' into benvin/timings 2026-11-08 21:43:24 +11:00
unkin-agent 11b89d6d5d Count worktree lock waits and assert timing counts, labels and --timings 2026-11-08 21:43:22 +11:00
benvin 1bb175c92c Merge pull request 'Generate Puppet resource types natively before the env swap' (#2) from benvin/generate-types into main
Reviewed-on: #2
2026-11-08 21:42:11 +11:00
unkin-agent 5b696fc572 Keep aliases of collided envs and align aliases even when the target fails
ci/woodpecker/pr/build Pipeline was successful
ci/woodpecker/pr/test Pipeline was successful
ci/woodpecker/pr/pre-commit Pipeline was successful
ci/woodpecker/pr/lint Pipeline was successful
2026-11-08 21:42:09 +11:00
benvin 358d17ca2f Merge pull request 'Add w10k: deploy Puppet environments as sha-pinned git worktrees' (#1) from benvin/scaffold into main
Reviewed-on: #1
2026-11-08 21:41:21 +11:00
unkin-agent d7369850db Keep in-flight work across concurrent Deploys 2026-11-08 21:40:33 +11:00
unkin-agent 6cadcbbf0e Merge remote-tracking branch 'origin/benvin/generate-types' into benvin/timings
# Conflicts:
#	internal/deploy/deploy.go
#	internal/deploy/forge.go
2026-11-08 21:40:03 +11:00
unkin-agent 0e60781f47 Add environment aliases pointing at their target's worktree
ci/woodpecker/pr/build Pipeline was successful
ci/woodpecker/pr/test Pipeline was successful
ci/woodpecker/pr/pre-commit Pipeline was successful
ci/woodpecker/pr/lint Pipeline was successful
2026-11-08 21:32:46 +11:00
unkin-agent 1130645dd3 Merge remote-tracking branch 'origin/benvin/scaffold' into benvin/generate-types
ci/woodpecker/pr/build Pipeline was successful
ci/woodpecker/pr/test Pipeline was successful
ci/woodpecker/pr/pre-commit Pipeline was successful
ci/woodpecker/pr/lint Pipeline was successful
# Conflicts:
#	internal/deploy/deploy.go
2026-11-08 21:29:18 +11:00
unkin-agent 260dd4fc78 Warn about corrected branch names only for envs being deployed
ci/woodpecker/pr/build Pipeline was successful
ci/woodpecker/pr/test Pipeline was successful
ci/woodpecker/pr/pre-commit Pipeline was successful
ci/woodpecker/pr/lint Pipeline was successful
2026-11-08 21:06:28 +11:00
unkin-agent 503db52306 Resolve named deploys over all branches and sources before filtering
- pick env winners over every branch, then select, so a named deploy matches a full deploy
- match env names across sources first, raw branch names only when no env matches
- report collision and invalid-name errors only for the named args
- add tests for collision losers, all-corrected collisions, prefixed sources and unrelated invalid branches
2026-11-08 21:04:45 +11:00
unkin-agent 3c43222238 Merge remote-tracking branch 'origin/benvin/timings' into benvin/named-deploy
# Conflicts:
#	internal/deploy/deploy_test.go
2026-11-08 21:03:29 +11:00
unkin-agent 5e468b2e8e Merge remote-tracking branch 'origin/benvin/scaffold' into benvin/named-deploy
# Conflicts:
#	internal/deploy/deploy.go
#	internal/deploy/forge.go
2026-11-08 21:02:45 +11:00
unkin-agent 4edc42329c Label waiters on in-flight work cache=shared and count panics as failed
ci/woodpecker/pr/build Pipeline was successful
ci/woodpecker/pr/test Pipeline was successful
ci/woodpecker/pr/pre-commit Pipeline was successful
ci/woodpecker/pr/lint Pipeline was successful
- report cache=shared for callers that waited on another's once work
- drop the git module.resolve cache label
- recover deployEnv panics before its outcome is recorded
- count source fetch and branch errors as failed
2026-11-08 21:02:23 +11:00
unkin-agent 94bcdc19f4 Merge remote-tracking branch 'origin/benvin/timings' into benvin/named-deploy
ci/woodpecker/pr/build Pipeline was successful
ci/woodpecker/pr/test Pipeline was successful
ci/woodpecker/pr/pre-commit Pipeline was successful
ci/woodpecker/pr/lint Pipeline was successful
# Conflicts:
#	internal/deploy/deploy.go
2026-11-08 20:49:07 +11:00
unkin-agent ba06c3bae7 Merge remote-tracking branch 'origin/benvin/generate-types' into benvin/timings
ci/woodpecker/pr/build Pipeline was successful
ci/woodpecker/pr/test Pipeline was successful
ci/woodpecker/pr/pre-commit Pipeline was successful
ci/woodpecker/pr/lint Pipeline was successful
# Conflicts:
#	internal/deploy/deploy.go
#	internal/gentypes/generate.go
#	internal/gentypes/generate_test.go
2026-11-08 20:47:56 +11:00
unkin-agent 8ea6aacd3f Merge remote-tracking branch 'origin/benvin/scaffold' into benvin/generate-types
ci/woodpecker/pr/build Pipeline was successful
ci/woodpecker/pr/test Pipeline was successful
ci/woodpecker/pr/pre-commit Pipeline was successful
ci/woodpecker/pr/lint Pipeline was successful
# Conflicts:
#	internal/deploy/deploy.go
2026-11-08 20:46:10 +11:00
unkin-agent b31b4f6175 Skip types w10k cannot prove match puppet
- bound-check a trailing $ in the lexer and turn a per-file panic into an env error
- allowlist top-level statements: requires, literal constants, module Puppet, begin/rescue requires
- require the require that defines Puppet::ResourceApi, Boolean and File parents and included mixins
- name providers by their provide call; skip types whose provider files are not one recognised provide
- read symbol option keys only, as newparam, newproperty and register_type do
- parse Resource API types with a TypeParser-compatible grammar
- skip duplicate properties and parameters
- add a parseFile fuzz target and real-puppet golden fixtures for each case
2026-11-08 20:45:18 +11:00
unkin-agent 09f84fd752 Merge remote-tracking branch 'origin/benvin/timings' into benvin/named-deploy
ci/woodpecker/pr/test Pipeline was successful
ci/woodpecker/pr/build Pipeline was successful
ci/woodpecker/pr/lint Pipeline was successful
ci/woodpecker/pr/pre-commit Pipeline was successful
2026-11-08 20:34:09 +11:00
unkin-agent 2e7644e2fa Merge remote-tracking branch 'origin/benvin/generate-types' into benvin/timings
# Conflicts:
#	internal/deploy/deploy.go
#	internal/deploy/deploy_test.go
#	internal/deploy/git.go
2026-11-08 20:33:44 +11:00
unkin-agent 7d457a89cf Clear GC marks for worktrees and modules a named deploy swaps in
ci/woodpecker/pr/build Pipeline was successful
ci/woodpecker/pr/test Pipeline was successful
ci/woodpecker/pr/pre-commit Pipeline was successful
ci/woodpecker/pr/lint Pipeline was successful
2026-11-08 20:32:25 +11:00
unkin-agent 0112806a21 Merge remote-tracking branch 'origin/benvin/scaffold' into benvin/generate-types
ci/woodpecker/pr/build Pipeline was successful
ci/woodpecker/pr/lint Pipeline was successful
ci/woodpecker/pr/test Pipeline was successful
ci/woodpecker/pr/pre-commit Pipeline was successful
# Conflicts:
#	internal/deploy/deploy.go
2026-11-08 20:31:40 +11:00
unkin-agent cee4a1fb8d Scope named deploys to their envs and complete env args 2026-11-08 20:31:06 +11:00
unkin-agent a152bb57a0 Merge remote-tracking branch 'origin/benvin/scaffold' into benvin/generate-types
ci/woodpecker/pr/build Pipeline was successful
ci/woodpecker/pr/test Pipeline was successful
ci/woodpecker/pr/lint Pipeline was successful
ci/woodpecker/pr/pre-commit Pipeline was successful
# Conflicts:
#	internal/deploy/deploy.go
2026-11-08 20:30:54 +11:00
unkin-agent 55224fd9f7 Report wait on leaf phases only and include it in module.download
ci/woodpecker/pr/build Pipeline was successful
ci/woodpecker/pr/test Pipeline was successful
ci/woodpecker/pr/pre-commit Pipeline was successful
ci/woodpecker/pr/lint Pipeline was successful
2026-11-08 20:30:31 +11:00
unkin-agent dd1421f77c Drop named-deploy scoping and env completion 2026-11-08 20:30:31 +11:00
unkin-agent e7c72ed2d7 Test named deploys and timing phase keys
ci/woodpecker/pr/build Pipeline was successful
ci/woodpecker/pr/test Pipeline was successful
ci/woodpecker/pr/lint Pipeline was successful
ci/woodpecker/pr/pre-commit Pipeline was successful
2026-11-08 20:20:22 +11:00
unkin-agent 1d4b995e1c Add --timings phase logs and scope named deploys to their environments 2026-11-08 20:18:44 +11:00
unkin-agent d570c98fea Skip unparseable types instead of failing the environment
ci/woodpecker/pr/build Pipeline was successful
ci/woodpecker/pr/test Pipeline was successful
ci/woodpecker/pr/pre-commit Pipeline was successful
ci/woodpecker/pr/lint Pipeline was successful
Parse failures are logged per file and counted per env; I/O, confinement and parser-limit errors still fail the deploy.
2026-11-08 19:01:34 +11:00
unkin-agent 71425b58c8 Cap tokens per Ruby file
ci/woodpecker/pr/build Pipeline was successful
ci/woodpecker/pr/test Pipeline was successful
ci/woodpecker/pr/pre-commit Pipeline was successful
ci/woodpecker/pr/lint Pipeline was successful
2026-11-08 18:54:44 +11:00
unkin-agent 0edce80e2c Key typed worktrees on generate_types and the generator version
ci/woodpecker/pr/build Pipeline was successful
ci/woodpecker/pr/pre-commit Pipeline was successful
ci/woodpecker/pr/lint Pipeline was successful
ci/woodpecker/pr/test Pipeline failed
2026-11-08 18:50:46 +11:00
unkin-agent 8435678797 Reject unparsed type-body statements and render literals as Ruby does
- error on stray closers, deep nesting and runaway parses
- allow only inert statements in type and attribute bodies, resolving included mixins
- add the implicit ensure puppet gives types defining exists?, create and destroy
- accept behavior: as the Resource API alias of behaviour:
- normalise Ruby integer, float, string escape and regex literals, failing on forms that cannot be reproduced
- unlink stale symlinks in .resource_types
- verify fixtures, with real providers, against real puppet output
2026-11-08 18:50:46 +11:00
unkin-agent e2bd36c8d9 Merge remote-tracking branch 'origin/benvin/scaffold' into benvin/generate-types
ci/woodpecker/pr/build Pipeline was successful
ci/woodpecker/pr/test Pipeline was successful
ci/woodpecker/pr/pre-commit Pipeline was successful
ci/woodpecker/pr/lint Pipeline was successful
# Conflicts:
#	internal/deploy/config.go
#	internal/deploy/deploy_test.go
2026-11-08 18:08:16 +11:00
unkin-agent ac24c66924 Write .resource_types through an os.Root on the worktree
ci/woodpecker/pr/build Pipeline was successful
ci/woodpecker/pr/lint Pipeline was successful
ci/woodpecker/pr/test Pipeline was successful
ci/woodpecker/pr/pre-commit Pipeline was successful
2026-11-08 18:03:35 +11:00
unkin-agent 893da512f1 Give the failing-input fixture a stale output mtime
ci/woodpecker/pr/build Pipeline was successful
ci/woodpecker/pr/pre-commit Pipeline was successful
ci/woodpecker/pr/test Pipeline was successful
ci/woodpecker/pr/lint Pipeline was successful
2026-11-08 18:01:13 +11:00
unkin-agent dfb5fa021f Generate Puppet resource types natively before the env swap
ci/woodpecker/pr/build Pipeline was successful
ci/woodpecker/pr/pre-commit Pipeline failed
ci/woodpecker/pr/test Pipeline failed
ci/woodpecker/pr/lint Pipeline was successful
- add gentypes: a static Go port of `puppet generate types` for classic and Resource API types
- run it in prepare when w10k.generate_types is set; a failure fails the env and keeps the old link
- confine reads to the worktree and module cache, refuse a committed .resource_types symlink
- test against real puppet output for a vendored Apache-2.0 type set
2026-11-08 17:59:12 +11:00
269 changed files with 36304 additions and 130 deletions
+1
View File
@@ -1,3 +1,4 @@
exclude: ^internal/gentypes/testdata/
repos:
- repo: https://github.com/pre-commit/pre-commit-hooks
rev: v4.6.0
+22 -2
View File
@@ -5,9 +5,11 @@ import (
"os"
"path/filepath"
"regexp"
"slices"
"strings"
"time"
"git.unkin.net/unkin/w10k/internal/gentypes"
"gopkg.in/yaml.v3"
)
@@ -15,8 +17,11 @@ 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"`
Aliases map[string]string `yaml:"aliases"`
Gems []string `yaml:"gems"`
} `yaml:"w10k"`
}
@@ -57,6 +62,21 @@ func ParseConfig(b []byte) (*Config, error) {
if c.W10k.GitTimeout != nil && *c.W10k.GitTimeout <= 0 {
return nil, fmt.Errorf("w10k.git_timeout must be positive")
}
for alias, target := range c.W10k.Aliases {
if !wordOnly.MatchString(alias) || !wordOnly.MatchString(target) {
return nil, fmt.Errorf("w10k.aliases: %s -> %s: names must match \\w+", alias, target)
}
if _, ok := c.W10k.Aliases[target]; ok {
return nil, fmt.Errorf("w10k.aliases: %s -> %s: target is an alias", alias, target)
}
}
for _, g := range c.W10k.Gems {
if !gentypes.KnownGem(g) {
return nil, fmt.Errorf("w10k.gems: %q is not a gem w10k models", g)
}
}
slices.Sort(c.W10k.Gems)
c.W10k.Gems = slices.Compact(c.W10k.Gems)
if len(c.Sources) == 0 {
return nil, fmt.Errorf("no sources defined")
}
+33
View File
@@ -1,8 +1,11 @@
package deploy
import (
"slices"
"testing"
"time"
"git.unkin.net/unkin/w10k/internal/gentypes"
)
func TestParseConfigSymbolKeys(t *testing.T) {
@@ -67,6 +70,11 @@ func TestParseConfigErrors(t *testing.T) {
"bad prefix": "cachedir: /c\nsources: {a: {remote: r, basedir: /b, prefix: [x]}}",
"bad invalid": "cachedir: /c\nsources: {a: {remote: r, basedir: /b, invalid_branches: nope}}",
"bad source name": "cachedir: /c\nsources: {a-b: {remote: r, basedir: /b}}",
"bad alias name": "cachedir: /c\nw10k: {aliases: {a-b: develop}}\nsources: {a: {remote: r, basedir: /b}}",
"bad alias target": "cachedir: /c\nw10k: {aliases: {production: dev/x}}\nsources: {a: {remote: r, basedir: /b}}",
"alias of alias": "cachedir: /c\nw10k: {aliases: {production: staging, staging: develop}}\nsources: {a: {remote: r, basedir: /b}}",
"self alias": "cachedir: /c\nw10k: {aliases: {production: production}}\nsources: {a: {remote: r, basedir: /b}}",
"unknown gem": "cachedir: /c\nw10k: {gems: [nope]}\nsources: {a: {remote: r, basedir: /b}}",
} {
if _, err := ParseConfig([]byte(in)); err == nil {
t.Errorf("%s: expected error", name)
@@ -107,3 +115,28 @@ 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)
}
}
}
func TestParseConfigGems(t *testing.T) {
c, err := ParseConfig([]byte("cachedir: /c\nw10k: {gems: [toml, toml]}\nsources: {a: {remote: r, basedir: /b}}"))
if err != nil || !slices.Equal(c.W10k.Gems, []string{"toml"}) {
t.Fatalf("gems = %v, %v", c.W10k.Gems, err)
}
d := &Deployer{cfg: c}
c.W10k.GenerateTypes = true
if p := d.worktreePrefix("s"); p != "s-types"+gentypes.Version+"+toml-" {
t.Errorf("prefix %q does not key on gems", p)
}
}
+409 -101
View File
@@ -9,6 +9,7 @@ import (
"errors"
"fmt"
"log"
"log/slog"
"maps"
"os"
"path/filepath"
@@ -16,10 +17,13 @@ import (
"runtime/debug"
"slices"
"sort"
"strconv"
"strings"
"sync"
"syscall"
"time"
"git.unkin.net/unkin/w10k/internal/gentypes"
)
const (
@@ -46,13 +50,17 @@ type Deployer struct {
sem chan struct{}
mu sync.Mutex
flights map[string]*flight
skips map[string]int
counts map[string]int
Timings *slog.Logger
wtLocks sync.Map
}
type flight struct {
done chan struct{}
val string
err error
done chan struct{}
val string
worked bool
err error
}
type deployResult struct {
@@ -68,9 +76,11 @@ type deployResult struct {
}
type resolved struct {
path string
dir string
key string
name string
path string
dir string
key string
cache string
}
func New(cfg *Config, jobs int, grace time.Duration) *Deployer {
@@ -81,14 +91,15 @@ 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{}, counts: map[string]int{}}
}
func (d *Deployer) once(key string, fn func() (string, error)) (string, error) {
// once runs fn once per key; cache is miss for the caller that did the work, shared for callers that waited on it, hit when fn found it already done.
func (d *Deployer) once(key string, fn func() (string, bool, error)) (string, string, error) {
d.mu.Lock()
f, ok := d.flights[key]
if !ok {
f = &flight{done: make(chan struct{})}
f = &flight{done: make(chan struct{}), worked: true}
d.flights[key] = f
}
d.mu.Unlock()
@@ -96,15 +107,23 @@ func (d *Deployer) once(key string, fn func() (string, error)) (string, error) {
func() {
defer close(f.done)
defer recoverErr(&f.err, key)
f.val, f.err = fn()
f.val, f.worked, f.err = fn()
}()
}
<-f.done
return f.val, f.err
switch {
case !f.worked:
return f.val, "hit", f.err
case ok:
return f.val, "shared", f.err
}
return f.val, "miss", f.err
}
func (d *Deployer) limit(fn func() error) error {
func (d *Deployer) limit(ctx context.Context, fn func() error) error {
t := time.Now()
d.sem <- struct{}{}
addWait(ctx, time.Since(t))
defer func() { <-d.sem }()
return fn()
}
@@ -178,6 +197,8 @@ func recoverErr(err *error, what string) {
// Lock takes an exclusive flock on the cachedir, released by the returned func.
func (d *Deployer) Lock() (func(), error) {
_, end := d.phase(context.Background(), "lock")
defer end()
if err := os.MkdirAll(d.cfg.Cachedir, 0o755); err != nil {
return nil, err
}
@@ -201,34 +222,171 @@ func (d *Deployer) Sources() []*Source {
return out
}
// Deploy builds every environment, or only those named by env or branch; a named deploy skips purge and GC.
func (d *Deployer) Deploy(ctx context.Context, only []string, modules bool) error {
want := map[string]bool{}
for _, e := range only {
want[e] = true
}
found := map[string]bool{}
var errs []error
for _, s := range d.Sources() {
if err := d.deploySource(ctx, s, want, found, modules); err != nil {
errs = append(errs, fmt.Errorf("source %s: %w", s.Name, err))
ctx, end := d.phase(ctx, "run")
d.mu.Lock()
maps.DeleteFunc(d.flights, func(_ string, f *flight) bool {
select {
case <-f.done:
return true
default:
return false
}
})
clear(d.skips)
clear(d.counts)
d.mu.Unlock()
var errs []error
var plans []*srcPlan
for _, s := range d.Sources() {
p, err := d.planSource(ctx, s)
if err != nil {
d.count("failed")
errs = append(errs, fmt.Errorf("source %s: %w", s.Name, err))
continue
}
plans = append(plans, p)
}
for e := range want {
if !found[e] {
errs = append(errs, fmt.Errorf("environment %s not found", e))
if err := d.checkAliases(plans); err != nil {
d.count("failed")
end()
return errors.Join(append(errs, err)...)
}
errs = append(errs, d.selectEnvs(plans, only)...)
for _, p := range plans {
if err := d.deploySource(ctx, p, modules); err != nil {
errs = append(errs, fmt.Errorf("source %s: %w", p.s.Name, err))
}
}
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])
}
var summary []any
for _, k := range []string{"created", "updated", "unchanged", "failed", "removed"} {
summary = append(summary, k, d.counts[k])
}
d.mu.Unlock()
end(summary...)
return errors.Join(errs...)
}
// srcPlan is a source's resolved envs, the branches that got none and why, and the envs to build (nil = all).
type srcPlan struct {
s *Source
envs map[string]envRef
skipped map[string]error
want map[string]bool
}
// selectEnvs resolves args to envs as a full deploy would: env names in any source first, else raw branch names.
func (d *Deployer) selectEnvs(plans []*srcPlan, only []string) []error {
if len(only) == 0 {
return nil
}
var errs []error
for _, p := range plans {
p.want = map[string]bool{}
}
for _, a := range only {
if t, ok := d.cfg.W10k.Aliases[a]; ok {
a = t
}
isEnv := slices.ContainsFunc(plans, func(p *srcPlan) bool { _, ok := p.envs[a]; return ok })
hit := false
var why []error
for _, p := range plans {
if isEnv {
if _, ok := p.envs[a]; ok {
p.want[a], hit = true, true
}
continue
}
for name, ref := range p.envs {
if ref.branch == a {
p.want[name], hit = true, true
}
}
for _, err := range p.skipErrs(func(b string) bool {
name, _, _ := p.s.EnvName(b)
return b == a || name == a
}) {
d.count("failed")
why = append(why, fmt.Errorf("source %s: %w", p.s.Name, err))
}
}
if !hit && len(why) == 0 {
why = append(why, fmt.Errorf("environment %s not found", a))
}
errs = append(errs, why...)
}
return errs
}
// checkAliases requires every alias name to be free and its target to come from at most one source.
func (d *Deployer) checkAliases(plans []*srcPlan) error {
var errs []error
for _, a := range slices.Sorted(maps.Keys(d.cfg.W10k.Aliases)) {
t := d.cfg.W10k.Aliases[a]
var in []string
for _, p := range plans {
if _, ok := p.envs[a]; ok {
errs = append(errs, fmt.Errorf("alias %s collides with an environment in source %s", a, p.s.Name))
}
if _, ok := p.envs[t]; ok {
in = append(in, p.s.Name)
}
}
if len(in) > 1 {
errs = append(errs, fmt.Errorf("alias %s: target %s exists in sources %s", a, t, strings.Join(in, ", ")))
}
}
return errors.Join(errs...)
}
// aliasesOf returns the aliases targeting env, sorted.
func (d *Deployer) aliasesOf(env string) []string {
var out []string
for a, t := range d.cfg.W10k.Aliases {
if t == env {
out = append(out, a)
}
}
slices.Sort(out)
return out
}
// Aliases maps alias env name -> target env name.
func (d *Deployer) Aliases() map[string]string { return d.cfg.W10k.Aliases }
// skipErrs returns the distinct reasons, in branch order, for skipped branches match accepts.
func (p *srcPlan) skipErrs(match func(string) bool) []error {
var out []error
seen := map[error]bool{}
for _, b := range slices.Sorted(maps.Keys(p.skipped)) {
if err := p.skipped[b]; match(b) && !seen[err] {
seen[err] = true
out = append(out, err)
}
}
return out
}
func (d *Deployer) count(outcome string) {
d.mu.Lock()
d.counts[outcome]++
d.mu.Unlock()
}
type envRef struct{ branch, sha string }
// Environments maps env name -> branch; skipped holds names no branch won because only corrected branches claimed them.
func (d *Deployer) Environments(ctx context.Context, s *Source) (envs map[string]envRef, skipped map[string]bool, errs []error) {
// Environments maps env name -> branch and sha, and each branch that gets no env to why.
func (d *Deployer) Environments(ctx context.Context, s *Source) (map[string]envRef, map[string]error, error) {
all, err := d.branches(ctx, d.srcMirror(s))
if err != nil {
return nil, nil, []error{err}
return nil, nil, err
}
names := make([]string, 0, len(all))
for b := range all {
@@ -237,13 +395,14 @@ func (d *Deployer) Environments(ctx context.Context, s *Source) (envs map[string
sort.Strings(names)
claims := map[string][]string{}
exact := map[string]string{}
skipped := map[string]error{}
for _, b := range names {
if s.Ignored(b) {
continue
}
name, corrected, err := s.EnvName(b)
if err != nil {
errs = append(errs, err)
skipped[b] = err
continue
}
if !corrected {
@@ -251,7 +410,7 @@ func (d *Deployer) Environments(ctx context.Context, s *Source) (envs map[string
}
claims[name] = append(claims[name], b)
}
envs, skipped = map[string]envRef{}, map[string]bool{}
envs := map[string]envRef{}
for _, name := range slices.Sorted(maps.Keys(claims)) {
bs := claims[name]
win, isExact := exact[name]
@@ -259,49 +418,61 @@ func (d *Deployer) Environments(ctx context.Context, s *Source) (envs map[string
win = bs[0]
}
if win == "" {
errs = append(errs, fmt.Errorf("branches %s all correct to environment %s, skipped", strings.Join(bs, ", "), name))
skipped[name] = true
err := fmt.Errorf("branches %s all correct to environment %s, skipped", strings.Join(bs, ", "), name)
for _, b := range bs {
skipped[b] = err
}
continue
}
for _, b := range bs {
if b != win {
errs = append(errs, fmt.Errorf("branch %s collides with environment %s, skipped", b, name))
skipped[b] = fmt.Errorf("branch %s collides with environment %s, skipped", b, name)
}
}
if !isExact && s.InvalidBranches == "correct_and_warn" {
log.Printf("warning: branch %s deployed as environment %s", win, name)
}
envs[name] = envRef{win, all[win]}
}
return envs, skipped, errs
return envs, skipped, nil
}
func (d *Deployer) deploySource(ctx context.Context, s *Source, want, found map[string]bool, modules bool) error {
if err := d.syncMirror(ctx, d.srcMirror(s), s.Remote, nil, envRefspecs); err != nil {
return err
func (d *Deployer) planSource(ctx context.Context, s *Source) (*srcPlan, error) {
fctx, end := d.phase(ctx, "source.fetch", "source", s.Name)
err := d.syncMirror(fctx, d.srcMirror(s), s.Remote, nil, envRefspecs)
end()
if err != nil {
return nil, err
}
envs, skipped, errs := d.Environments(ctx, s)
if envs == nil {
return errors.Join(errs...)
bctx, end := d.phase(ctx, "source.branches", "source", s.Name)
envs, skipped, err := d.Environments(bctx, s)
end("envs", len(envs))
return &srcPlan{s: s, envs: envs, skipped: skipped}, err
}
func (d *Deployer) deploySource(ctx context.Context, p *srcPlan, modules bool) error {
s, full := p.s, p.want == nil
var errs []error
if full {
errs = p.skipErrs(func(string) bool { return true })
for range errs {
d.count("failed")
}
}
full := len(want) == 0
if err := os.MkdirAll(s.Basedir, 0o755); err != nil {
return err
return errors.Join(append(errs, err)...)
}
var mu sync.Mutex
var wg sync.WaitGroup
for name, ref := range envs {
if !full && !want[name] {
for _, name := range slices.Sorted(maps.Keys(p.envs)) {
ref := p.envs[name]
if !full && !p.want[name] {
continue
}
found[name] = true
if _, corrected, _ := s.EnvName(ref.branch); corrected && s.InvalidBranches == "correct_and_warn" {
log.Printf("warning: branch %s deployed as environment %s", ref.branch, name)
}
wg.Add(1)
go func() {
defer wg.Done()
err := func() (err error) {
defer recoverErr(&err, "environment "+name)
return d.deployEnv(ctx, s, name, ref, modules)
}()
err := errors.Join(d.deployEnv(ctx, s, name, ref, modules), d.swapAliases(s, name))
if err != nil {
mu.Lock()
errs = append(errs, fmt.Errorf("environment %s: %w", name, err))
@@ -311,11 +482,34 @@ func (d *Deployer) deploySource(ctx context.Context, s *Source, want, found map[
}
wg.Wait()
if full {
errs = append(errs, d.purge(s, envs, skipped))
errs = append(errs, d.purge(s, p.envs, p.skipped))
}
return errors.Join(errs...)
}
// swapAliases points each alias of env at env's current worktree itself, never at env's link.
func (d *Deployer) swapAliases(s *Source, env string) error {
aliases := d.aliasesOf(env)
target := d.owned(s, filepath.Join(s.Basedir, env))
if target == "" {
if len(aliases) > 0 {
log.Printf("error: environment %s has no w10k worktree, aliases %s left untouched", env, strings.Join(aliases, ", "))
}
return nil
}
for _, a := range aliases {
link := filepath.Join(s.Basedir, a)
if t, err := os.Readlink(link); err == nil && t == target {
continue
}
if err := Swap(target, link); err != nil {
return fmt.Errorf("alias %s: %w", a, err)
}
log.Printf("alias %s -> %s", a, filepath.Base(target))
}
return nil
}
func linkTarget(link string) string {
t, err := os.Readlink(link)
if err != nil {
@@ -334,14 +528,41 @@ func (d *Deployer) owned(s *Source, link string) string {
return ""
}
func (d *Deployer) deployEnv(ctx context.Context, s *Source, name string, ref envRef, modules bool) error {
// 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" + strings.Join(append([]string{gentypes.Version}, d.cfg.W10k.Gems...), "+") + "-"
}
return sha + "-"
}
func (d *Deployer) deployEnv(ctx context.Context, s *Source, name string, ref envRef, modules bool) (err error) {
sha := ref.sha
start := time.Now()
ctx, total := d.phase(ctx, "env.total", "source", s.Name, "env", name)
outcome := "unchanged"
defer func() {
if err != nil {
outcome = "failed"
}
d.count(outcome)
total("outcome", outcome)
}()
defer recoverErr(&err, "environment "+name)
link := filepath.Join(s.Basedir, name)
_, end := d.phase(ctx, "env.resolve", "sha", sha)
cur := d.owned(s, link)
if cur != "" && !modules && strings.HasPrefix(filepath.Base(cur), sha+"-") && d.complete(cur) {
prefix := d.worktreePrefix(sha)
base := filepath.Base(cur)
unchanged := cur != "" && !modules && strings.HasPrefix(base, prefix) && len(base) == len(prefix)+12 && d.complete(cur)
end()
if unchanged {
d.emit(ctx, "env.skip", time.Since(start), "reason", "unchanged")
return nil
}
pf, checksum, err := d.puppetfile(ctx, d.srcMirror(s), sha)
pctx, end := d.phase(ctx, "env.puppetfile")
pf, checksum, err := d.puppetfile(pctx, d.srcMirror(s), sha)
end()
if err != nil {
return err
}
@@ -353,25 +574,40 @@ 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) {
d.emit(ctx, "env.skip", time.Since(start), "reason", "modules_unchanged")
return nil
}
if _, err := d.once("env:"+target, func() (string, error) {
skipped, _, err := d.once("env:"+target, func() (string, bool, error) {
if d.complete(target) {
return "", nil
return "", false, nil
}
started := d.now().UTC()
if err := d.checkout(ctx, s, sha, target, mods); err != nil {
return "", err
return "", true, err
}
return "", d.prepare(s, ref, checksum, target, mods, started)
}); err != nil {
v, err := d.prepare(ctx, s, name, ref, checksum, target, mods, started)
return v, true, err
})
if err != nil {
return err
}
if err := Swap(target, link); err != nil {
_, end = d.phase(ctx, "env.swap")
err = Swap(target, link)
end()
if err != nil {
return err
}
outcome = "updated"
if cur == "" {
outcome = "created"
}
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
}
@@ -423,9 +659,12 @@ func (d *Deployer) installModules(ctx context.Context, pf *Puppetfile) ([]resolv
func (d *Deployer) gitModule(ctx context.Context, m Module) (resolved, error) {
key := urlKey(m.Git)
mirror := d.path("git", key+".git")
if _, err := d.once("fetch:"+mirror, func() (string, error) {
return "", d.syncMirror(ctx, mirror, m.Git, modFetchOpts, modRefspecs)
}); err != nil {
pctx, end := d.phase(ctx, "module.fetch", "module", m.Name)
_, c, err := d.once("fetch:"+mirror, func() (string, bool, error) {
return "", true, d.syncMirror(pctx, mirror, m.Git, modFetchOpts, modRefspecs)
})
end("cache", c)
if err != nil {
return resolved{}, err
}
var cands []string
@@ -441,41 +680,47 @@ func (d *Deployer) gitModule(ctx context.Context, m Module) (resolved, error) {
default:
cands = []string{"refs/w10k/HEAD"}
}
sha, err := d.revParse(ctx, mirror, cands...)
pctx, end = d.phase(ctx, "module.resolve", "module", m.Name)
sha, err := d.revParse(pctx, mirror, cands...)
dir := d.path("modules", key, sha)
end()
if err != nil {
return resolved{}, err
}
dir := d.path("modules", key, sha)
_, err = d.once("mod:"+dir, func() (string, error) {
pctx, end = d.phase(ctx, "module.worktree", "module", m.Name)
_, c, err = d.once("mod:"+dir, func() (string, bool, error) {
if d.complete(dir) {
return "", nil
return "", false, nil
}
tmp := dir + ".tmp"
for _, p := range []string{tmp, dir} {
if err := d.removeWorktree(ctx, mirror, p); err != nil {
return "", err
if err := d.removeWorktree(pctx, mirror, p); err != nil {
return "", true, err
}
}
if _, err := d.git(ctx, mirror, "worktree", "add", "--detach", "-q", "--", tmp, sha); err != nil {
return "", err
if _, err := d.git(pctx, mirror, "worktree", "add", "--detach", "-q", "--", tmp, sha); err != nil {
return "", true, err
}
if _, err := d.git(ctx, mirror, "worktree", "move", "--", tmp, dir); err != nil {
return "", err
if _, err := d.git(pctx, mirror, "worktree", "move", "--", tmp, dir); err != nil {
return "", true, err
}
return "", d.markDone(dir, nil)
return "", true, d.markDone(dir, nil)
})
return resolved{dir: dir, key: "git " + m.Git + " " + sha}, err
end("cache", c)
return resolved{name: m.Name, dir: dir, key: "git " + m.Git + " " + sha, cache: c}, err
}
func (d *Deployer) forgeModule(ctx context.Context, base string, m Module) (resolved, error) {
slug := m.Owner + "-" + m.Name
version := m.Version
if version == "" {
v, err := d.once("latest:"+base+" "+slug, func() (string, error) {
pctx, end := d.phase(ctx, "module.resolve", "module", slug)
v, c, err := d.once("latest:"+base+" "+slug, func() (string, bool, error) {
var v string
err := d.limit(func() (err error) { v, err = forgeLatest(ctx, base, slug); return err })
return v, err
err := d.limit(pctx, func() (err error) { v, err = forgeLatest(ctx, base, slug); return err })
return v, true, err
})
end("cache", c)
if err != nil {
return resolved{}, err
}
@@ -483,19 +728,35 @@ func (d *Deployer) forgeModule(ctx context.Context, base string, m Module) (reso
}
release := slug + "-" + version
dir := d.path("forge", release+"-"+shortHash(base))
_, err := d.once("forge:"+dir, func() (string, error) {
start := time.Now()
var dl, ex, wait time.Duration
_, c, err := d.once("forge:"+dir, func() (string, bool, error) {
if d.complete(dir) {
return "", nil
return "", false, nil
}
if err := os.RemoveAll(dir); err != nil {
return "", err
return "", true, err
}
if err := d.limit(func() error { return forgeInstall(ctx, base, release, dir) }); err != nil {
return "", err
q := time.Now()
if err := d.limit(ctx, func() error {
wait = time.Since(q)
t := time.Now()
var err error
dl, err = forgeInstall(ctx, base, release, dir)
ex = time.Since(t) - dl
dl += wait
return err
}); err != nil {
return "", true, err
}
return "", d.markDone(dir, nil)
return "", true, d.markDone(dir, nil)
})
return resolved{dir: dir, key: "forge " + base + " " + release}, err
if c != "miss" {
dl = time.Since(start)
}
d.emit(ctx, "module.download", dl, "module", slug, "cache", c, "wait", wait.Round(time.Microsecond))
d.emit(ctx, "module.extract", ex, "module", slug, "cache", c)
return resolved{name: slug, dir: dir, key: "forge " + base + " " + release, cache: c}, err
}
func (d *Deployer) checkout(ctx context.Context, s *Source, sha, target string, mods []resolved) error {
@@ -509,7 +770,10 @@ func (d *Deployer) checkout(ctx context.Context, s *Source, sha, target string,
if err := os.MkdirAll(filepath.Dir(target), 0o755); err != nil {
return err
}
if _, err := d.git(ctx, mirror, "worktree", "add", "--detach", "-q", "--", target, sha); err != nil {
wctx, end := d.phase(ctx, "env.worktree")
_, err := d.git(wctx, mirror, "worktree", "add", "--detach", "-q", "--", target, sha)
end()
if err != nil {
return err
}
root, err := os.OpenRoot(target)
@@ -518,7 +782,10 @@ func (d *Deployer) checkout(ctx context.Context, s *Source, sha, target string,
}
defer func() { _ = root.Close() }()
for _, mod := range mods {
if err := linkModule(root, mod.path, mod.dir); err != nil {
_, end := d.phase(ctx, "module.link", "module", mod.name, "cache", mod.cache)
err := linkModule(root, mod.path, mod.dir)
end()
if err != nil {
return err
}
}
@@ -540,7 +807,22 @@ 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(ctx context.Context, s *Source, name string, ref envRef, checksum, target string, mods []resolved, started time.Time) (string, error) {
var skipped []error
if d.cfg.W10k.GenerateTypes {
_, end := d.phase(ctx, "env.generate_types")
st, err := gentypes.GenerateGems(target, d.cfg.W10k.Gems, d.path("modules"), d.path("forge"))
end("generated", st.Generated, "skipped", len(st.Skipped), "up_to_date", st.UpToDate)
if err != nil {
return "", fmt.Errorf("generate types: %w", err)
}
skipped = st.Skipped
for _, e := range skipped {
log.Printf("error: environment %s: generate types: skipped %v", name, e)
}
}
_, end := d.phase(ctx, "env.marker")
defer end()
r := deployResult{
Name: ref.branch,
Signature: ref.sha,
@@ -557,13 +839,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.
@@ -619,13 +901,27 @@ func Swap(target, link string) error {
return os.Rename(tmp, link)
}
func (d *Deployer) purge(s *Source, envs map[string]envRef, skipped map[string]bool) error {
// purge removes owned envs no branch claims; a name only skipped branches claim keeps its live env, as do its aliases.
func (d *Deployer) purge(s *Source, envs map[string]envRef, skipped map[string]error) error {
entries, err := os.ReadDir(s.Basedir)
if err != nil {
return err
}
keep := map[string]bool{}
for name := range envs {
keep[name] = true
}
for b := range skipped {
if name, _, err := s.EnvName(b); err == nil {
keep[name] = true
}
}
for _, e := range entries {
if _, ok := envs[e.Name()]; ok || skipped[e.Name()] {
name := e.Name()
if t, ok := d.cfg.W10k.Aliases[name]; ok {
name = t
}
if keep[name] {
continue
}
link := filepath.Join(s.Basedir, e.Name())
@@ -635,6 +931,7 @@ func (d *Deployer) purge(s *Source, envs map[string]envRef, skipped map[string]b
if err := os.Remove(link); err != nil {
return err
}
d.count("removed")
log.Printf("environment %s removed", e.Name())
}
return nil
@@ -659,11 +956,14 @@ func (d *Deployer) Live(s *Source) (map[string]string, error) {
}
type gcRun struct {
d *Deployer
ctx context.Context
marks map[string]time.Time
seen map[string]bool
errs []error
d *Deployer
ctx context.Context
marks map[string]time.Time
seen map[string]bool
errs []error
marked int
removed int
delDur time.Duration
}
// collect marks p on first sight and removes it only once a previous run's mark is older than the grace period.
@@ -672,16 +972,21 @@ func (g *gcRun) collect(p string, remove func() error) {
t, ok := g.marks[p]
if !ok {
g.marks[p] = g.d.now()
g.marked++
log.Printf("gc: marked %s", p)
return
}
if g.d.now().Sub(t) < g.d.grace {
return
}
if err := remove(); err != nil {
rt := time.Now()
err := remove()
g.delDur += time.Since(rt)
if err != nil {
g.errs = append(g.errs, err)
return
}
g.removed++
delete(g.marks, p)
log.Printf("gc: removed %s", p)
}
@@ -720,6 +1025,7 @@ func (d *Deployer) GC(ctx context.Context) error { return d.gc(ctx, true) }
// gc drops the mark of everything live this run; only a sweep may add marks or delete, and only where every live set it needs was computed.
func (d *Deployer) gc(ctx context.Context, sweep bool) (err error) {
start := time.Now()
g := &gcRun{d: d, ctx: ctx, marks: d.loadMarks(), seen: map[string]bool{}}
defer func() {
for p := range g.marks {
@@ -728,6 +1034,8 @@ func (d *Deployer) gc(ctx context.Context, sweep bool) (err error) {
}
}
err = errors.Join(append(g.errs, d.saveMarks(g.marks))...)
d.emit(ctx, "gc.mark", time.Since(start)-g.delDur, "marked", g.marked, "pending", len(g.marks))
d.emit(ctx, "gc.delete", g.delDur, "removed", g.removed)
}()
liveEnv := map[string]bool{}
+855
View File
@@ -1,9 +1,13 @@
package deploy
import (
"bytes"
"context"
"encoding/json"
"fmt"
"log"
"log/slog"
"maps"
"net"
"net/http"
"net/http/cgi"
@@ -11,8 +15,11 @@ import (
"os"
"os/exec"
"path/filepath"
"runtime"
"slices"
"strings"
"sync"
"sync/atomic"
"testing"
"time"
)
@@ -617,6 +624,110 @@ 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)
}
prior := readFileT(t, filepath.Join(live, ".resource_types", "local.pp"))
old := live
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")) {
t.Fatal("an unparseable type is skipped while the env still deploys its other types")
}
if exists(filepath.Join(skipped, ".resource_types", "local.pp")) {
t.Fatal("a skipped type must have no .pp in the new worktree")
}
if got := readFileT(t, filepath.Join(old, ".resource_types", "local.pp")); got != prior {
t.Fatalf("the old worktree's output must be untouched, got:\n%s", got)
}
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"})
@@ -694,6 +805,312 @@ func TestGCKeepsModulesOfRemovedSource(t *testing.T) {
}
}
func TestNamedDeployTouchesOnlyNamed(t *testing.T) {
f := newFixture(t)
old := commit(t, f.control, map[string]string{"Puppetfile": f.puppetfile(), "manifests/site.pp": "node default {}\n"})
gitT(t, f.control, "branch", "gone")
commit(t, f.control, map[string]string{"manifests/site.pp": "node other {}\n"})
gitT(t, f.control, "branch", "gone2")
commit(t, f.control, map[string]string{"manifests/site.pp": "node default { }\n"})
gitT(t, f.control, "branch", "benvin/foo-bar")
f.mustDeploy(false)
gone, gone2 := f.env("gone"), f.env("gone2")
gitT(t, f.control, "branch", "-D", "gone", "gone2")
f.mustDeploy(false)
f.clock = f.clock.Add(11 * time.Minute)
marks := func() map[string]time.Time {
m := map[string]time.Time{}
if err := json.Unmarshal([]byte(readFileT(t, f.cache(gcStateFile))), &m); err != nil {
t.Fatal(err)
}
return m
}
before := marks()
if _, ok := before[gone2]; !ok {
t.Fatalf("gone2 must be marked: %v", before)
}
gitT(t, f.control, "branch", "-f", "benvin/foo-bar", old)
main := f.env("main")
if err := f.deploy(false, "benvin/foo-bar"); err != nil {
t.Fatal(err)
}
if f.env("benvin_foo_bar") != gone {
t.Fatal("a raw branch name deploys its sanitised env, reviving the matching worktree")
}
delete(before, gone)
if f.env("main") != main || !exists(gone2) || !maps.Equal(marks(), before) {
t.Fatalf("a named deploy must clear only the marks of what it revives: %v", marks())
}
sha := commit(t, f.control, map[string]string{"manifests/site.pp": "node x {}\n"})
if err := f.deploy(false, "main"); err != nil || !strings.HasPrefix(filepath.Base(f.env("main")), sha+"-") {
t.Fatalf("env name deploys: %v", err)
}
if err := f.deploy(false, "main", "nope"); err == nil || !strings.Contains(err.Error(), "nope not found") {
t.Fatalf("unknown env must error: %v", err)
}
if !exists(gone2) {
t.Fatal("named deploys never GC")
}
}
func TestNamedDeployCollisionLoserKeepsOut(t *testing.T) {
f := newFixture(t)
commit(t, f.control, map[string]string{"manifests/site.pp": "node default {}\n"})
gitT(t, f.control, "checkout", "-q", "-b", "a_b")
win := commit(t, f.control, map[string]string{"manifests/site.pp": "node a {}\n"})
gitT(t, f.control, "checkout", "-q", "-b", "a-b")
commit(t, f.control, map[string]string{"manifests/site.pp": "node b {}\n"})
_ = f.deploy(false)
err := f.deploy(false, "a-b")
if !strings.HasPrefix(filepath.Base(f.env("a_b")), win+"-") {
t.Fatalf("named deploy of collision loser a-b took env a_b: %s", f.env("a_b"))
}
if err == nil || !strings.Contains(err.Error(), "a-b collides") {
t.Fatalf("want collision error for a-b, got %v", err)
}
if err := f.deploy(false, "a_b"); err != nil || !strings.HasPrefix(filepath.Base(f.env("a_b")), win+"-") {
t.Fatalf("named deploy of a_b must keep the full-deploy winner: %v", err)
}
}
func TestNamedDeployCorrectedCollisionSkipsAll(t *testing.T) {
f := newFixture(t)
commit(t, f.control, map[string]string{"manifests/site.pp": "node default {}\n"})
gitT(t, f.control, "branch", "a-b")
gitT(t, f.control, "branch", "a.b")
for _, arg := range []string{"a.b", "a_b"} {
err := f.deploy(false, arg)
if exists(filepath.Join(f.basedir, "a_b")) {
t.Fatalf("deploy %s built a_b, which a full deploy skips", arg)
}
if err == nil || !strings.Contains(err.Error(), "a-b") || !strings.Contains(err.Error(), "a.b") {
t.Fatalf("deploy %s: want collision error naming both branches, got %v", arg, err)
}
}
}
func TestNamedDeployPrefixedSources(t *testing.T) {
f := newFixture(t)
commit(t, f.control, map[string]string{"manifests/site.pp": "node default {}\n"})
gitT(t, f.control, "branch", "benvin/x")
pbase := filepath.Join(f.root, "code", "penvs")
p := &Source{Name: "p", Remote: f.control, Basedir: pbase, Prefix: "p", InvalidBranches: "correct_and_warn"}
f.cfg.Sources["p"] = p
penv := func(name string) string { return f.deployer().owned(p, filepath.Join(pbase, name)) }
var logs bytes.Buffer
log.SetOutput(&logs)
defer log.SetOutput(os.Stderr)
if err := f.deploy(false, "main"); err != nil || f.env("main") == "" {
t.Fatalf("deploy main: %v", err)
}
if strings.Contains(logs.String(), "benvin/x") {
t.Fatalf("named deploy warned about a branch it did not deploy:\n%s", logs.String())
}
if penv("p_main") != "" {
t.Fatal("env name main also deployed branch main of source p as p_main")
}
if err := f.deploy(false, "p_main"); err != nil || penv("p_main") == "" {
t.Fatalf("deploy p_main: %v", err)
}
if err := f.deploy(false, "benvin/x"); err != nil || f.env("benvin_x") == "" || penv("p_benvin_x") == "" {
t.Fatalf("raw branch benvin/x must deploy in every source: %v", err)
}
}
func TestNamedDeployIgnoresUnrelatedInvalid(t *testing.T) {
f := newFixture(t)
f.cfg.Sources["unkin"].InvalidBranches = "error"
commit(t, f.control, map[string]string{"manifests/site.pp": "node default {}\n"})
gitT(t, f.control, "branch", "bad-name")
if err := f.deploy(false, "main"); err != nil {
t.Fatalf("unrelated invalid branch failed named deploy: %v", err)
}
if err := f.deploy(false, "bad-name"); err == nil || !strings.Contains(err.Error(), "not a valid environment name") {
t.Fatalf("named invalid branch must error: %v", err)
}
}
func timingLines(s string) []map[string]string {
var out []map[string]string
for line := range strings.Lines(s) {
kv := map[string]string{}
for _, f := range strings.Fields(line) {
k, v, _ := strings.Cut(f, "=")
kv[k] = v
}
out = append(out, kv)
}
return out
}
func TestTimingsPhases(t *testing.T) {
f := newFixture(t)
f.cfg.W10k.GenerateTypes = true
commit(t, f.control, map[string]string{"Puppetfile": f.puppetfile()})
var buf bytes.Buffer
d := f.deployer()
d.Timings = slog.New(slog.NewTextHandler(&buf, nil))
unlock, err := d.Lock()
if err != nil {
t.Fatal(err)
}
unlock()
src := map[string]string{"source.fetch": "", "source.branches": "", "env.resolve": "", "gc.mark": "", "gc.delete": "", "run": ""}
with := func(m map[string]string) map[string]string {
for k, v := range src {
m[k] = v
}
return m
}
runs := []struct {
modules bool
want map[string]string
}{
{false, with(map[string]string{
"lock": "", "env.puppetfile": "", "module.resolve": ",,miss", "module.fetch": "miss,shared", "module.worktree": "miss,shared",
"module.download": "miss,miss", "module.extract": "miss,miss", "module.link": "miss,miss,miss,shared",
"env.worktree": "", "env.generate_types": "", "env.marker": "", "env.swap": "", "env.total": "created",
})},
{false, with(map[string]string{"env.skip": "unchanged", "env.total": "unchanged"})},
{true, with(map[string]string{
"env.puppetfile": "", "module.resolve": ",,miss", "module.fetch": "miss,shared", "module.worktree": "hit,hit",
"module.download": "hit,hit", "module.extract": "hit,hit", "env.skip": "modules_unchanged", "env.total": "unchanged",
})},
}
var all strings.Builder
for i, r := range runs {
if err := d.Deploy(context.Background(), nil, r.modules); err != nil {
t.Fatal(err)
}
labels := map[string][]string{}
for _, kv := range timingLines(buf.String()) {
labels[kv["phase"]] = append(labels[kv["phase"]], kv["cache"]+kv["outcome"]+kv["reason"])
if strings.HasPrefix(kv["phase"], "module.") && (kv["source"] != "unkin" || kv["env"] != "main") {
t.Errorf("run %d: module phase lacks inherited source/env: %v", i, kv)
}
}
got := map[string]string{}
for k, v := range labels {
slices.Sort(v)
got[k] = strings.Join(v, ",")
}
if !maps.Equal(got, r.want) {
t.Errorf("run %d labels:\n got %v\nwant %v", i, got, r.want)
}
all.WriteString(buf.String())
buf.Reset()
}
out := all.String()
for _, want := range []string{
" dur=", " wait=", " source=unkin", " env=main", " module=bind", " module=acme-thing",
" generated=", " up_to_date=", " skipped=", " marked=", " removed=", " created=1", " updated=", " unchanged=1", " failed=",
} {
if !strings.Contains(out, want) {
t.Errorf("timings lack %q", want)
}
}
if t.Failed() {
t.Log(out)
}
}
func TestTimingsColdCacheHasNoHits(t *testing.T) {
f := newFixture(t)
commit(t, f.control, map[string]string{"Puppetfile": f.puppetfile()})
var buf bytes.Buffer
d := f.deployer()
d.Timings = slog.New(slog.NewTextHandler(&buf, nil))
if err := d.Deploy(context.Background(), nil, false); err != nil {
t.Fatal(err)
}
for _, kv := range timingLines(buf.String()) {
if kv["cache"] == "hit" {
t.Errorf("cold cachedir reports %s module=%s cache=hit dur=%s", kv["phase"], kv["module"], kv["dur"])
}
}
}
func TestTimingsCacheLabels(t *testing.T) {
f := newFixture(t)
commit(t, f.control, map[string]string{"Puppetfile": f.puppetfile()})
for run, want := range []string{"miss", "hit"} {
var buf bytes.Buffer
d := f.deployer()
d.Timings = slog.New(slog.NewTextHandler(&buf, nil))
if err := d.Deploy(context.Background(), nil, true); err != nil {
t.Fatal(err)
}
misses := 0
for _, kv := range timingLines(buf.String()) {
switch kv["phase"] {
case "module.download":
if kv["module"] == "acme-thing" && kv["cache"] != want {
t.Errorf("run %d: acme-thing download cache=%s, want %s", run, kv["cache"], want)
}
case "module.worktree":
if kv["cache"] == "miss" {
misses++
}
}
}
if (run == 0) != (misses > 0) {
t.Errorf("run %d: module.worktree misses=%d", run, misses)
}
}
}
func TestTimingsWaitWithinDur(t *testing.T) {
f := newFixture(t)
commit(t, f.control, map[string]string{"Puppetfile": f.puppetfile()})
for _, b := range []string{"a", "b", "c", "d", "e", "f", "g", "h"} {
gitT(t, f.control, "branch", b)
}
var buf bytes.Buffer
d := New(f.cfg, 1, 10*time.Minute)
d.Timings = slog.New(slog.NewTextHandler(&buf, nil))
if err := d.Deploy(context.Background(), nil, false); err != nil {
t.Fatal(err)
}
contended := false
for _, kv := range timingLines(buf.String()) {
if kv["phase"] == "run" || kv["phase"] == "env.total" {
if _, ok := kv["wait"]; ok {
t.Errorf("aggregate phase reports wait: %v", kv)
}
}
w, ok := kv["wait"]
if !ok {
continue
}
wd, err1 := time.ParseDuration(w)
dd, err2 := time.ParseDuration(kv["dur"])
if err1 != nil || err2 != nil || wd > dd {
t.Errorf("wait must not exceed dur: %v", kv)
}
if wd > 0 && kv["phase"] != "module.download" {
contended = true
}
}
if !contended {
t.Fatalf("-j1 with 9 envs reports no wait on any phase() leaf:\n%s", buf.String())
}
}
func TestTimingsOffEmitsNothing(t *testing.T) {
f := newFixture(t)
commit(t, f.control, map[string]string{"Puppetfile": f.puppetfile()})
var buf bytes.Buffer
prev := slog.Default()
slog.SetDefault(slog.New(slog.NewTextHandler(&buf, nil)))
defer slog.SetDefault(prev)
f.mustDeploy(false)
f.mustDeploy(false)
if strings.Contains(buf.String(), "phase=") {
t.Fatalf("timings off must emit nothing:\n%s", buf.String())
}
}
func TestPuppetfileLocalRepoRejected(t *testing.T) {
f := newFixture(t)
secret := filepath.Join(f.root, "secret")
@@ -805,10 +1222,20 @@ func TestPanicFailsOnlyItsEnv(t *testing.T) {
}
return runGit(ctx, dir, args...)
}
var buf bytes.Buffer
d.Timings = slog.New(slog.NewTextHandler(&buf, nil))
err := d.Deploy(context.Background(), nil, false)
if err == nil || !strings.Contains(err.Error(), "environment bad: panic: boom") {
t.Fatalf("panic not reported as env error: %v", err)
}
for _, kv := range timingLines(buf.String()) {
if kv["phase"] == "env.total" && kv["env"] == "bad" && kv["outcome"] != "failed" {
t.Errorf("panicking env outcome=%s, want failed", kv["outcome"])
}
}
if !strings.Contains(buf.String(), " created=1 updated=0 unchanged=0 failed=1 ") {
t.Errorf("summary must count the panic as failed:\n%s", buf.String())
}
if f.env("main") == "" || f.env("bad") != "" {
t.Fatalf("main=%q bad=%q", f.env("main"), f.env("bad"))
}
@@ -817,6 +1244,26 @@ func TestPanicFailsOnlyItsEnv(t *testing.T) {
}
}
func TestSourceErrorsCountFailed(t *testing.T) {
f := newFixture(t)
commit(t, f.control, map[string]string{"manifests/site.pp": "\n"})
gitT(t, f.control, "branch", "bad-name")
cfg, err := ParseConfig(fmt.Appendf(nil, "cachedir: %s\nsources:\n unkin:\n remote: %s\n basedir: %s\n invalid_branches: error\n gone:\n remote: %s\n basedir: %s\n",
f.cfg.Cachedir, f.control, f.basedir, filepath.Join(f.root, "missing"), filepath.Join(f.root, "gone-envs")))
if err != nil {
t.Fatal(err)
}
var buf bytes.Buffer
d := New(cfg, 4, 10*time.Minute)
d.Timings = slog.New(slog.NewTextHandler(&buf, nil))
if err := d.Deploy(context.Background(), nil, false); err == nil {
t.Fatal("source errors not returned")
}
if !strings.Contains(buf.String(), " created=1 updated=0 unchanged=0 failed=2 ") {
t.Errorf("summary must count the fetch and branch errors as failed:\n%s", buf.String())
}
}
func TestConcurrentWorktreeAddsOneMirror(t *testing.T) {
f := newFixture(t)
for i := range 40 {
@@ -1057,6 +1504,290 @@ func TestCorrectedBranchCollisionSkipsAll(t *testing.T) {
}
}
func aliasFixture(t *testing.T) (*fixture, string, string) {
f := newFixture(t)
commit(t, f.control, map[string]string{"manifests/site.pp": "node default {}\n"})
gitT(t, f.control, "branch", "develop")
f.cfg.W10k.Aliases = map[string]string{"production": "develop"}
return f, filepath.Join(f.basedir, "production"), filepath.Join(f.basedir, "develop")
}
func readlinkT(t *testing.T, p string) string {
t.Helper()
s, err := os.Readlink(p)
if err != nil {
t.Fatal(err)
}
return s
}
func TestAliasPointsAtTargetWorktree(t *testing.T) {
f, prod, dev := aliasFixture(t)
f.mustDeploy(false)
got, want := readlinkT(t, prod), readlinkT(t, dev)
if got != want || !filepath.IsAbs(got) || filepath.Dir(got) != f.cache("worktrees", "unkin") {
t.Fatalf("production -> %q, develop -> %q; want the same absolute worktree", got, want)
}
live, err := f.deployer().Live(f.cfg.Sources["unkin"])
if err != nil || live["production"] != want {
t.Fatalf("alias must be live: %v %v", live, err)
}
}
func TestAliasSwapsAtomicallyWithTarget(t *testing.T) {
f, prod, dev := aliasFixture(t)
f.mustDeploy(false)
gitT(t, f.control, "checkout", "-q", "develop")
sha := commit(t, f.control, map[string]string{"manifests/site.pp": "node new {}\n"})
stop := make(chan struct{})
missing := make(chan string, 1)
go func() {
for {
select {
case <-stop:
close(missing)
return
default:
}
if _, err := os.Stat(prod); err != nil {
missing <- err.Error()
close(missing)
return
}
}
}()
f.mustDeploy(false)
close(stop)
if m, ok := <-missing; ok {
t.Fatalf("production vanished during swap: %s", m)
}
if got := readlinkT(t, prod); got != readlinkT(t, dev) || !strings.HasPrefix(filepath.Base(got), sha+"-") {
t.Fatalf("production -> %s, want develop's new worktree at %s", got, sha)
}
if exists(filepath.Join(f.basedir, ".production.w10k")) {
t.Fatal("leftover swap temp link")
}
}
func TestAliasNamedDeploys(t *testing.T) {
f, prod, dev := aliasFixture(t)
f.mustDeploy(false)
gitT(t, f.control, "checkout", "-q", "develop")
for _, arg := range []string{"develop", "production"} {
sha := commit(t, f.control, map[string]string{"manifests/site.pp": "node " + arg + " {}\n"})
main := f.env("main")
if err := f.deploy(false, arg); err != nil {
t.Fatalf("deploy %s: %v", arg, err)
}
if got := readlinkT(t, prod); got != readlinkT(t, dev) || !strings.HasPrefix(filepath.Base(got), sha+"-") {
t.Fatalf("deploy %s: production -> %s, want develop at %s", arg, got, sha)
}
if f.env("main") != main {
t.Fatalf("deploy %s touched main", arg)
}
}
}
func TestAliasValidationErrors(t *testing.T) {
t.Run("collision", func(t *testing.T) {
f, prod, _ := aliasFixture(t)
gitT(t, f.control, "branch", "production")
if err := f.deploy(false); err == nil || !strings.Contains(err.Error(), "alias production collides") {
t.Fatalf("want collision error, got %v", err)
}
if exists(prod) || f.env("develop") != "" {
t.Fatal("a config error must deploy nothing")
}
})
t.Run("ambiguous", func(t *testing.T) {
f, _, _ := aliasFixture(t)
f.cfg.Sources["other"] = &Source{Name: "other", Remote: f.control, Basedir: filepath.Join(f.root, "code", "other"), InvalidBranches: "correct_and_warn"}
if err := f.deploy(false, "main"); err == nil || !strings.Contains(err.Error(), "target develop exists in sources other, unkin") {
t.Fatalf("want ambiguity error, got %v", err)
}
if f.env("main") != "" {
t.Fatal("a config error must deploy nothing")
}
})
}
func TestAliasPurged(t *testing.T) {
t.Run("removed from config", func(t *testing.T) {
f, prod, _ := aliasFixture(t)
f.mustDeploy(false)
f.cfg.W10k.Aliases = nil
if err := f.deploy(false, "develop"); err != nil || !exists(prod) {
t.Fatalf("named deploys never purge: %v", err)
}
f.mustDeploy(false)
if exists(prod) {
t.Fatal("alias removed from config must be purged")
}
})
t.Run("target gone", func(t *testing.T) {
f, prod, _ := aliasFixture(t)
f.mustDeploy(false)
gitT(t, f.control, "branch", "-D", "develop")
f.mustDeploy(false)
if exists(prod) {
t.Fatal("alias of a vanished target must be purged")
}
})
}
func TestGCKeepsAliasOnlyWorktree(t *testing.T) {
f, prod, dev := aliasFixture(t)
f.mustDeploy(false)
wt := readlinkT(t, prod)
mustRemove(t, dev)
d := f.deployer()
for range 3 {
f.clock = f.clock.Add(11 * time.Minute)
if err := d.GC(context.Background()); err != nil {
t.Fatal(err)
}
}
if _, err := os.Stat(filepath.Join(wt, "manifests", "site.pp")); err != nil {
t.Fatalf("GC removed a worktree referenced by an alias: %v", err)
}
}
func TestAliasCutover(t *testing.T) {
for name, setup := range map[string]func(t *testing.T, prod string){
"real dir": func(t *testing.T, prod string) {
mkdirs(t, prod)
if err := os.WriteFile(filepath.Join(prod, "site.pp"), []byte("old"), 0o644); err != nil {
t.Fatal(err)
}
},
"relative symlink": func(t *testing.T, prod string) {
mkdirs(t, filepath.Join(filepath.Dir(prod), "g10k_develop"))
if err := os.Symlink("g10k_develop", prod); err != nil {
t.Fatal(err)
}
},
"absolute symlink": func(t *testing.T, prod string) {
g := filepath.Join(filepath.Dir(prod), "g10k_develop")
mkdirs(t, g)
if err := os.Symlink(g, prod); err != nil {
t.Fatal(err)
}
},
} {
t.Run(name, func(t *testing.T) {
f, prod, dev := aliasFixture(t)
setup(t, prod)
f.mustDeploy(false)
if got := readlinkT(t, prod); got != readlinkT(t, dev) || !filepath.IsAbs(got) {
t.Fatalf("production -> %q after cutover", got)
}
})
}
}
func TestAliasPinsCompileAcrossMove(t *testing.T) {
f, prod, _ := aliasFixture(t)
f.mustDeploy(false)
pinned, err := filepath.EvalSymlinks(prod)
if err != nil {
t.Fatal(err)
}
gitT(t, f.control, "checkout", "-q", "develop")
commit(t, f.control, map[string]string{"manifests/site.pp": "node moved {}\n"})
f.mustDeploy(false)
f.clock = f.clock.Add(time.Minute)
if err := f.deployer().GC(context.Background()); err != nil {
t.Fatal(err)
}
if got := readFileT(t, filepath.Join(pinned, "manifests", "site.pp")); got != "node default {}\n" {
t.Fatalf("pinned compile read %q", got)
}
if readFileT(t, filepath.Join(prod, "manifests", "site.pp")) != "node moved {}\n" {
t.Fatal("alias did not follow the move")
}
}
func TestAliasSurvivesTargetCollision(t *testing.T) {
f := newFixture(t)
commit(t, f.control, map[string]string{"manifests/site.pp": "node default {}\n"})
gitT(t, f.control, "branch", "feature-x")
f.cfg.W10k.Aliases = map[string]string{"production": "feature_x"}
f.mustDeploy(false)
prod, fx := filepath.Join(f.basedir, "production"), filepath.Join(f.basedir, "feature_x")
old := readlinkT(t, prod)
gitT(t, f.control, "branch", "feature.x")
if err := f.deploy(false); err == nil {
t.Fatal("want collision error")
}
if !exists(prod) || readlinkT(t, prod) != old || readlinkT(t, fx) != old {
t.Fatal("a colliding push must keep the target and its alias on their worktree")
}
}
func TestAliasKeptOnFetchFailure(t *testing.T) {
f, prod, _ := aliasFixture(t)
f.mustDeploy(false)
old := readlinkT(t, prod)
f.cfg.Sources["unkin"].Remote = filepath.Join(f.root, "missing")
if err := f.deploy(false); err == nil {
t.Fatal("want fetch error")
}
if readlinkT(t, prod) != old {
t.Fatal("fetch failure moved or purged the alias")
}
}
func failDevelop(t *testing.T, f *fixture) {
t.Helper()
gitT(t, f.control, "checkout", "-q", "develop")
commit(t, f.control, map[string]string{"Puppetfile": "mod 'bind', :git => 'file:///nope'\n"})
}
func TestAliasFollowsTargetOldWorktreeOnFailure(t *testing.T) {
f, prod, dev := aliasFixture(t)
f.mustDeploy(false)
old := readlinkT(t, dev)
failDevelop(t, f)
if err := f.deploy(false); err == nil {
t.Fatal("want deploy error")
}
if readlinkT(t, dev) != old || readlinkT(t, prod) != old {
t.Fatalf("develop -> %s, production -> %s, want both on %s", readlinkT(t, dev), readlinkT(t, prod), old)
}
}
func TestNewAliasOfFailingTargetReplacesLinkToLink(t *testing.T) {
f, prod, dev := aliasFixture(t)
f.cfg.W10k.Aliases = nil
f.mustDeploy(false)
if err := os.Symlink("develop", prod); err != nil {
t.Fatal(err)
}
failDevelop(t, f)
f.cfg.W10k.Aliases = map[string]string{"production": "develop"}
if err := f.deploy(false); err == nil {
t.Fatal("want deploy error")
}
if readlinkT(t, prod) != readlinkT(t, dev) {
t.Fatalf("production -> %s, want develop's worktree %s", readlinkT(t, prod), readlinkT(t, dev))
}
}
func TestAliasUntouchedWhenTargetHasNoLink(t *testing.T) {
f, prod, _ := aliasFixture(t)
f.mustDeploy(false)
old := readlinkT(t, prod)
gitT(t, f.control, "checkout", "-q", "-b", "staging")
commit(t, f.control, map[string]string{"Puppetfile": "mod 'bind', :git => 'file:///nope'\n"})
f.cfg.W10k.Aliases = map[string]string{"production": "staging"}
if err := f.deploy(false); err == nil {
t.Fatal("want deploy error")
}
if readlinkT(t, prod) != old || f.env("staging") != "" {
t.Fatalf("production -> %s, want %s untouched", readlinkT(t, prod), old)
}
}
func TestCorrectedBranchCollisionKeepsLiveEnv(t *testing.T) {
f := newFixture(t)
commit(t, f.control, map[string]string{"manifests/site.pp": "node default {}\n"})
@@ -1083,3 +1814,127 @@ func TestCorrectedBranchCollisionKeepsLiveEnv(t *testing.T) {
t.Fatal("live feature_x worktree must survive GC past grace")
}
}
func TestConcurrentDeploySharesInFlightFetch(t *testing.T) {
f := newFixture(t)
commit(t, f.control, map[string]string{"Puppetfile": f.puppetfile()})
d := f.deployer()
var srcFetches, modFetches atomic.Int32
bStarted := make(chan struct{})
var once sync.Once
d.runGit = func(ctx context.Context, dir string, args ...string) (string, error) {
if slices.Contains(args, "fetch") {
switch {
case slices.Contains(args, f.control):
if srcFetches.Add(1) == 2 {
once.Do(func() { close(bStarted) })
}
case slices.Contains(args, f.mod):
if modFetches.Add(1) == 1 {
<-bStarted
}
}
}
return runGit(ctx, dir, args...)
}
errc := make(chan error, 2)
go func() { errc <- d.Deploy(context.Background(), nil, false) }()
for modFetches.Load() == 0 {
runtime.Gosched()
}
go func() { errc <- d.Deploy(context.Background(), nil, false) }()
<-errc
<-errc
if n := modFetches.Load(); n != 1 {
t.Fatalf("module mirror fetched %d times; the second Deploy dropped the first's in-flight fetch", n)
}
}
func TestTimingsRemovalCounts(t *testing.T) {
f := newFixture(t)
commit(t, f.control, map[string]string{"manifests/site.pp": "\n"})
gitT(t, f.control, "checkout", "-q", "-b", "x")
commit(t, f.control, map[string]string{"manifests/site.pp": "# x\n"})
gitT(t, f.control, "checkout", "-q", "main")
f.mustDeploy(false)
gitT(t, f.control, "branch", "-D", "x")
run := func() map[string]map[string]string {
t.Helper()
var buf bytes.Buffer
d := f.deployer()
d.Timings = slog.New(slog.NewTextHandler(&buf, nil))
if err := d.Deploy(context.Background(), nil, false); err != nil {
t.Fatal(err)
}
got := map[string]map[string]string{}
for _, kv := range timingLines(buf.String()) {
got[kv["phase"]] = kv
}
return got
}
got := run()
if got["run"]["removed"] != "1" || got["gc.mark"]["marked"] != "1" || got["gc.delete"]["removed"] != "0" {
t.Errorf("removal run: run=%v gc.mark=%v gc.delete=%v", got["run"], got["gc.mark"], got["gc.delete"])
}
f.clock = f.clock.Add(11 * time.Minute)
got = run()
if got["run"]["removed"] != "0" || got["gc.mark"]["marked"] != "0" || got["gc.delete"]["removed"] != "1" {
t.Errorf("past grace: run=%v gc.mark=%v gc.delete=%v", got["run"], got["gc.mark"], got["gc.delete"])
}
}
func TestTimingsPanickingFlightIsMiss(t *testing.T) {
f := newFixture(t)
commit(t, f.control, map[string]string{"Puppetfile": f.puppetfile()})
d := f.deployer()
d.runGit = func(ctx context.Context, dir string, args ...string) (string, error) {
if slices.Contains(args, "fetch") && slices.Contains(args, f.mod) {
panic("boom")
}
return runGit(ctx, dir, args...)
}
var buf bytes.Buffer
d.Timings = slog.New(slog.NewTextHandler(&buf, nil))
if err := d.Deploy(context.Background(), nil, false); err == nil || !strings.Contains(err.Error(), "panic: boom") {
t.Fatalf("panic not reported: %v", err)
}
var got []string
for _, kv := range timingLines(buf.String()) {
if kv["phase"] == "module.fetch" {
got = append(got, kv["cache"])
}
}
slices.Sort(got)
if !slices.Equal(got, []string{"miss", "shared"}) {
t.Errorf("panicking fetch cache labels %v, want [miss shared]\n%s", got, buf.String())
}
}
func TestTimingsWorktreeLockWait(t *testing.T) {
f := newFixture(t)
commit(t, f.control, map[string]string{"manifests/site.pp": "\n"})
d := f.deployer()
var buf bytes.Buffer
d.Timings = slog.New(slog.NewTextHandler(&buf, nil))
d.runGit = func(ctx context.Context, dir string, args ...string) (string, error) {
if slices.Contains(args, "remove") {
mu := &sync.Mutex{}
mu.Lock()
d.wtLocks.Store(dir, mu)
time.AfterFunc(50*time.Millisecond, mu.Unlock)
}
return runGit(ctx, dir, args...)
}
if err := d.Deploy(context.Background(), nil, false); err != nil {
t.Fatal(err)
}
for _, kv := range timingLines(buf.String()) {
if kv["phase"] == "env.worktree" {
if w, err := time.ParseDuration(kv["wait"]); err != nil || w < 25*time.Millisecond {
t.Errorf("env.worktree wait=%s, want the worktree lock wait", kv["wait"])
}
return
}
}
t.Fatalf("no env.worktree line:\n%s", buf.String())
}
+10 -7
View File
@@ -73,24 +73,27 @@ func forgeLatest(ctx context.Context, base, slug string) (string, error) {
return r.CurrentRelease.Version, nil
}
func forgeInstall(ctx context.Context, base, release, dir string) error {
// forgeInstall returns the time spent reading the download, so the rest of the call is extraction.
func forgeInstall(ctx context.Context, base, release, dir string) (time.Duration, error) {
start := time.Now()
body, err := forgeGet(ctx, base+"/v3/files/"+release+".tar.gz")
if err != nil {
return err
return 0, err
}
defer func() { _ = body.Close() }()
if err := os.MkdirAll(filepath.Dir(dir), 0o755); err != nil {
return err
return 0, err
}
tmp, err := os.MkdirTemp(filepath.Dir(dir), ".tmp-")
if err != nil {
return err
return 0, err
}
if err := extract(&capReader{r: body, n: maxForgeDownload}, tmp, maxForgeExtracted); err != nil {
tr := &timedReader{r: &capReader{r: body, n: maxForgeDownload}, d: time.Since(start)}
if err := extract(tr, tmp, maxForgeExtracted); err != nil {
_ = os.RemoveAll(tmp)
return fmt.Errorf("%s: %w", release, err)
return tr.d, fmt.Errorf("%s: %w", release, err)
}
return os.Rename(tmp, dir)
return tr.d, os.Rename(tmp, dir)
}
// capReader fails once more than n bytes are read, so an oversized stream errors instead of being truncated silently.
+4 -2
View File
@@ -30,14 +30,16 @@ func runGit(ctx context.Context, dir string, args ...string) (string, error) {
return strings.TrimSpace(out.String()), nil
}
// git holds a -j slot only for the subprocess itself; worktree commands are serialized per repo since concurrent adds read each other's half-written admin dirs.
// git holds a -j slot only for the subprocess itself; worktree commands are serialized per repo since concurrent adds read each other's half-written admin dirs, and both waits count as wait.
func (d *Deployer) git(ctx context.Context, dir string, args ...string) (out string, err error) {
if len(args) > 0 && args[0] == "worktree" {
mu, _ := d.wtLocks.LoadOrStore(dir, &sync.Mutex{})
t := time.Now()
mu.(*sync.Mutex).Lock()
addWait(ctx, time.Since(t))
defer mu.(*sync.Mutex).Unlock()
}
err = d.limit(func() error {
err = d.limit(ctx, func() error {
ctx, cancel := context.WithTimeout(ctx, d.gitTimeout)
defer cancel()
out, err = d.runGit(ctx, dir, args...)
+72
View File
@@ -0,0 +1,72 @@
package deploy
import (
"context"
"io"
"slices"
"sync/atomic"
"time"
)
type spanKey struct{}
type span struct {
parent *span
attrs []any
wait atomic.Int64
kids atomic.Bool
}
func spanOf(ctx context.Context) *span {
s, _ := ctx.Value(spanKey{}).(*span)
return s
}
func addWait(ctx context.Context, w time.Duration) {
if s := spanOf(ctx); s != nil {
s.wait.Add(int64(w))
}
}
// phase times one unit of work; nested phases inherit attrs, and leaf phases report their -j slot and worktree lock waits as wait.
func (d *Deployer) phase(ctx context.Context, name string, attrs ...any) (context.Context, func(more ...any)) {
if d.Timings == nil {
return ctx, func(...any) {}
}
s := &span{parent: spanOf(ctx), attrs: attrs}
if s.parent != nil {
s.parent.kids.Store(true)
s.attrs = append(slices.Clip(s.parent.attrs), attrs...)
}
start := time.Now()
ctx = context.WithValue(ctx, spanKey{}, s)
return ctx, func(more ...any) {
if !s.kids.Load() {
more = append(more, "wait", time.Duration(s.wait.Load()).Round(time.Microsecond))
}
d.emit(ctx, name, time.Since(start), more...)
}
}
func (d *Deployer) emit(ctx context.Context, name string, dur time.Duration, args ...any) {
if d.Timings == nil {
return
}
line := []any{"phase", name, "dur", dur.Round(time.Microsecond)}
if s := spanOf(ctx); s != nil {
line = append(line, s.attrs...)
}
d.Timings.Info("timing", append(line, args...)...)
}
type timedReader struct {
r io.Reader
d time.Duration
}
func (t *timedReader) Read(p []byte) (int, error) {
s := time.Now()
n, err := t.r.Read(p)
t.d += time.Since(s)
return n, err
}
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
+362
View File
@@ -0,0 +1,362 @@
package gentypes
import (
"errors"
"os"
"path/filepath"
"slices"
"strconv"
"strings"
"testing"
"time"
)
const evalParent = "require 'puppet/util/inifile'\nclass Puppet::Provider::Zqp < Puppet::Provider\n initvars\n def self.tp\n" +
" resource_type.validproperties.reject { |p| p.to_sym == :ensure }\n end\n PP = [:x]\n def self.pp\n PP\n end\nend\n" +
"module PuppetX\n module Q\n class FileCollection < Puppet::Util::IniConfig::FileCollection; end\n" +
" File = FileCollection\n class Sub < File; end\n end\nend\n"
// evalProvider evaluates src as the body of Puppet::Type.type(:t).provide(:x) for a type t with properties b,
// ensure and a, after loading evalParent; parent sets parent: Puppet::Provider::Zqp.
func evalProvider(src string, parent bool) (c *classCtx, consts map[string]rval, w *world, err error) {
defer guard(&err)
w = newWorld(nil)
w.typ = &rtype{name: "t", validprops: []string{"b", "ensure", "a"}}
w.types["t"] = &loadedType{t: w.typ}
if err := (&parser{w: w}).load(libFile{mod: "m", rel: "puppet_x/zqp.rb", src: evalParent}); err != nil {
return nil, nil, w, err
}
toks, err := lex(src)
if err != nil {
return nil, nil, w, err
}
p := &parser{toks: toks, consts: map[string]rval{}, used: map[int]bool{}, w: w, defined: w.defined, mod: "m", dir: "puppet/provider/t", file: "x.rb", src: src}
c = newClass(kProv, true)
c.parent, c.block, c.typ = "Puppet::Provider", true, w.typ
if parent {
c.parent = "Puppet::Provider::Zqp"
}
return c, p.consts, w, p.body("", p.classStmt("Puppet::Type::t", c))
}
func inspect(v rval) string {
switch v.k {
case vStr:
return `"` + v.s + `"`
case vSym:
return ":" + v.s
case vArray:
var parts []string
for _, e := range v.arr {
parts = append(parts, inspect(e))
}
return "[" + strings.Join(parts, ", ") + "]"
case vNum:
return v.s
case vNil:
return "nil"
}
s, _ := rubyToS(v)
return s
}
// Each body loads in openvox 9.3.0 on Ruby 3.3 with the result in ruby (X's inspect, or - when X is unset, and the
// provider's public and private instance methods); w10k must reach want, or skip where it cannot prove the result.
var evalCases = []struct{ name, src, ruby, want string }{
{"selftype", "X = Puppet::Type.type(:t).validproperties\n", "[:b, :ensure, :a] pub=[] priv=[]", "[:b, :ensure, :a] pub=[]"},
{"scall own", "def self.tp\n resource_type.validproperties.reject { |p| p.to_sym == :ensure }\nend\nX = tp\n", "[:b, :a] pub=[] priv=[]", "[:b, :a] pub=[]"},
{"parent", "X = tp\n", "[:b, :a] pub=[] priv=[]", "[:b, :a] pub=[]"},
{"reject do", "X = [:c, :ensure, :a].reject do |q|\n q == :ensure\nend\n", "[:c, :a] pub=[] priv=[]", "[:c, :a] pub=[]"},
{"sym to_s plus", "X = :a.to_s + '='\n", "\"a=\" pub=[] priv=[]", "\"a=\" pub=[]"},
{"interp to_s", "X = \"#{:s}#{nil}#{1}#{true}#{'x'}\"\n", "\"s1truex\" pub=[] priv=[]", "\"s1truex\" pub=[]"},
{"to_sym", "X = 'a'.to_sym\n", ":a pub=[] priv=[]", ":a pub=[]"},
{"sym to_sym freeze", "X = :a.to_sym.to_s.freeze\n", "\"a\" pub=[] priv=[]", "\"a\" pub=[]"},
{"eq sym", "X = :a == :a\n", "true pub=[] priv=[]", "true pub=[]"},
{"eq sym str", "X = :a == 'a'\n", "false pub=[] priv=[]", "false pub=[]"},
{"ne", "X = :a != 'a'\n", "true pub=[] priv=[]", "true pub=[]"},
{"eq nil false", "X = nil == false\n", "false pub=[] priv=[]", "false pub=[]"},
{"eq int", "X = 1 == 1\n", "true pub=[] priv=[]", "true pub=[]"},
{"eq float", "X = 1.0 == 1\n", "true pub=[] priv=[]", "skip"},
{"percent i", "X = %i[a b]\n", "[:a, :b] pub=[] priv=[]", "[:a, :b] pub=[]"},
{"percent w", "X = %w[a b]\n", "[\"a\", \"b\"] pub=[] priv=[]", "[\"a\", \"b\"] pub=[]"},
{"defined true", "X = defined?(String)\n", "\"constant\" pub=[] priv=[]", "\"constant\" pub=[]"},
{"defined false", "X = defined?(Nope)\n", "nil pub=[] priv=[]", "skip"},
{"unless defined", "K = '-'.freeze unless defined? K\n", "- pub=[] priv=[]", "- pub=[]"},
{"unless defined read", "K = '-'.freeze unless defined? K\nX = K\n", "\"-\" pub=[] priv=[]", "skip"},
{"unless defined skip", "K = 1\nK2 = 2 unless defined?(K)\nX = K2\n", "raise NameError", "skip"},
{"if modifier", "X = 1 if 1 == 1\n", "1 pub=[] priv=[]", "1 pub=[]"},
{"unless modifier", "X = 1 unless 1 == 1\n", "- pub=[] priv=[]", "- pub=[]"},
{"loop literal", "[:a, :b].each do |f|\n define_method(f) do\n end\n define_method(f.to_s + '=') { |v| }\nend\n", "- pub=[:a, :a=, :b, :b=] priv=[]", "- pub=[:a, :a=, :b, :b=]"},
{"loop next if", "X = Puppet::Type.type(:t).validproperties\nX.each do |p|\n next if p == :ensure\n define_method(p) do\n end\n define_method(\"#{p}=\") do |v|\n end\nend\n", "[:b, :ensure, :a] pub=[:a, :a=, :b, :b=] priv=[]", "[:b, :ensure, :a] pub=[:a, :a=, :b, :b=]"},
{"loop next unless", "[:q1, :q2].each do |m|\n next unless m == :q2\n define_method(m) {}\nend\n", "- pub=[:q2] priv=[]", "- pub=[:q2]"},
{"loop scall to_sym", "def self.tp\n resource_type.validproperties\nend\ntp.each do |prop|\n define_method \"#{prop}=\".to_sym do |value|\n end\nend\n", "- pub=[:a=, :b=, :ensure=] priv=[]", "- pub=[:a=, :b=, :ensure=]"},
{"visibility", "private\n[:p1].each { |m| define_method(m) {} }\ndefine_method(\"p2\") {}\npublic\ndefine_method(:z) {}\n", "- pub=[:z] priv=[:p1, :p2]", "- pub=[:z]"},
{"bare define_method", "define_method(:zoned) do\nend\ndefine_method('zoned=') do |s|\nend\n", "- pub=[:zoned, :zoned=] priv=[]", "- pub=[:zoned, :zoned=]"},
{"empty loop", "[].each do |x|\n raise 'no'\nend\n", "- pub=[] priv=[]", "- pub=[]"},
{"raise loop", "[1].each do |x|\n raise 'no'\nend\n", "raise RuntimeError", "skip"},
{"other type", "X = Puppet::Type.type(:file).validproperties\n", "[:content, :checksum_value, :target, :ensure, :owner, :group, :mode, :type, :seluser, :selrole, :seltype, :selrange, :ctime, :mtime] pub=[] priv=[]", "skip"},
{"params", "def self.m(a)\n 1\nend\nX = m\n", "raise ArgumentError", "skip"},
{"command", "commands tp: 'tp'\nX = tp\n", "raise Puppet::MissingCommand", "skip"},
{"recursion", "def self.a\n a\nend\nX = a\n", "raise SystemStackError", "skip"},
{"str plus sym", "X = 'a' + :b\n", "raise TypeError", "skip"},
{"define_method int", "define_method(1) do\nend\n", "raise TypeError", "skip"},
{"define_method no block", "define_method(:x)\n", "raise ArgumentError", "skip"},
{"brace binds", "define_method \"q\".to_sym { }\n", "raise ArgumentError", "skip"},
{"overwrite File", "File = 1\n", "- pub=[] priv=[]", "skip"},
{"undefined", "X = Nope\n", "raise NameError", "skip"},
{"call args", "X = foo 1\n", "raise NoMethodError", "skip"},
{"hash each", "{ a: 1 }.each do |k|\n define_method(k) {}\nend\n", "raise TypeError", "skip"},
{"call plus", "def self.s\n 'a'\nend\nX = s + s\n", "\"aa\" pub=[] priv=[]", "\"aa\" pub=[]"},
{"if defined false", "X = 1 if defined?(Nope)\n", "- pub=[] priv=[]", "- pub=[]"},
{"unless defined true", "X = 1 unless defined?(String)\n", "- pub=[] priv=[]", "- pub=[]"},
{"parent const", "X = pp\n\n", "[:x] pub=[] priv=[]", "[:x] pub=[]"},
{"and", "X = 1 && 2\n", "2 pub=[] priv=[]", "2 pub=[]"},
{"and nil", "X = nil && 1\n", "nil pub=[] priv=[]", "nil pub=[]"},
{"or", "X = false || :b\n", ":b pub=[] priv=[]", ":b pub=[]"},
{"or first", "X = 1 || nil\n", "1 pub=[] priv=[]", "1 pub=[]"},
{"or and precedence", "X = 1 || nil && 2\n", "1 pub=[] priv=[]", "1 pub=[]"},
{"not", "X = !nil\n", "true pub=[] priv=[]", "true pub=[]"},
{"not binds tight", "X = !1 == false\n", "true pub=[] priv=[]", "true pub=[]"},
{"respond_to", "X = :a.respond_to?(:intern)\n", "true pub=[] priv=[]", "true pub=[]"},
{"respond_to unknown", "X = 'a'.respond_to?(:nope)\n", "false pub=[] priv=[]", "skip"},
{"is_a", "X = :a.is_a?(Symbol) && !'a'.is_a?(Symbol)\n", "true pub=[] priv=[]", "true pub=[]"},
{"kind_of Object", "X = [].kind_of?(Object)\n", "true pub=[] priv=[]", "true pub=[]"},
{"is_a unmodelled", "X = nil.is_a?(Comparable)\n", "false pub=[] priv=[]", "skip"},
{"intern", "X = 'a'.intern\n", ":a pub=[] priv=[]", ":a pub=[]"},
{"hash new", "X = Hash.new { |h, k| h[k] = [] }\n", "{} pub=[] priv=[]", "{} pub=[]"},
{"loop reassign param", "%w[a].each do |p|\n p = 'z' if p == 'a'\n define_method(p) {}\nend\n", "- pub=[:z] priv=[]", "- pub=[:z]"},
{"loop reassign skipped", "%i[a b].each do |p|\n p = p.intern if p.respond_to?(:intern) && !p.is_a?(Symbol)\n define_method(p) {}\n define_method(\"#{p}=\") {}\nend\n", "- pub=[:a, :a=, :b, :b=] priv=[]", "- pub=[:a, :a=, :b, :b=]"},
{"loop assign other", "[:a].each do |p|\n q = p\n define_method(q) {}\nend\n", "- pub=[:a] priv=[]", "skip"},
{"regex interp", "R = %r{b}\nX = \"#{%r{a#{R}c}}\"\n", "\"(?-mix:a(?-mix:b)c)\" pub=[] priv=[]", "\"(?-mix:a(?-mix:b)c)\" pub=[]"},
{"regex interp look-behind", "R = %r{.{1,3}(?<!~|bak)}\nX = \"#{%r{^if[a-z_]+(?::#{R})?$}}\"\n", "\"(?-mix:^if[a-z_]+(?::(?-mix:.{1,3}(?<!~|bak)))?$)\" pub=[] priv=[]", "\"(?-mix:^if[a-z_]+(?::(?-mix:.{1,3}(?<!~|bak)))?$)\" pub=[]"},
{"regex interp invalid", "P = '+'\nX = %r{(?<!a#{P})}\n", "raise RegexpError", "skip"},
{"regex interp x flag", "X = %r{a#{'b'}}x\n", "/ab/x pub=[] priv=[]", "skip"},
{"regex interp string", "X = \"#{%r{a#{'[b-c]'}}}\"\n", "\"(?-mix:a[b-c])\" pub=[] priv=[]", "\"(?-mix:a[b-c])\" pub=[]"},
}
func TestEvaluator(t *testing.T) {
for _, c := range evalCases {
t.Run(c.name, func(t *testing.T) {
ctx, consts, _, err := evalProvider(c.src, strings.HasPrefix(c.name, "parent"))
got := "skip"
if err == nil {
x, ok := consts["X"]
got = "-"
if ok {
got = inspect(x)
}
var pub []string
for m := range ctx.methods {
if ctx.hidden[m] {
continue
}
pub = append(pub, ":"+m)
}
slices.Sort(pub)
got += " pub=[" + strings.Join(pub, ", ") + "]"
}
if got != c.want {
t.Fatalf("got %s (%v), want %s; ruby gives %s", got, err, c.want, c.ruby)
}
})
}
}
// In Ruby, File = FileCollection inside module Q makes class Sub < File a subclass of FileCollection.
func TestEvaluatorAlias(t *testing.T) {
_, _, w, err := evalProvider("", false)
if err != nil {
t.Fatal(err)
}
if w.kind["PuppetX::Q::File"] != kClass || w.sup["PuppetX::Q::Sub"] != "PuppetX::Q::File" {
t.Fatalf("alias File = FileCollection not usable as a superclass: %c %q", w.kind["PuppetX::Q::File"], w.sup["PuppetX::Q::Sub"])
}
}
func TestEvaluatorUnknownParent(t *testing.T) {
w := newWorld(nil)
w.typ = &rtype{name: "t"}
w.types["t"] = &loadedType{t: w.typ}
_, err := providerFile(libFile{mod: "m", rel: "puppet/provider/t/x.rb", src: "Puppet::Type.type(:t).provide(:x, parent: :y) do\n X = tp\nend\n"}, "t", false, w)
if err == nil {
t.Fatal("singleton method of an unmodelled parent provider evaluated")
}
}
// Each body costs more than the evaluator budgets allow; w10k must stop with a budget error, quickly.
func TestEvaluatorBudgets(t *testing.T) {
var b strings.Builder
b.WriteString("A0 = '" + strings.Repeat("x", 1024) + "'\n")
for i := 1; i <= 40; i++ {
b.WriteString("A" + strconv.Itoa(i) + " = A" + strconv.Itoa(i-1) + " + A" + strconv.Itoa(i-1) + "\n")
}
doubling := b.String()
fan := func(leaf string) string {
var b strings.Builder
b.WriteString("def self.a0\n " + leaf + "\nend\n")
for i := 1; i <= 6; i++ {
b.WriteString("def self.a" + strconv.Itoa(i) + "\n a" + strconv.Itoa(i-1) + strings.Repeat(" + a"+strconv.Itoa(i-1), 199) + "\nend\n")
}
return b.String() + "X = a6\n"
}
loop := "[" + strings.Repeat(":a, ", 3000) + ":a].each do |x|\n" + strings.Repeat(" next if x == :b\n", 3000) + "end\n"
for name, src := range map[string]string{"doubling constants": doubling, "fanned-out calls": fan("''"), "fanned-out strings": fan("'" + strings.Repeat("x", 1024) + "'"), "long loop": loop} {
t.Run(name, func(t *testing.T) {
start := time.Now()
_, _, _, err := evalProvider(src, false)
if !errors.Is(err, errLimit) {
t.Fatalf("got %v, want a budget error", err)
}
if d := time.Since(start); d > 30*time.Second {
t.Fatalf("budget took %v", d)
}
})
}
}
const (
fmInitvars = " super\n @mapped = Hash.new { |h, k| h[k] = {} }\n @filetype = :flat\n"
fmHook = " klass.extend PuppetX::Fm::ClassMethods\n klass.mk_property_methods\n klass.initvars\n"
)
// fmModule is a filemapper 4.0.0-style mixin whose included hook extends ClassMethods, defines property methods and
// runs initvars; extra adds ClassMethods methods.
func fmModule(extra, initvars, hook string) string {
return "module PuppetX; end\nmodule PuppetX::Fm\n def create; end\n def flush; end\n def self.included(klass)\n" + hook +
" end\n module ClassMethods\n attr_accessor :filetype\n def initvars\n" + initvars + " end\n" + extra +
" def mk_property_methods\n resource_type.validproperties.each do |attr|\n" +
" attr = attr.intern if attr.respond_to?(:intern) && !attr.is_a?(Symbol)\n define_method(attr) do\n end\n" +
" define_method(\"#{attr}=\") do |val|\n end\n end\n end\n end\nend\n"
}
// Each env includes fmModule or a variant. openvox 9.3.0 writes the provider doc in want; w10k must write the same,
// or skip where want is "".
func TestIncludedHook(t *testing.T) {
const typ = "Puppet::Type.newtype(:t) do\n feature :fprop, 'p', methods: [:a, :a=]\n feature :fmix, 'm', methods: [:flush]\n" +
" newparam(:name)\n newproperty(:a)\n newproperty(:b)\nend\n"
iv, hook, mixin := fmInitvars, fmHook, fmModule
prov := func(pre, opts, body string) string {
return "require 'puppet_x/m/fm'\n" + pre + "Puppet::Type.type(:t).provide(:x" + opts + ") do\n" + body + "end\n"
}
const feats = " # * Supported features: `fmix`, `fprop`.\n"
for name, c := range map[string]struct{ mixin, typ, prov, want string }{
"wipes earlier DSL": {mixin("", iv, hook), typ, prov("", "", " defaultfor osfamily: :x\n commands zz: 'zz'\n include PuppetX::Fm\n desc 'd'\n defaultfor osfamily: :y\n"),
" # : d\n # \n # * Default for `osfamily` == `y`.\n" + feats},
"private before include": {mixin("", iv, hook), typ, prov("", "", " private\n include PuppetX::Fm\n"), " # : * Supported features: `fmix`, `fprop`.\n"},
"initvars after include": {mixin("", iv, hook), typ, prov("", "", " include PuppetX::Fm\n defaultfor osfamily: :x\n initvars\n defaultfor osfamily: :y\n"),
" # : * Default for `osfamily` == `y`.\n" + feats},
"own singleton wins": {mixin("", iv, hook), typ, prov("", "", " def self.mk_property_methods\n end\n include PuppetX::Fm\n"), " # : * Supported features: `fmix`.\n"},
"commands after include": {mixin("", iv, hook), typ, prov("", "", " include PuppetX::Fm\n commands zz: 'zz'\n"), " # : * Required binaries: `zz`.\n" + feats},
"hook shadowed": {mixin(" def postinit\n end\n", iv, hook), typ, prov("", "", " include PuppetX::Fm\n"), ""},
"initvars without super": {mixin("", " @defaults = [{ osfamily: :q }]\n", hook), typ, prov("", "", " include PuppetX::Fm\n"), ""},
"initvars sets doc": {mixin("", " super\n @doc = 'z'\n", hook), typ, prov("", "", " include PuppetX::Fm\n"), ""},
"hook sends": {mixin("", iv, " klass.send(:initvars)\n"), typ, prov("", "", " include PuppetX::Fm\n"), ""},
"parsedfile filetype": {mixin("", iv, hook), typ, prov("require 'puppet/provider/parsedfile'\n", ", parent: Puppet::Provider::ParsedFile", " include PuppetX::Fm\n"), ""},
"type includes hook": {mixin("", iv, hook), "require 'puppet_x/m/fm'\n" + strings.Replace(typ, " newparam(:name)\n", " include PuppetX::Fm\n newparam(:name)\n", 1),
prov("", "", ""), ""},
} {
t.Run(name, func(t *testing.T) {
env := fidelityEnv(t, map[string]string{"m/lib/puppet_x/m/fm.rb": c.mixin, "m/lib/puppet/type/t.rb": c.typ, "m/lib/puppet/provider/t/x.rb": c.prov})
b, err := os.ReadFile(filepath.Join(env, OutDir, "t.pp"))
want := " # x\n" + c.want + " Puppet::Resource::Param(Any, 'provider')"
switch {
case c.want == "" && err == nil:
t.Fatalf("t.pp written; w10k cannot prove it:\n%s", b)
case c.want != "" && !strings.Contains(string(b), want):
t.Fatalf("t.pp lacks %q: %v\n%s", want, err, b)
}
})
}
}
// Ruby 3.3's Regexp.new compiles each source when ruby is true; onigCheck may accept only those, and declines the
// forms it does not model.
func TestOnigCheck(t *testing.T) {
for _, c := range []struct {
src string
ruby, want bool
}{
{`\Aifcfg-[a-z]+[a-z_\d]+(?::(?-mix:.{1,12}(?<!~|\.bak|\.old|\.orig|\.rpmnew|\.rpmorig|\.rpmsave))|\.(?-mix:[1-3]?\d{1,3}|40[0-8]\d|409[0-5]))?\Z`, true, true},
{`a|`, true, true},
{`()(?:)`, true, true},
{`[-a][a-]`, true, true},
{`x{2}?y*+z??`, true, true},
{`(?i:a)(?m-i:b)`, true, true},
{`(?<=ab|c)(?<!\d{2}x)`, true, true},
{`[^\]a\d]`, true, true},
{`a{,3}b{2,}`, true, true},
{`é.`, true, true},
{`(?=a)(?!b)`, true, true},
{`^\bx\B$`, true, true},
{`(?<!a+)`, false, false},
{`(?<=a|b*)`, false, false},
{`[z-a]`, false, false},
{`a{3,2}`, false, false},
{`(a`, false, false},
{`a)`, false, false},
{`*a`, false, false},
{`a{2}{3}`, true, false},
{`[]`, false, false},
{`a\`, false, false},
{`(?<=(a))`, true, false},
{`(?<=^a)`, true, false},
{`(?<n>a)`, true, false},
{`\x41`, true, false},
{`(?i:(?<=ss))`, true, false},
{`a{1,2}+`, true, false},
{`[[:alpha:]]`, true, false},
{`(?x:a b)`, true, false},
{`a{`, true, false},
{`a]`, true, false},
{`(?#c)`, true, false},
{`[a-\d]`, false, false},
{`[\d-z]`, false, false},
} {
if err := onigCheck(c.src, false); (err == nil) != c.want || err == nil && !c.ruby {
t.Errorf("%s: got %v, want accepted=%v (ruby compiles it: %v)", c.src, err, c.want, c.ruby)
}
}
}
// Each case is Ruby 3.3's File.join of parts.
func TestFileJoin(t *testing.T) {
for _, c := range []struct {
parts []string
want string
}{
{[]string{"a", ""}, "a/"}, {[]string{"", "a"}, "/a"}, {[]string{"/", "b"}, "/b"}, {[]string{"a//", "b"}, "a//b"},
{[]string{"a/", "/b"}, "a/b"}, {[]string{"//", "//b"}, "//b"}, {[]string{"a", "/"}, "a/"}, {[]string{"/", "/"}, "/"},
{[]string{"", "/"}, "/"}, {[]string{"a", "", " b"}, "a/ b"}, {[]string{"x", "", ""}, "x/"}, {nil, ""},
} {
if got := fileJoin(c.parts); got != c.want {
t.Errorf("fileJoin(%q) = %q, want %q", c.parts, got, c.want)
}
}
parts := slices.Repeat([]string{"/a"}, 1<<12)
if n := testing.AllocsPerRun(1, func() { _ = fileJoin(parts) }); n > 64 {
t.Errorf("fileJoin of %d rooted parts allocates %v times", len(parts), n)
}
}
// Each case is Ruby 3.3's Regexp#names, or an error where Ruby raises or w10k does not model the name.
func TestOnigNames(t *testing.T) {
for _, c := range []struct{ src, flags, want string }{
{`(?<a>x)\(?<b>y\)[(?<c>)](?<a>z)`, "", "a"}, {`(?#c(?<a>x)(?<b>y)`, "", "b"}, {`(?#c\)(?<a>x)`, "", ""},
{"(?x) # (?<n>c)\n(?<m>d)", "", "m"}, {"(?x:a # (?<n>c)\n)(?<m>d) # (?<o>e)", "", "m o"}, {"(?x:a)# (?<n>c)\n", "", "n"},
{"(?x)[#](?<n>c)", "", "n"}, {`(?x)\#(?<n>c)`, "", "n"}, {`[]](?<a>x)`, "", "a"}, {`[^]](?<a>x)`, "", "a"},
{`[a[b](?<c>x)]](?<a>x)`, "", "a"}, {`[[:alpha:]](?<a>x)`, "", "a"}, {`[a&&[^b]](?<a>x)`, "", "a"}, {`[\]](?<a>x)`, "", "a"},
{`(?<=a)(?<!b)(?<c>d)`, "", "c"}, {`(?'q'x)(?<r>y)`, "", "q r"}, {`(?i)(?<a>x)`, "", "a"}, {`(?-x:#(?<a>x))`, "", "a"},
{`(?<a>x)\k<a>`, "", "a"}, {`(?<a_1>x)(?<_b>y)`, "", "a_1 _b"}, {`(?<a>x)(?<b>(?<c>y))`, "", "a b c"}, {`(?~ab)(?<a>x)`, "", "a"},
{`(?>a)(?<a>x)`, "", "a"}, {`\\(?<a>x)`, "", "a"}, {`\Q(?<a>x)`, "", "a"}, {"(?x)(?<a>x)#)\n(?<b>y)", "", "a b"},
{"(?x)a(?-x)#(?<b>y)", "", "b"}, {"(?x:(?-x)#(?<a>x))#(?<b>y)", "", "a b"}, {`(?<b>x)(?<a>y)(?<b>z)`, "", "b a"},
{"(?<a>x) # (?<b>y)\n (?<c>z)", "x", "a c"}, {`(x)`, "", ""},
{`\k<a>(?<a>x)`, "", "error"}, {`\g<a>(?<a>x)`, "", "error"}, {`(?<1a>x)`, "", "error"}, {`(?<a-b>x)`, "", "error"},
{`(?<>x)`, "", "error"}, {`(?<a>x`, "", "error"}, {`(?<a>x)\k<b>(?<b>y)`, "", "error"}, {`(?<a>x)\k<1>`, "", "error"},
{`(?<a>x)\k<a+0>`, "", "error"}, {`(?<é>x)`, "", "error"}, {`a)`, "", "error"}, {`[a`, "", "error"}, {`(?#a`, "", "error"},
} {
got, err := onigNames(regex{c.src, c.flags})
if g := strings.Join(got, " "); err != nil && c.want != "error" || err == nil && g != c.want {
t.Errorf("onigNames(%q) = %q %v, want %q", c.src, g, err, c.want)
}
}
}
+390
View File
@@ -0,0 +1,390 @@
package gentypes
import (
"maps"
"os"
"path/filepath"
"strings"
"testing"
)
const rsapiHead = "require 'puppet/resource_api'\nPuppet::ResourceApi.register_type(\n name: 't',\n desc: 'd',\n"
func rsapi(extra, attrs string) string {
return rsapiHead + extra + " attributes: {\n name: { type: 'String', desc: 'n', behaviour: :namevar },\n" + attrs + " },\n)\n"
}
const (
classic = "Puppet::Type.newtype(:t) do\n newparam(:name)\nend\n"
mixin = "module PuppetX\n module A\n module Mix\n def exists?; end\n def create; end\n def destroy; end\n end\n end\nend\n"
empty = "module PuppetX\n module A\n module Mix\n end\n end\nend\n"
)
func provider(body string) map[string]string {
return map[string]string{"m/lib/puppet/type/t.rb": classic, "m/lib/puppet/provider/t/x.rb": body}
}
func featureType(features, body string) map[string]string {
return map[string]string{"m/lib/puppet/type/t.rb": "Puppet::Type.newtype(:t) do\n" + features + " newparam(:name)\nend\n",
"m/lib/puppet/provider/t/x.rb": "Puppet::Type.type(:t).provide(:x) do\n" + body + "end\n"}
}
func fidelityEnv(t *testing.T, files map[string]string) string {
t.Helper()
env := t.TempDir()
for p, body := range files {
writeFile(t, filepath.Join(env, "modules", p), body)
}
if _, err := Generate(env); err != nil {
t.Fatal(err)
}
return env
}
// Each env makes openvox 9.3.0 `puppet generate types` fail to load or document type t, so it writes no t.pp.
func TestFidelityPuppetWritesNothing(t *testing.T) {
cases := map[string]map[string]string{
"provider requires missing gem": provider("require 'no_such_gem_xyz'\nPuppet::Type.type(:t).provide(:x) do\nend\n"),
"provider raises": provider("raise 'boom'\nPuppet::Type.type(:t).provide(:x) do\nend\n"),
"provider undefined const": provider("Puppet::Type.type(:t).provide(:x) do\nend\nFoo::Bar.baz\n"),
"provider undefined parent": provider("Puppet::Type.type(:t).provide(:x, parent: Puppet::Provider::Nope) do\nend\n"),
"provider block includes undefined": provider("Puppet::Type.type(:t).provide(:x) do\n include PuppetX::Nope\nend\n"),
"provider confine loads module file": {"m/lib/puppet/type/t.rb": classic, "m/lib/puppet/confine/mything.rb": "raise 'mine'\n", "m/lib/puppet/provider/t/x.rb": "Puppet::Type.type(:t).provide(:x) do\n confine mything: true\nend\n"},
"provider defaultfor non-collection": provider("Puppet::Type.type(:t).provide(:x) do\n defaultfor 1\nend\n"),
"provider dochook": provider("Puppet::Type.type(:t).provide(:x) do\n def self.dochook_x\n raise 'x'\n end\nend\n"),
"provider sets @doc": provider("Puppet::Type.type(:t).provide(:x) do\n @doc = 1\nend\n"),
"provider sets $stdout": provider("Puppet::Type.type(:t).provide(:x) do\n $stdout = 1\nend\n"),
"provider aliases undefined method": provider("Puppet::Type.type(:t).provide(:x) do\n alias_method :a, :nope\nend\n"),
"File.join of a symbol array": provider("require File.join(File.dirname(__FILE__), %i[x])\nPuppet::Type.type(:t).provide(:x) do\nend\n"),
"provider superclass mismatch": provider("class QHelper < StandardError\nend\nclass QHelper < Puppet::Error\nend\nPuppet::Type.type(:t).provide(:x) do\nend\n"),
"library redefines a Puppet::Type method": {"m/lib/puppet_x/m/patch.rb": "class Puppet::Type\n def self.newparam(*)\n raise 'patched'\n end\nend\n",
"m/lib/puppet/type/t.rb": "require 'puppet_x/m/patch'\n" + classic},
"provider commands before initvars": provider("class Puppet::Provider::Q < Puppet::Provider\n commands a: 'a'\nend\nPuppet::Type.type(:t).provide(:x, parent: Puppet::Provider::Q) do\nend\n"),
"provider defaultfor before initvars": provider("class Puppet::Provider::Q < Puppet::Provider\n defaultfor a: 'a'\nend\nPuppet::Type.type(:t).provide(:x, parent: Puppet::Provider::Q) do\nend\n"),
"feature repeated": featureType(" feature :f, 'a'\n feature :f, 'b'\n", ""),
"feature unknown option": featureType(" feature :f, 'a', bogus: 1\n", ""),
"provider record_line bad keyword": provider("require 'puppet/provider/parsedfile'\nPuppet::Type.type(:t).provide(:x, parent: Puppet::Provider::ParsedFile) do\n record_line :x, fields: ['name'], bogus: 1\nend\n"),
"rsapi reserved tag": {"m/lib/puppet/type/t.rb": rsapi("", " tag: { type: 'String', desc: 'x' },\n")},
"rsapi reserved provider": {"m/lib/puppet/type/t.rb": rsapi("", " provider: { type: 'String', desc: 'x', behaviour: :parameter },\n")},
"rsapi desc and docs": {"m/lib/puppet/type/t.rb": rsapi(" docs: 'e',\n", "")},
"rsapi ensure not enum": {"m/lib/puppet/type/t.rb": rsapi("", " ensure: { type: 'String', desc: 'x' },\n")},
"rsapi reserved insync trigger": {"m/lib/puppet/type/t.rb": rsapi("", " rsapi_custom_insync_trigger: { type: 'String', desc: 'x' },\n")},
"rsapi Float exponent plus": {"m/lib/puppet/type/t.rb": rsapi("", " a: { type: 'Float[1.0e+5]', desc: 'x' },\n")},
"rsapi Float overflow": {"m/lib/puppet/type/t.rb": rsapi("", " a: { type: 'Float[1e400]', desc: 'x' },\n")},
"rsapi Float 0e0": {"m/lib/puppet/type/t.rb": rsapi("", " a: { type: 'Float[0e0]', desc: 'x' },\n")},
"rsapi Float zero mantissa exponent": {"m/lib/puppet/type/t.rb": rsapi("", " a: { type: 'Float[0.0e5]', desc: 'x' },\n")},
"safe_insync? in a Property subclass": {"m/lib/puppet/type/t.rb": "class QS < Puppet::Property\n def safe_insync?(is); end\nend\n" + classic},
"newvalues in a parent class body": {"m/lib/puppet/type/t.rb": "class QD < Puppet::Property\n newvalues(:x)\nend\nPuppet::Type.newtype(:t) do\n newparam(:name)\n newproperty(:a, parent: QD)\nend\n"},
"parent defined after use": {"m/lib/puppet/type/t.rb": "Puppet::Type.newtype(:t) do\n newparam(:name)\n newproperty(:a, parent: QL)\nend\nclass QL < Puppet::Property\nend\n"},
"parent not a Property": {"m/lib/puppet/type/t.rb": "class QP\nend\nPuppet::Type.newtype(:t) do\n newparam(:name)\n newproperty(:a, parent: QP)\nend\n"},
"require resolves to puppet core first": {
"m/lib/puppet/util/execution.rb": "module PuppetX\n module Sh\n end\nend\n",
"m/lib/puppet_x/sh.rb": "module PuppetX\n module Sh\n end\nend\n",
"m/lib/puppet/type/t.rb": "require 'puppet/util/execution'\nPuppet::Type.newtype(:t) do\n include PuppetX::Sh\n newparam(:name)\nend\n",
},
}
for name, files := range cases {
t.Run(name, func(t *testing.T) {
if exists(filepath.Join(fidelityEnv(t, files), OutDir, "t.pp")) {
t.Fatal("t.pp written; real puppet writes none")
}
})
}
}
// Each env makes w10k's t.pp differ from real puppet's unless it skips (verified with openvox 9.3.0).
func TestFidelityNoWrongOutput(t *testing.T) {
cases := map[string]struct {
files map[string]string
bad string
}{
"empty Variant is flattened": {map[string]string{"m/lib/puppet/type/t.rb": rsapi("", " a: { type: 'Variant[Variant, String]', desc: 'x' },\n")}, "Param(Any, 'a')"},
"include reads a file nobody required": {map[string]string{
"m/lib/puppet_x/a/helpers.rb": empty,
"m/lib/puppet_x/a/mix.rb": mixin,
"m/lib/puppet/type/t.rb": "require 'puppet_x/a/helpers'\nPuppet::Type.newtype(:t) do\n include PuppetX::A::Mix\n newparam(:name)\nend\n",
}, "'ensure'"},
"include unions every module's copy": {map[string]string{
"a/lib/puppet_x/a/mix.rb": mixin,
"b/lib/puppet_x/a/mix.rb": empty,
"a/lib/puppet/type/t.rb": "require 'puppet_x/a/mix'\nPuppet::Type.newtype(:t) do\n include PuppetX::A::Mix\n newparam(:name)\nend\n",
}, "'ensure'"},
"parent defines a class method": {map[string]string{
"m/lib/puppet/type/t.rb": "class QN < Puppet::Property\n def self.isnamevar?\n true\n end\nend\nPuppet::Type.newtype(:t) do\n newparam(:name)\n newproperty(:a, parent: QN)\nend\n",
}, "Param(Any, 'a')"},
"parent reopened with a class method": {map[string]string{
"m/lib/puppet/type/t.rb": "class QN < Puppet::Property\nend\nPuppet::Type.newtype(:t) do\n newparam(:name)\n newproperty(:a, parent: QN)\nend\nclass QN\n def self.isnamevar?\n true\n end\nend\n",
}, "Param(Any, 'a')"},
"type class reopened": {map[string]string{
"m/lib/puppet/type/t.rb": classic + "class Puppet::Type::T\n def self.title_patterns\n [[/(x)/, [[:name]]]]\n end\nend\n",
}, "'name'"},
"provider class reopened": {map[string]string{
"m/lib/puppet/type/t.rb": classic + "class Puppet::Type::T::ProviderX\n @doc = 'patched'\nend\n",
"m/lib/puppet/provider/t/x.rb": "Puppet::Type.type(:t).provide(:x) do\n desc 'x'\nend\n",
}, "# : x\n"},
"constant lexical scope": {map[string]string{
"m/lib/puppet/type/t.rb": "VALS = 'a'\nmodule Puppet\n VALS = 'b'\nend\nPuppet::Type.newtype(:t) do\n newparam(:name)\n newproperty(:p) do\n newvalues(VALS)\n end\nend\n",
}, "Enum['b']"},
}
for name, c := range cases {
t.Run(name, func(t *testing.T) {
b, err := os.ReadFile(filepath.Join(fidelityEnv(t, c.files), OutDir, "t.pp"))
if err == nil && strings.Contains(string(b), c.bad) {
t.Fatalf("t.pp contains %s; real puppet's does not", c.bad)
}
})
}
}
// Each env loads in openvox 9.3.0 and w10k must write the same t.pp.
func TestFidelityProvidersThatLoad(t *testing.T) {
cases := map[string]map[string]string{
"literal DSL, ENV and constants": provider("Puppet::Type.type(:t).provide(:x) do\n" +
" ENV['W10K_A'] = \"#{ENV.fetch('PATH', nil)}:/x\"\n ENV['W10K_B'] = [ENV.fetch('W10K_NONE', nil), '/a'].join(':')\n" +
" defaultfor ['os.name' => :x, 'os.family' => :y]\n confine 'os.family': :redhat, exists: '/', feature: :posix\n" +
" commands a: 'a', 'b': 'b'\n has_features :f1, :f2\n mk_resource_methods\n X = %r{^a$}.freeze\n" +
" H = File.expand_path('../../x.py', __dir__)\n @things = { a: 1 }\n $w10k_g = [1]\n" +
" attr_accessor :thing\n alias_method :thing2, :thing\n private :thing2\nend\n"),
"guarded missing require": provider("begin\n require 'no_such_lib_w10k'\nrescue LoadError\nend\nPuppet::Type.type(:t).provide(:x) do\nend\n"),
"class reopened with its superclass": provider("class QHelper2 < Puppet::Error\nend\nclass QHelper2 < Puppet::Error\n def x; end\nend\n" +
"Puppet::Type.type(:t).provide(:x) do\nend\n"),
"parsed file records": provider("require 'puppet/provider/parsedfile'\nPuppet::Type.type(:t).provide(:x, parent: Puppet::Provider::ParsedFile, default_target: '/tmp/x') do\n" +
" text_line :blank, match: %r{^\\s*$}\n record_line :x, fields: ['name'], optional: ['name'], to_line: proc { |h| h[:name] }\n" +
" record_line :y, fields: %w[name], block_eval: :instance do\n def to_line(h)\n h[:name]\n end\n end\nend\n"),
"trailing-dot chain and File.join arrays": {"m/lib/puppet/type/t.rb": classic,
"m/lib/puppet/provider/h.rb": "class Puppet::Provider::H < Puppet::Provider\n initvars\n commands h: 'h'\nend\n",
"m/lib/puppet/provider/t/x.rb": "require File.expand_path(File.join(File.dirname(__FILE__), %w[..], ['x', [], '/../h']))\nPuppet::Type.\n # c\n type(:t).\n\n" +
" provide(:x, parent: Puppet::Provider::H) do\n defaultfor osfamily: %i[a b]\nend\n"},
"helper required by path": {"m/lib/puppet/type/t.rb": classic,
"m/lib/puppet/provider/h.rb": "require 'json'\nclass Puppet::Provider::H < Puppet::Provider\n initvars\n commands a: 'a'\nend\n",
"m/lib/puppet/provider/t/x.rb": "require File.expand_path(File.join(File.dirname(__FILE__), '..', 'h'))\nPuppet::Type.type(:t).provide(:x, parent: Puppet::Provider::H) do\nend\n"},
}
for name, files := range cases {
t.Run(name, func(t *testing.T) {
b, err := os.ReadFile(filepath.Join(fidelityEnv(t, files), OutDir, "t.pp"))
if err != nil || !strings.Contains(string(b), "Puppet::Resource::Param(Any, 'provider')") {
t.Fatalf("t.pp not generated: %v\n%s", err, b)
}
})
}
}
// Each type file defines classes at its top level and loads in openvox 9.3.0, which writes want into t.pp.
func TestFidelityUserClasses(t *testing.T) {
for name, c := range map[string]struct{ src, want string }{
"nested in reopened Puppet::Property": {"module Puppet\n class Property\n class QV < Property\n def insync?(is)\n true\n end\n end\n" +
" class QM < QV\n end\n end\n Type.newtype(:t) do\n newparam(:name)\n newproperty(:a, array_matching: :all, parent: Puppet::Property::QM) do\n" +
" desc 'a'\n end\n end\nend\n", " # a\n Puppet::Resource::Param(Any, 'a')\n"},
"user subclass of Parameter::Boolean": {"require 'puppet/parameter/boolean'\nclass QB < Puppet::Parameter::Boolean\n def x; end\nend\n" +
"Puppet::Type.newtype(:t) do\n newparam(:name)\n newparam(:b, parent: QB)\nend\n", "Puppet::Resource::Param(Variant[Boolean, Enum['true', 'false', 'yes', 'no']], 'b')"},
} {
t.Run(name, func(t *testing.T) {
b, err := os.ReadFile(filepath.Join(fidelityEnv(t, map[string]string{"m/lib/puppet/type/t.rb": c.src}), OutDir, "t.pp"))
if err != nil || !strings.Contains(string(b), c.want) {
t.Fatalf("t.pp lacks %q: %v\n%s", c.want, err, b)
}
})
}
}
// With toml declared, each env either loads in openvox 9.3.0 with toml 0.3.0 installed or skips because what loads
// depends on whether another type activated the gem first.
func TestGemToml(t *testing.T) {
typ := func(pre string) string { return pre + classic }
cases := map[string]struct {
files map[string]string
want bool
}{
"require loads the gem": {map[string]string{"m/lib/puppet/type/t.rb": typ("require 'toml'\n")}, true},
"guarded require loads the gem": {map[string]string{"m/lib/puppet/type/t.rb": typ("begin\n require 'toml'\nrescue LoadError\nend\n")}, true},
"library subclasses a gem class": {map[string]string{"m/lib/puppet_x/m/k.rb": "module PuppetX\n class K < TOML::Key\n end\nend\n",
"m/lib/puppet/type/t.rb": typ("require 'toml'\nrequire 'puppet_x/m/k'\n")}, true},
"module copy competes": {map[string]string{"m/lib/toml.rb": "", "m/lib/puppet/type/t.rb": typ("require 'toml'\n")}, false},
"unmodelled gem file": {map[string]string{"m/lib/puppet/type/t.rb": typ("require 'toml/version'\n")}, false},
"dependency entry": {map[string]string{"m/lib/puppet/type/t.rb": typ("require 'parslet'\n")}, false},
"library opens gem module": {map[string]string{"m/lib/puppet_x/m/t.rb": "module TOML\nend\n", "m/lib/puppet/type/t.rb": typ("require 'puppet_x/m/t'\n")}, false},
"library opens gem module after require": {map[string]string{"m/lib/puppet_x/m/t.rb": "module Parslet\nend\n",
"m/lib/puppet/type/t.rb": typ("require 'toml'\nrequire 'puppet_x/m/t'\n")}, false},
}
for name, c := range cases {
t.Run(name, func(t *testing.T) {
env := t.TempDir()
for p, body := range c.files {
writeFile(t, filepath.Join(env, "modules", p), body)
}
st, err := GenerateGems(env, []string{"toml"})
if err != nil {
t.Fatal(err)
}
if got := exists(filepath.Join(env, OutDir, "t.pp")); got != c.want {
t.Fatalf("t.pp written = %v, want %v (skipped %v)", got, c.want, st.Skipped)
}
})
}
if _, err := GenerateGems(t.TempDir(), []string{"nope"}); err == nil {
t.Fatal("unknown gem accepted")
}
}
// Each env loads in openvox 9.3.0; w10k writes its provider doc, or skips where it cannot prove the doc.
func TestFidelityProviderDocs(t *testing.T) {
for name, c := range map[string]struct {
files map[string]string
doc string
}{
"string feature redefined": {featureType(" feature 'f', 'a'\n feature 'f', 'b', methods: [:m]\n", " def m; end\n"), " # : * Supported features: `f`.\n"},
"feature method shadowed": {featureType(" feature :f, 'a'\n", " def self.f?\n true\n end\n"), ""},
"feature method from Provider": {featureType(" feature :f, 'a', methods: [:execute]\n", ""), ""},
"feature method command and def": {featureType(" feature :f, 'a', methods: [:m]\n", " commands m: 'm'\n def m; end\n"), ""},
"defaultfor operator symbol": {provider("Puppet::Type.type(:t).provide(:x) do\n defaultfor [{ :+ => 1 }]\nend\n"), ""},
"defaultfor non-ASCII string": {provider("Puppet::Type.type(:t).provide(:x) do\n defaultfor ['é' => 1]\nend\n"), ""},
"defaultfor inline-option regexp": {provider("Puppet::Type.type(:t).provide(:x) do\n defaultfor a: /(?i:x)/\nend\n"), ""},
} {
t.Run(name, func(t *testing.T) {
b, err := os.ReadFile(filepath.Join(fidelityEnv(t, c.files), OutDir, "t.pp"))
switch {
case c.doc == "" && err == nil:
t.Fatalf("t.pp written; w10k cannot prove its provider doc:\n%s", b)
case c.doc != "" && !strings.Contains(string(b), c.doc):
t.Fatalf("t.pp lacks %q: %v\n%s", c.doc, err, b)
}
})
}
}
func typeWith(name, extra string) string {
return "Puppet::Type.newtype(:" + name + ") do\n newparam(:name) { isnamevar }\n" + extra + "end\n"
}
// Puppet::Type.type(:u) loads u with its providers; openvox 9.3.0 writes t.pp with want.
func TestFidelityCrossType(t *testing.T) {
env := fidelityEnv(t, map[string]string{
"m/lib/puppet/type/t.rb": typeWith("t", " newparam(:cluster)\n def self.title_patterns\n c = Regexp.new(/[^\\/]+/)\n n = Regexp.new('a/b')\n i = Regexp.new(/x/i)\n"+
" [[/^(#{c})\\/(#{n})$/, [[:cluster], [:name]]], [/^(#{i})$/, [[:name]]]]\n end\n"),
"m/lib/puppet/type/u.rb": typeWith("u", ""),
"m/lib/puppet/provider/u/base.rb": "Puppet::Type.type(:u).provide(:base) do\n desc 'base doc'\n commands bb: 'bb'\nend\n",
"m/lib/puppet/provider/t/a.rb": "Puppet::Type.type(:t).provide(:a, parent: Puppet::Type.type(:u).provider(:base)) do\nend\n",
"m/lib/puppet/provider/t/b.rb": "Puppet::Type.type(:t).provide(:b, parent: Puppet::Type.type(:u).provider(:missing)) do\n desc 'b'\nend\n",
})
want := " # a\n # : \n # \n # b\n # : b\n Puppet::Resource::Param(Any, 'provider')\n ],\n {\n" +
" /^((?-mix:[^\\/]+))\\/((?-mix:a\\/b))$/ => ['cluster', 'name'],\n /^((?i-mx:x))$/ => ['name']\n },\n"
if b := readFile(t, filepath.Join(env, OutDir, "t.pp")); !strings.Contains(b, want) {
t.Fatalf("t.pp lacks %q:\n%s", want, b)
}
}
// Each env loads type t in openvox 9.3.0 only through state w10k does not model, so w10k writes no t.pp.
func TestCrossTypeSkips(t *testing.T) {
for name, files := range map[string]map[string]string{
"puppet core type": {"m/lib/puppet/type/t.rb": classic,
"m/lib/puppet/provider/t/x.rb": "Puppet::Type.type(:t).provide(:x, parent: Puppet::Type.type(:file).provider(:posix)) do\nend\n"},
"own type's providers still loading": {"m/lib/puppet/type/t.rb": classic,
"m/lib/puppet/provider/t/x.rb": "Puppet::Type.type(:t).provide(:x, parent: Puppet::Type.type(:t).provider(:y)) do\nend\n"},
"type in two modules": {"m/lib/puppet/type/t.rb": classic, "m/lib/puppet/type/u.rb": typeWith("u", ""), "n/lib/puppet/type/u.rb": typeWith("u", ""),
"m/lib/puppet/provider/t/x.rb": "Puppet::Type.type(:t).provide(:x, parent: Puppet::Type.type(:u).provider(:y)) do\nend\n"},
"missing type": {"m/lib/puppet/type/t.rb": classic,
"m/lib/puppet/provider/t/x.rb": "Puppet::Type.type(:t).provide(:x, parent: Puppet::Type.type(:nope).provider(:y)) do\nend\n"},
"loaded type's provider raises": {"m/lib/puppet/type/t.rb": classic, "m/lib/puppet/type/v.rb": typeWith("v", ""), "m/lib/puppet/provider/v/x.rb": "raise 'boom'\n",
"m/lib/puppet/provider/t/x.rb": "Puppet::Type.type(:t).provide(:x, parent: Puppet::Type.type(:v).provider(:x)) do\nend\n"},
"title_patterns compiles a bad regex": {"m/lib/puppet/type/t.rb": typeWith("t", " newparam(:c)\n def self.title_patterns\n c = Regexp.new('(')\n [[/(#{c})/, [[:name]]]]\n end\n")},
} {
t.Run(name, func(t *testing.T) {
if exists(filepath.Join(fidelityEnv(t, files), OutDir, "t.pp")) {
t.Fatal("t.pp written")
}
})
}
}
const featureTypeSrc = "Puppet::Type.newtype(:t) do\n feature :fm, 'm', methods: [:m]\n feature :fk, 'k', methods: [:k]\n feature :fd, 'd', methods: [:lcs_diff]\n" +
" newparam(:name) { |_n| isnamevar }\n newproperty(:p) do |prop|\n include Puppet::Util\n desc 'p'\n end\n ensurable { |x| defaultvalues }\nend\n"
func featureEnv(prov string, extra map[string]string) map[string]string {
files := map[string]string{"m/lib/puppet/type/t.rb": featureTypeSrc, "m/lib/puppet/provider/t/x.rb": prov,
"m/lib/puppet/feature/nolib.rb": "require 'puppet/util/feature'\nPuppet.features.add(:nolib, libs: ['no_such_lib_w10k'])\n",
"m/lib/puppet/feature/jsonf.rb": "Puppet.features.add(:jsonf, libs: 'json')\n",
"m/lib/puppet_x/m/mix.rb": "module PuppetX\n module M\n module Mix\n def m; end\n private :m\n def k; end\n end\n end\nend\n"}
maps.Copy(files, extra)
return files
}
// A provider gated on module features, with core and module mixins, loads in openvox 9.3.0 and documents want.
func TestFidelityFeatures(t *testing.T) {
env := fidelityEnv(t, featureEnv("require 'zzz_absent' if Puppet.features.nolib?\nrequire 'json' if Puppet.features.jsonf?\n"+
"require 'zzz_absent2' if Puppet.features.undefined_feat?\nrequire 'puppet/util/diff'\nrequire 'puppet_x/m/mix'\n"+
"Puppet::Type.type(:t).provide(:x) do\n include Puppet::Util::Diff\n include PuppetX::M::Mix\n desc 'x'\nend\n", nil))
if b := readFile(t, filepath.Join(env, OutDir, "t.pp")); !strings.Contains(b, " # x\n # : x\n # \n # * Supported features: `fd`, `fk`.\n") {
t.Fatalf("t.pp lacks the provider doc:\n%s", b)
}
}
// Each provider is gated on a feature that makes puppet fail to load it or that w10k cannot evaluate, so w10k skips.
func TestFeatureSkips(t *testing.T) {
for name, files := range map[string]map[string]string{
"true feature requires a missing lib": featureEnv("require 'zzz_absent' if Puppet.features.jsonf?\nPuppet::Type.type(:t).provide(:x) do\nend\n", nil),
"false feature unless": featureEnv("require 'zzz_absent' unless Puppet.features.nolib?\nPuppet::Type.type(:t).provide(:x) do\nend\n", nil),
"openvox feature": featureEnv("require 'json' if Puppet.features.posix?\nPuppet::Type.type(:t).provide(:x) do\nend\n", nil),
"feature file copies differ": featureEnv("require 'json' if Puppet.features.dup?\nPuppet::Type.type(:t).provide(:x) do\nend\n",
map[string]string{"m/lib/puppet/feature/dup.rb": "Puppet.features.add(:dup, libs: ['json'])\n", "n/lib/puppet/feature/dup.rb": "Puppet.features.add(:dup, libs: ['set'])\n"}),
"feature lib a module provides": featureEnv("require 'json' if Puppet.features.modlib?\nPuppet::Type.type(:t).provide(:x) do\nend\n",
map[string]string{"m/lib/puppet/feature/modlib.rb": "Puppet.features.add(:modlib, libs: ['mylib'])\n", "m/lib/mylib.rb": "raise 'x'\n"}),
} {
t.Run(name, func(t *testing.T) {
if exists(filepath.Join(fidelityEnv(t, files), OutDir, "t.pp")) {
t.Fatal("t.pp written")
}
})
}
}
const blockParent = "Puppet::Type.type(:u).provide(:base) do\n def self.lens(resource = nil, &block)\n if block\n @lens_block = block\n else\n" +
" raise(Puppet::Error, 'Lens is not provided') unless @lens_block\n @lens_block.call(resource)\n end\n end\n" +
" def self.path(resource = nil, &block)\n if block\n @path_block = block\n elsif @path_block\n @path_block.call(resource)\n else\n" +
" \"#{resource[:name]}\"\n end\n end\n def self.label(a = 'lbl', b = :s, &blk)\n a\n end\n def self.ivdoc(&block)\n @doc = block\n end\nend\n"
func blockEnv(prov string) map[string]string {
return map[string]string{"m/lib/puppet/type/u.rb": typeWith("u", ""), "m/lib/puppet/provider/u/base.rb": blockParent,
"m/lib/puppet/type/t.rb": typeWith("t", " newparam(:zz) if block_given?\n ensurable do\n defaultvalues\n newvalue(:extra) if block_given?\n block if block_given?\n end\n"),
"m/lib/puppet/provider/t/x.rb": prov}
}
// Class methods called with a block store it, block_given? is false outside methods, and a guarded raise does not
// run, so openvox 9.3.0 writes t.pp with want.
func TestFidelityBlockCalls(t *testing.T) {
env := fidelityEnv(t, blockEnv("raise('Missing u') if Puppet::Type.type(:u).nil?\nPuppet::Type.type(:t).provide(:x, parent: Puppet::Type.type(:u).provider(:base)) do\n"+
" lens { 'Shellvars.lns' }\n path do |resource|\n if resource\n 'a'\n else\n 'b'\n end\n end\n NAME = label\n desc NAME\nend\n"))
b := readFile(t, filepath.Join(env, OutDir, "t.pp"))
if !strings.Contains(b, " # x\n # : lbl\n") || strings.Contains(b, "zz") || strings.Contains(b, "extra") {
t.Fatalf("t.pp differs from puppet's:\n%s", b)
}
for name, prov := range map[string]string{
"guarded raise runs": "raise('Missing nope') if Puppet::Type.type(:nope).nil?\nPuppet::Type.type(:t).provide(:x) do\nend\n",
"block stored in @doc": "Puppet::Type.type(:t).provide(:x, parent: Puppet::Type.type(:u).provider(:base)) do\n ivdoc { 'x' }\nend\n",
"block call without block": "Puppet::Type.type(:t).provide(:x, parent: Puppet::Type.type(:u).provider(:base)) do\n lens\nend\n",
} {
t.Run(name, func(t *testing.T) {
if exists(filepath.Join(fidelityEnv(t, blockEnv(prov)), OutDir, "t.pp")) {
t.Fatal("t.pp written; real puppet writes none")
}
})
}
}
func rsapiPatterns(patterns string) map[string]string {
return map[string]string{"m/lib/puppet/type/t.rb": rsapi(" title_patterns: [\n"+patterns+" ],\n", " owner: { type: 'String', desc: 'o', behaviour: :namevar },\n")}
}
// Regexp#names counts only real named groups, so openvox 9.3.0 writes want; names w10k cannot model skip.
func TestFidelityTitlePatternNames(t *testing.T) {
env := fidelityEnv(t, rsapiPatterns(" { pattern: %r{^(?<name>[^-]*)\\(?<x>y\\)[(?<z>)]-(?<owner>.*)$}, desc: 'a' },\n"+
" { pattern: %r{^(?<name>.*) # (?<q>c)\n $}x, desc: 'b' },\n"))
want := " /^(?<name>[^-]*)\\(?<x>y\\)[(?<z>)]-(?<owner>.*)$/ => ['name', 'owner'],\n /(?x-mi:^(?<name>.*) # (?<q>c)\n $)/ => ['name']\n"
if b := readFile(t, filepath.Join(env, OutDir, "t.pp")); !strings.Contains(b, want) {
t.Fatalf("t.pp lacks %q:\n%s", want, b)
}
for _, re := range []string{`%r{^(?<name-x>.*)$}`, `%r{^\k<name>(?<name>.*)$}`, `%r{^(?<1name>.*)$}`} {
if exists(filepath.Join(fidelityEnv(t, rsapiPatterns(" { pattern: "+re+", desc: 'a' },\n")), OutDir, "t.pp")) {
t.Errorf("%s: t.pp written", re)
}
}
}
+63
View File
@@ -0,0 +1,63 @@
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 := parseSrc(src, func(rel, mod string) ([]libFile, error) {
if strings.Contains(rel, "mix") {
return []libFile{{mod: "m", rel: rel, src: mix}}, nil
}
return []libFile{{mod: "m", rel: rel, src: src}}, nil
})
if err == nil {
for _, ty := range types {
_, _ = render(ty, map[string]string{"a": ""}, time.Unix(0, 0))
}
}
w := newWorld(nil)
if pr, err := providerFile(libFile{mod: "m", rel: "puppet/provider/t/x.rb", src: src}, "t", false, w); err == nil && pr.c != nil {
_, _ = (&rtype{name: "t", features: []feature{{name: "f", methods: []string{"m"}, byMeth: true}}}).providerDoc(pr, map[string]*provDecl{pr.name: pr}, w)
}
_, _ = mixinMethods(src, "PuppetX::M")
_ = loadSrc(src)
_, _ = parsePType(src)
})
}
func FuzzEval(f *testing.F) {
for _, c := range evalCases {
f.Add(c.src)
}
f.Add("include PuppetX::Fm\ndefaultfor a: :b\n")
fm := fmModule("", fmInitvars, fmHook)
f.Fuzz(func(t *testing.T, src string) {
_, _, _, _ = evalProvider(src, len(src)%2 == 0)
w := newWorld(nil)
w.typ = &rtype{name: "t", validprops: []string{"a", "ensure"}}
w.types["t"] = &loadedType{t: w.typ}
if err := (&parser{w: w}).load(libFile{mod: "m", rel: "puppet_x/m/fm.rb", src: fm}); err != nil {
t.Fatal(err)
}
_, _ = providerFile(libFile{mod: "m", rel: "puppet/provider/t/x.rb", src: "Puppet::Type.type(:t).provide(:x) do\n" + src + "\nend\n"}, "t", false, w)
})
}
+490
View File
@@ -0,0 +1,490 @@
// 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 = "14"
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
gems map[string]bool
}
// Stats counts Generate's inputs; Skipped holds inputs that failed to parse and keep any previous output.
type Stats struct {
Generated, UpToDate int
Skipped []error
}
// Generate writes <env>/.resource_types; every file it reads must resolve inside env or one of roots.
// A skipped input has no .pp, so puppetserver falls back to its Ruby type.
func Generate(env string, roots ...string) (st Stats, err error) {
return GenerateGems(env, nil, roots...)
}
// GenerateGems is Generate with gems, which must be KnownGems, installed beside puppet.
func GenerateGems(env string, gems []string, roots ...string) (st Stats, err error) {
g := &gen{gems: map[string]bool{}}
for _, name := range gems {
if _, ok := knownGems[name]; !ok {
return st, fmt.Errorf("gem %q is not one w10k models", name)
}
g.gems[name] = true
}
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 st, err
}
g.roots = append(g.roots, real)
}
g.env = g.roots[0]
mods, err := g.modules()
if err != nil {
return st, 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 st, err
}
inputs = append(inputs, files...)
dirs, err := g.list(filepath.Join(m, "lib", "puppet", "provider"))
if err != nil {
return st, err
}
for _, d := range dirs {
files, err := g.glob(d)
if err != nil {
return st, 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 st, 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 st, err
}
entries, err := dir.ReadDir(-1)
_ = dir.Close()
if err != nil {
return st, 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 st, err
}
}
}
var errs []error
for _, in := range inputs {
name := strings.TrimSuffix(filepath.Base(in), ".rb")
wrote, err := generateOne(in, out, providers, g.libs(mods), g.shadows, g.gems)
switch {
case err == nil && wrote:
st.Generated++
case err == nil:
st.UpToDate++
case errors.As(err, new(skipErr)):
st.Skipped = append(st.Skipped, fmt.Errorf("%s: %w", strings.TrimPrefix(in, g.env+"/"), err))
if err := out.Remove(name + ".pp"); err != nil && !errors.Is(err, os.ErrNotExist) {
errs = append(errs, err)
}
default:
errs = append(errs, fmt.Errorf("%s: %w", strings.TrimPrefix(in, g.env+"/"), err))
}
}
return st, errors.Join(errs...)
}
// writeOut atomically writes b to name in out with mtime mt.
func writeOut(out *os.Root, name string, b []byte, mt time.Time) error {
tmp := "." + name + ".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.Write(b); err != nil {
_ = f.Close()
return err
}
if err := f.Close(); err != nil {
return err
}
if err := out.Chtimes(tmp, mt, mt); err != nil {
return err
}
return out.Rename(tmp, name)
}
// 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, by type.
func generateOne(in string, out *os.Root, providers map[string][]string, resolve Resolver, shadows func(string) (string, error), gems map[string]bool) (wrote bool, err error) {
defer func() {
if r := recover(); r != nil {
err = fmt.Errorf("panic: %v", r)
}
}()
ifi, err := os.Stat(in)
if err != nil {
return false, 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 false, nil
}
src, err := os.ReadFile(in)
if err != nil {
return false, err
}
w := newWorld(resolve)
w.shadows = shadows
w.gems = gems
w.provFiles = providers
types, err := parseFile(libFile{mod: moduleOf(in, 4), rel: "puppet/type/" + filepath.Base(in), src: string(src)}, w)
if err != nil {
return false, unparsed(err)
}
var t *rtype
for _, c := range types {
if c.name == name {
t = c
}
}
if t == nil {
return false, skipErr{fmt.Errorf("custom type %q was not defined", name)}
}
w.typ = t
w.types[name] = &loadedType{t: t}
docs, err := providerDocs(t, providers[name], w)
if err != nil {
return false, err
}
body, err := render(t, docs, time.Now())
if err != nil {
return false, unparsed(err)
}
return true, writeOut(out, dst, []byte(body), ifi.ModTime())
}
// moduleOf returns the module dir n levels above file f.
func moduleOf(f string, n int) string {
for ; n > 0; n-- {
f = filepath.Dir(f)
}
return f
}
// providerDocs returns the doc of each provider puppet registers for t, or a skip when loading a provider file could
// fail or its doc cannot be proven.
func providerDocs(t *rtype, files []string, w *world) (map[string]string, error) {
provs, err := loadProviders(t, files, w)
if err != nil {
return nil, err
}
docs := map[string]string{}
for name, pr := range provs {
doc, err := t.providerDoc(pr, provs, w)
if err != nil {
return nil, unparsed(fmt.Errorf("provider %s: %w", name, err))
}
docs[name] = doc
}
return docs, nil
}
// loadProviders loads t's provider files as the type's providerloader.loadall does, failing when one could raise.
func loadProviders(t *rtype, files []string, w *world) (map[string]*provDecl, error) {
if t.rsapi {
var b strings.Builder
for _, part := range strings.Split(t.name, "_") {
if part != "" {
b.WriteString(strings.ToUpper(part[:1]) + part[1:])
}
}
w.define("Puppet::Provider::"+b.String(), kMod)
}
provs := map[string]*provDecl{}
byFile := map[string]string{}
var parents []string
for _, f := range files {
src, err := os.ReadFile(f)
if err != nil {
return nil, err
}
base := filepath.Base(f)
pr, err := providerFile(libFile{mod: moduleOf(f, 5), rel: "puppet/provider/" + t.name + "/" + base, src: string(src)}, t.name, t.rsapi, w)
if err == nil && !t.rsapi && pr.name == "" {
err = fmt.Errorf("no Puppet::Type.type(:%s).provide call", t.name)
}
if err == nil && provs[pr.name] != nil {
err = fmt.Errorf("provider %s is defined twice", pr.name)
}
if err != nil {
return nil, unparsed(fmt.Errorf("provider %s: %w", base, err))
}
byFile[strings.TrimSuffix(base, ".rb")] = pr.name
if pr.parent != "" && provs[pr.parent] == nil {
parents = append(parents, pr.parent)
}
if pr.name != "" {
provs[pr.name] = pr
}
}
for _, p := range parents {
if byFile[p] != p {
return nil, skipErr{fmt.Errorf("parent provider %s is not defined", p)}
}
}
return provs, nil
}
// libs resolves lib/<rel> in every module in modulepath order, as Ruby's require searches module lib dirs, or in mod alone.
func (g *gen) libs(mods []string) Resolver {
return func(rel, mod string) ([]libFile, error) {
var out []libFile
for _, m := range mods {
if mod != "" && m != mod {
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
}
out = append(out, libFile{mod: m, rel: rel, src: string(b)})
}
return out, nil
}
}
// shadows returns a file under mod/lib whose require path resolves ahead of module lib dirs, or a symlink there.
func (g *gen) shadows(mod string) (string, error) {
real, err := g.confine(filepath.Join(mod, "lib"))
if err != nil {
return "", err
}
found := ""
err = filepath.WalkDir(real, func(p string, d fs.DirEntry, err error) error {
if err != nil {
return err
}
rel, _ := filepath.Rel(real, p)
lib := strings.TrimSuffix(strings.TrimSuffix(filepath.ToSlash(rel), ".rb"), ".so")
if d.Type()&fs.ModeSymlink != 0 || !d.IsDir() && lib != filepath.ToSlash(rel) && coreLib(lib) {
found = filepath.ToSlash(rel)
return fs.SkipAll
}
return nil
})
return found, err
}
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
}
+794
View File
@@ -0,0 +1,794 @@
package gentypes
import (
"errors"
"os"
"os/exec"
"path/filepath"
"strings"
"testing"
"time"
)
// realOnly are golden files real puppet generates that w10k skips because it cannot prove the output matches.
var realOnly = set("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 instead, comments included.
func TestGolden(t *testing.T) {
env, golden, allowSkip := "testdata/env", "testdata/golden", realOnly
view := func(s string) string { _, rest, _ := strings.Cut(s, "\n"); return rest }
if e := os.Getenv("GENTYPES_ENV"); e != "" {
env, golden, allowSkip = e, os.Getenv("GENTYPES_GOLDEN"), 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 := GenerateGems(work, []string{"toml"}); 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)
}
st, err := Generate(work)
if err != nil {
t.Fatal(err)
}
got := map[string]string{}
for _, s := range st.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 9: unsupported top-level RHelper.add",
"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 Type.newtype in RFoo",
"r_mod_compact": "unsupported Type.newtype in Puppet::RCompact",
"r_include_noreq": "include PuppetX::Review::Mix: no require defines it",
"r_feature_const": "uninitialized constant RNope",
"grafana_ldap_config": `require "toml": no module provides it`,
} {
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 := parseSrc("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 that use procs"},
{"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 := parseSrc(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 := parseSrc(src, nil)
if err != nil {
t.Fatal(err)
}
out, err := render(types[0], map[string]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)
}
st, err := Generate(env, cache)
if err != nil {
t.Fatal(err)
}
if st.Generated != 0 || st.UpToDate != 2 {
t.Fatalf("unchanged inputs must count as up to date: %+v", st)
}
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 st, err = Generate(env, cache); err != nil || st.Generated != 1 || st.UpToDate != 1 {
t.Fatalf("got %v, %+v", err, st)
}
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)
}
st, err := Generate(env)
if err != nil || len(st.Skipped) != 1 || !strings.Contains(st.Skipped[0].Error(), "modules/m/lib/puppet/type/bad.rb: line 2:") {
t.Fatalf("got %v, skipped %v", err, st.Skipped)
}
if !exists(filepath.Join(env, OutDir, "good.pp")) || exists(filepath.Join(env, OutDir, "bad.pp")) {
t.Fatal("good inputs still generate; a skipped input's old output is removed")
}
})
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 st, err := Generate(env); err != nil || len(st.Skipped) != 1 || !strings.Contains(st.Skipped[0].Error(), `"a" was not defined`) {
t.Fatalf("got %v, skipped %v", err, st.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 st, err := Generate(env); !errors.Is(err, errLimit) || len(st.Skipped) != 0 {
t.Fatalf("got %v, skipped %v", err, st.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 st, err := Generate(env); err != nil || len(st.Skipped) != 1 {
t.Fatalf("got %v, skipped %v", err, st.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 parseSrc(src string, resolve Resolver) ([]*rtype, error) {
return parseFile(libFile{mod: "m", rel: "puppet/type/t.rb", src: src}, newWorld(resolve))
}
func provSrc(src, typ string) (string, string, error) {
pr, err := providerFile(libFile{mod: "m", rel: "puppet/provider/" + typ + "/x.rb", src: src}, typ, false, newWorld(nil))
if err != nil {
return "", "", err
}
return pr.name, pr.parent, nil
}
func loadSrc(src string) (err error) {
defer guard(&err)
return (&parser{w: newWorld(nil)}).load(libFile{mod: "m", rel: "puppet_x/x.rb", src: src})
}
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 := parseSrc(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": "unsupported top-level )", "]\n": "unsupported top-level ]", "}\n": "unsupported top-level }", "end\n": "unsupported top-level end", "class A\n foo )\nend\n": "unsupported foo ) in A"} {
if _, _, err := provSrc(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 := parseSrc("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 := loadSrc("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: no require defines it as a module",
"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": "include Foo: no require defines it as a module",
"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\n def create; end\nend\n": "create",
"module PuppetX::M::Mix\n def self.append_features(base); end\nend\n": "def self.append_features hook",
"module PuppetX::M::Mix\n module ClassMethods\n def x; end\n end\n def flush; end\nend\n": "flush",
"module PuppetX::M::Mix\n include Other\nend\n": "unsupported include Other in mixin",
"module PuppetX::M::Mix\n extend ActiveSupport::Concern\nend\n": "unsupported extend",
"module PuppetX::M\nend\n": "not defined",
"module PuppetX::M::Mix\n def a; end\n def b; end\n private :a, :b\n public :b\n def c; end\nend\n": "b c",
"module PuppetX::M::Mix\n private :a\nend\n": "private: undefined method a",
} {
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) {}\n": "c ",
"Puppet::Type.type(:t).provide(:c, parent: Puppet::Provider::Foo) {}\n": "error",
"class Puppet::Provider::T::Rsapi\nend\n": "error",
"": " ",
"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",
"$": "error",
} {
name, parent, err := provSrc(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, string) ([]libFile, error) { panic("boom") }, nil, nil)
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)
}
}
// Ruby continues a line that ends in a method-call dot, across blank and comment lines.
func TestLexTrailingDot(t *testing.T) {
toks, err := lex("a.\n # c\n\n b&.\n c\nd\n")
if err != nil {
t.Fatal(err)
}
var got []string
for _, tk := range toks {
got = append(got, tk.text)
}
if s := strings.Join(got, " "); s != "a . b &. c d " {
t.Fatalf("tokens %q", s)
}
}
+698
View File
@@ -0,0 +1,698 @@
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++
if t := l.last(); t == nil || t.kind != tOp || t.text != "." && t.text != "&." {
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), flags: string(typ)})
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
File diff suppressed because it is too large Load Diff
+380
View File
@@ -0,0 +1,380 @@
package gentypes
import (
"fmt"
"math"
"regexp"
"regexp/syntax"
"slices"
"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
enum []string
}
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]+)?)$`)
zeroExp = regexp.MustCompile(`^\.?0*[eE]`)
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) {
t, err := parseTree(s)
if err != nil {
return "", 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
}
func parseTree(s string) (*ptype, error) {
p := &tparser{s: s}
t, err := p.typ(0)
if err != nil {
return nil, fmt.Errorf("type %q: %w", s, err)
}
if p.skip(); p.pos != len(p.s) {
return nil, fmt.Errorf("type %q: unsupported trailing input", s)
}
if t, err = normalize(t); err != nil {
return nil, fmt.Errorf("type %q: %w", s, err)
}
return t, nil
}
// presentAbsent reports whether s passes resource_api's validate_ensure: Enum[present, absent], optionally wrapped in Optional.
func presentAbsent(s string) bool {
t, err := parseTree(s)
if err != nil {
return false
}
if t.name == "Optional" && len(t.kids) == 1 {
t = t.kids[0]
}
v := slices.Compact(slices.Sorted(slices.Values(t.enum)))
return slices.Equal(v, []string{"absent", "present"})
}
// 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" {
flat = k.kids
}
for _, m := range flat {
if !seen[m.canon] {
seen[m.canon] = true
members = append(members, m)
}
}
}
switch len(members) {
case 0:
return &ptype{name: "Variant", canon: "Variant"}, nil
case 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' })
for i := 0; ok && i < len(texts); i++ {
t.enum = append(t.enum, unquote(texts[i]))
}
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
}
switch kinds {
case "ii":
a, _ := strconv.ParseInt(args[0].text, 10, 64)
b, _ := strconv.ParseInt(args[1].text, 10, 64)
return a <= b
case "if", "fi", "ff":
a, err1 := strconv.ParseFloat(args[0].text, 64)
b, err2 := strconv.ParseFloat(args[1].text, 64)
return err1 == nil && err2 == nil && a <= b
}
return true
}
// puppetFloat reports whether TypeParser lexes text (sans sign) as a finite float: lexer2's PATTERN_NUMBER and
// assert_numeric, then Utils.match_to_fp, which rejects zero mantissas with an exponent.
func puppetFloat(text string) bool {
m := floatLit.FindStringSubmatch(text)
if m == nil || m[2] == "" || m[1] == "0" && zeroExp.MatchString(m[2]) {
return false
}
f, err := strconv.ParseFloat(text, 64)
return err == nil && !math.IsInf(f, 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 puppetFloat(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
}
+682
View File
@@ -0,0 +1,682 @@
package gentypes
import (
"fmt"
"maps"
"regexp"
"slices"
"sort"
"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)
}
// providerParam ports providify's provider doc: each provider's doc as a Puppet::Util::Docs#markdown_definitionlist.
func providerParam(typ string, docs map[string]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 _, name := range slices.Sorted(maps.Keys(docs)) {
lines := strings.Split(scrub(docs[name]), "\n")
doc += name + "\n: " + lines[0] + "\n"
for _, l := range lines[1:] {
if l != "" {
l = " " + l
}
doc += l + "\n"
}
doc += "\n"
}
return &attr{name: "provider", doc: doc, raw: true}
}
// providerDoc ports Puppet::Util::Docs#doc on provider p: its desc, then openvox 9.3.0's dochooks in name order.
func (t *rtype) providerDoc(p *provDecl, provs map[string]*provDecl, w *world) (string, error) {
var extra []string
if len(p.c.commands) > 0 {
var bins []string
for _, v := range p.c.commands {
bins = append(bins, "`"+v+"`")
}
sort.Strings(bins)
extra = append(extra, "Required binaries: "+strings.Join(bins, ", ")+".")
}
if len(p.c.defaults) > 0 {
var parts []string
for _, d := range p.c.defaults {
s, err := defaultDoc(d)
if err != nil {
return "", err
}
parts = append(parts, s)
}
extra = append(extra, strings.Join(parts, " "))
}
feats, err := t.supported(p, provs, w)
if err != nil {
return "", err
}
if len(feats) > 0 {
extra = append(extra, "Supported features: "+strings.Join(feats, ", ")+".")
}
for i := range extra {
extra[i] = "* " + extra[i]
}
doc := strings.Join(extra, "\n")
if p.c.doc == nil {
return doc, nil
}
if doc != "" {
doc = "\n\n" + doc
}
return scrub(*p.c.doc) + doc, nil
}
// defaultDoc renders one defaultfor argument as Puppet::Provider's defaults dochook does.
func defaultDoc(d rval) (string, error) {
var pairs []string
add := func(f, v rval) error {
fs, err := rubyToS(f)
if err != nil {
return err
}
var vs []string
var flat func(rval) error
flat = func(v rval) error {
if v.k == vArray {
for _, e := range v.arr {
if err := flat(e); err != nil {
return err
}
}
return nil
}
s, err := rubyToS(v)
vs = append(vs, s)
return err
}
if err := flat(v); err != nil {
return err
}
pairs = append(pairs, "`"+fs+"` == `"+strings.Join(vs, ", ")+"`")
return nil
}
nilv := rval{k: vNil}
for i, k := range d.keys {
if err := add(k, d.arr[i]); err != nil {
return "", err
}
}
for _, e := range d.arr {
if d.k == vHash {
break
}
f, v := e, nilv
if e.k == vArray {
f = nilv
if len(e.arr) > 0 {
f = e.arr[0]
}
if len(e.arr) > 1 {
v = e.arr[1]
}
}
if err := add(f, v); err != nil {
return "", err
}
}
sort.Strings(pairs)
return "Default for " + strings.Join(pairs, " and ") + ".", nil
}
// rubyToS renders a literal as Ruby's #to_s.
func rubyToS(v rval) (string, error) {
switch v.k {
case vStr, vSym, vNum:
return v.s, nil
case vNil:
return "", nil
case vRegex:
on, off := v.re.opts()
if strings.Trim(v.re.flags, "mix") != "" || strings.HasPrefix(v.re.src, "(?") {
return "", fmt.Errorf("unsupported Regexp#to_s of /%s/%s", v.re.src, v.re.flags)
}
if off != "" {
off = "-" + off
}
return "(?" + on + off + ":" + exprStr(v.re.src) + ")", nil
}
return rubyInspect(v)
}
var (
bareSym = regexp.MustCompile(`^(?:[a-z_][A-Za-z0-9_]*[?!=]?|[A-Z][A-Za-z0-9_]*)$`)
opSym = regexp.MustCompile(`^(?:[@$]|[A-Z][A-Za-z0-9_]*[?!=]$|[-+*/%<>=!~^&|\[\]` + "`" + `]+$)`)
strEscs = map[byte]string{'"': `\"`, '\\': `\\`, '\n': `\n`, '\t': `\t`, '\r': `\r`, '\f': `\f`, '\v': `\v`, '\a': `\a`, '\b': `\b`, 0x1b: `\e`}
trueFals = map[vkind]string{vNil: "nil", vTrue: "true", vFalse: "false"}
)
// rubyInspect renders a literal as Ruby 3.3's #inspect, failing where w10k cannot prove the bytes.
func rubyInspect(v rval) (string, error) {
switch v.k {
case vNil, vTrue, vFalse:
return trueFals[v.k], nil
case vNum:
return v.s, nil
case vStr:
var b strings.Builder
b.WriteByte('"')
for i := 0; i < len(v.s); i++ {
c := v.s[i]
switch {
case strEscs[c] != "":
b.WriteString(strEscs[c])
case c == '#' && i+1 < len(v.s) && strings.IndexByte("{$@", v.s[i+1]) >= 0:
b.WriteString(`\#`)
case c < 0x20 || c >= 0x7f:
return "", fmt.Errorf("unsupported String#inspect of %q", v.s)
default:
b.WriteByte(c)
}
}
return b.String() + `"`, nil
case vSym:
switch {
case bareSym.MatchString(v.s):
return ":" + v.s, nil
case opSym.MatchString(v.s):
return "", fmt.Errorf("unsupported Symbol#inspect of %q", v.s)
}
s, err := rubyInspect(rval{k: vStr, s: v.s})
return ":" + s, err
case vRegex:
if strings.Trim(v.re.flags, "mix") != "" {
return "", fmt.Errorf("unsupported Regexp#inspect of /%s/%s", v.re.src, v.re.flags)
}
return v.re.inspect(), nil
case vArray, vHash:
var parts []string
for i, e := range v.arr {
s, err := rubyInspect(e)
if err != nil {
return "", err
}
if v.k == vHash {
k, err := rubyInspect(v.keys[i])
if err != nil {
return "", err
}
s = k + "=>" + s
}
parts = append(parts, s)
}
if v.k == vHash {
return "{" + strings.Join(parts, ", ") + "}", nil
}
return "[" + strings.Join(parts, ", ") + "]", nil
}
return "", fmt.Errorf("unsupported inspect of %s", v.kindName())
}
// supported ports the features dochook: t's features p declares itself or whose methods p defines publicly.
func (t *rtype) supported(p *provDecl, provs map[string]*provDecl, w *world) ([]string, error) {
chain, root, err := ancestry(p, provs, w)
if err != nil {
return nil, err
}
for _, c := range chain {
for n := range c.smethods {
if n == "features" || n == "feature?" || n == "declared_feature?" || slices.ContainsFunc(t.features, func(f feature) bool { return f.name+"?" == n }) {
return nil, fmt.Errorf("def self.%s shadows a provider feature method", n)
}
}
}
var out []string
for _, f := range t.features {
ok := slices.Contains(p.c.declared, f.name)
if !ok && f.byMeth {
ok = true
for _, m := range f.methods {
pub, err := t.publicMethod(m, chain, root)
if err != nil {
return nil, fmt.Errorf("feature %s: %w", f.name, err)
}
if !pub {
ok = false
break
}
}
}
if ok {
out = append(out, "`"+f.name+"`")
}
}
sort.Strings(out)
return out, nil
}
// ancestry returns p's class bodies from p up, and the first ancestor w10k has no body for.
func ancestry(p *provDecl, provs map[string]*provDecl, w *world) ([]*classCtx, string, error) {
var chain []*classCtx
for len(chain) <= maxDepth {
chain = append(chain, p.c)
if p.parent == "" {
break
}
if p = provs[p.parent]; p == nil {
return nil, "", fmt.Errorf("parent provider is not defined")
}
}
root := p.sup
if root == "" {
root = "Puppet::Provider"
}
for ; w.user[root] && w.classes[root] != nil && len(chain) <= maxDepth; root = w.sup[root] {
chain = append(chain, w.classes[root])
}
if len(chain) > maxDepth {
return nil, "", fmt.Errorf("provider ancestry is too deep")
}
return chain, root, nil
}
// publicMethod reports Module#public_method_defined?(m) on the provider whose ancestry is chain then root.
func (t *rtype) publicMethod(m string, chain []*classCtx, root string) (bool, error) {
name, _ := strings.CutSuffix(m, "=")
res := name != "name" && (name == "provider" || slices.ContainsFunc(append(t.props[:len(t.props):len(t.props)], t.params...), func(a *attr) bool { return a.name == name }))
for _, c := range chain {
switch {
case c.cmds[m] || c.mkres && res && c.methods[m]:
return false, fmt.Errorf("cannot order the definitions of method %s", m)
case c.methods[m]:
return !c.hidden[m], nil
case c.mkres && res || slices.Contains(c.mixed, m):
return true, nil
}
}
switch {
case root == "Puppet::Provider" && !providerMethods[m], root == "Puppet::Provider::ParsedFile" && !providerMethods[m] && !parsedMethods[m]:
return false, nil
}
return false, fmt.Errorf("method %s may be defined by %s", m, root)
}
// Public instance methods of openvox 9.3.0's Puppet::Provider and Puppet::Provider::ParsedFile on Ruby 3.3.
var (
providerMethods = set("! != !~ < <= <=> == === > >= N_ Nn_ _ __id__ __send__ adderrorcontext alert between? clamp class class_def clear clone command crit debug define_singleton_method devfail display dup emerg enum_for eql? equal? err error_context exceptwrap execpipe execute extend fail freeze frozen? get hash info inspect instance_eval instance_exec instance_of? instance_variable_defined? instance_variable_get instance_variable_set instance_variables is_a? itself kind_of? meta_def meta_eval meta_undef method methods n_ name nil? notice np_ ns_ object_id p_ private_methods protected_methods public_method public_methods public_send remove_instance_variable resource resource= respond_to? s_ send set singleton_class singleton_method singleton_methods tap then to_enum to_json to_s to_yaml warning yield_self")
parsedMethods = set("create destroy exists? flush prefetch property_hash property_hash= record_type")
)
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 map[string]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
}
File diff suppressed because it is too large Load Diff
+1
View File
@@ -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
@@ -0,0 +1,2 @@
Puppet::Type.type(:alternative_entry).provide(:chkconfig) do
end
@@ -0,0 +1,2 @@
Puppet::Type.type(:alternative_entry).provide(:dpkg) do
end
@@ -0,0 +1,2 @@
Puppet::Type.type(:alternatives).provide(:chkconfig) do
end
@@ -0,0 +1,2 @@
Puppet::Type.type(:alternatives).provide(:dpkg) do
end
@@ -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
@@ -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.
@@ -0,0 +1,2 @@
Puppet::Type.type(:archive).provide(:curl) do
end
@@ -0,0 +1,2 @@
Puppet::Type.type(:archive).provide(:ruby) do
end
@@ -0,0 +1,2 @@
Puppet::Type.type(:archive).provide(:wget) do
end
@@ -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,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.
@@ -0,0 +1,5 @@
# frozen_string_literal: true
require 'puppet/util/feature'
Puppet.features.add(:augeas, libs: ['augeas'])
@@ -0,0 +1,589 @@
#
# Copyright 2011 Bryan Kearney <bkearney@redhat.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
#
# https://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.
require 'augeas' if Puppet.features.augeas?
require 'strscan'
require 'puppet/util'
require 'puppet/util/diff'
require 'puppet/util/package'
require_relative '../../../puppet_x/augeas/util/parser'
Puppet::Type.type(:augeas).provide(:augeas) do
desc 'The Augeas provider'
include Puppet::Util
include Puppet::Util::Diff
include Puppet::Util::Package
include PuppetX::Augeas::Util::Parser
confine feature: :augeas
has_features :parse_commands, :need_to_run?, :execute_changes
SAVE_NOOP = 'noop'.freeze
SAVE_OVERWRITE = 'overwrite'.freeze
SAVE_NEWFILE = 'newfile'.freeze
SAVE_BACKUP = 'backup'.freeze
COMMANDS = {
'set' => [:path, :string],
'setm' => [:path, :string, :string],
'rm' => [:path],
'remove' => [:path],
'clear' => [:path],
'clearm' => [:path, :string],
'touch' => [:path],
'mv' => [:path, :path],
'move' => [:path, :path],
'rename' => [:path, :string],
'insert' => [:string, :string, :path],
'ins' => [:string, :string, :path],
'get' => [:path, :comparator, :string],
'values' => [:path, :glob],
'defvar' => [:string, :path],
'defnode' => [:string, :path, :string],
'match' => [:path, :glob],
'size' => [:comparator, :int],
'include' => [:string],
'not_include' => [:string],
'==' => [:glob],
'!=' => [:glob],
}.freeze
attr_accessor :aug
# Extracts an 2 dimensional array of commands which are in the
# form of command path value.
# The input can be
# - A string with one command
# - A string with many commands per line
# - An array of strings.
def parse_commands(data)
context = resource[:context]
# Add a trailing / if it is not there
unless context.empty?
context << '/' if context[-1, 1] != '/'
end
data = data.split($INPUT_RECORD_SEPARATOR) if data.is_a?(String)
data = data.flatten
args = []
data.each do |line|
next if line.nil?
line.strip!
next if line.empty?
argline = []
sc = StringScanner.new(line)
cmd = sc.scan(%r{\w+|==|!=})
formals = COMMANDS[cmd]
raise(_('Unknown command %{cmd}') % { cmd: cmd }) unless formals
argline << cmd
narg = 0
formals.each do |f|
sc.skip(%r{\s+})
narg += 1
if f == :path
start = sc.pos
nbracket = 0
in_single_tick = false
in_double_tick = false
loop do
sc.skip(%r{([^\]\[\s\\'"]|\\.)+})
ch = sc.getch
nbracket += 1 if ch == '['
nbracket -= 1 if ch == ']'
in_single_tick = !in_single_tick if ch == "'"
in_double_tick = !in_double_tick if ch == '"'
raise(_('unmatched [')) if nbracket < 0
break if (nbracket == 0 && !in_single_tick && !in_double_tick && (ch =~ %r{\s})) || sc.eos?
end
len = sc.pos - start
len -= 1 unless sc.eos?
p = sc.string[start, len]
raise(_('missing path argument %{narg} for %{cmd}') % { narg: narg, cmd: cmd }) if p.nil?
# Rip off any ticks if they are there.
p = p[1, (p.size - 2)] if p[0, 1] == "'" || p[0, 1] == '"'
p.chomp!('/')
argline << if p[0, 1] != '$' && p[0, 1] != '/'
context + p
else
p
end
elsif f == :string
delim = sc.peek(1)
if ["'", '"'].include?(delim)
sc.getch
argline << sc.scan(%r{([^\\#{delim}]|(\\.))*})
# Unescape the delimiter so it's actually possible to have a
# literal delim inside the string. We only unescape the
# delimeter and not every backslash-escaped character so that
# things like escaped spaces '\ ' get passed through because
# Augeas needs to see them. If we unescaped them, too, users
# would be forced to double-escape them
argline.last.gsub!(%r{\\(#{delim})}, '\1')
sc.getch
else
argline << sc.scan(%r{[^\s]+})
end
raise(_('missing string argument %{narg} for %{cmd}') % { narg: narg, cmd: cmd }) unless argline[-1]
elsif f == :comparator
argline << sc.scan(%r{(==|!=|=~|<=|>=|<|>)})
unless argline[-1]
puts sc.rest
raise(_('invalid comparator for command %{cmd}') % { cmd: cmd })
end
elsif f == :int
argline << sc.scan(%r{\d+}).to_i
elsif f == :glob
argline << sc.rest
end
end
args << argline
end
args
end
def open_augeas
unless @aug
flags = Augeas::NONE
flags = Augeas::TYPE_CHECK if resource[:type_check] == :true
flags |= if resource[:incl]
Augeas::NO_MODL_AUTOLOAD
else
Augeas::NO_LOAD
end
root = resource[:root]
load_path = get_load_path(resource)
debug("Opening augeas with root #{root}, lens path #{load_path}, flags #{flags}")
@aug = Augeas.open(root, load_path, flags)
debug("Augeas version #{get_augeas_version} is installed") if versioncmp(get_augeas_version, '0.3.6') >= 0
# Optimize loading if the context is given and it's a simple path,
# requires the glob function from Augeas 0.8.2 or up
glob_avail = !aug.match('/augeas/version/pathx/functions/glob').empty?
opt_ctx = resource[:context].match("^/files/[^'\"\\[\\]]+$") if resource[:context]
if resource[:incl]
aug.set('/augeas/load/Xfm/lens', resource[:lens])
aug.set('/augeas/load/Xfm/incl', resource[:incl])
restricted_metadata = '/augeas//error'
elsif glob_avail && opt_ctx
# Optimize loading if the context is given, requires the glob function
# from Augeas 0.8.2 or up
ctx_path = resource[:context].sub(%r{^/files(.*?)/?$}, '\1/')
load_path = "/augeas/load/*['%s' !~ glob(incl) + regexp('/.*')]" % ctx_path
if aug.match(load_path).size < aug.match('/augeas/load/*').size
aug.rm(load_path)
restricted_metadata = "/augeas/files#{ctx_path}/error"
else
# This will occur if the context is less specific than any glob
debug('Unable to optimize files loaded by context path, no glob matches')
end
end
aug.load
print_load_errors(restricted_metadata)
end
@aug
end
def close_augeas
return if @aug.nil?
@aug.close
debug('Closed the augeas connection')
@aug = nil
end
def numeric?(s)
case s
when Integer
true
when String
s.match(%r{\A[+-]?\d+?(\.\d+)?\Z}n).nil? ? false : true
else
false
end
end
# Used by the need_to_run? method to process get filters. Returns
# true if there is a match, false if otherwise
# Assumes a syntax of get /files/path [COMPARATOR] value
def process_get(cmd_array)
return_value = false
# validate and tear apart the command
raise(_('Invalid command: %{cmd}') % { cmd: cmd_array.join(' ') }) if cmd_array.length < 4
_ = cmd_array.shift
path = cmd_array.shift
comparator = cmd_array.shift
arg = cmd_array.join(' ')
# check the value in augeas
result = @aug.get(path) || ''
if ['<', '<=', '>=', '>'].include?(comparator) && numeric?(result) &&
numeric?(arg)
resultf = result.to_f
argf = arg.to_f
return_value = resultf.send(comparator, argf)
elsif comparator == '!='
return_value = (result != arg)
elsif comparator == '=~'
regex = Regexp.new(arg)
return_value = (result =~ regex)
else
return_value = result.send(comparator, arg)
end
!!return_value
end
# Used by the need_to_run? method to process values filters. Returns
# true if there is a matched value, false if otherwise
def process_values(cmd_array)
return_value = false
# validate and tear apart the command
raise(_('Invalid command: %{cmd}') % { cmd: cmd_array.join(' ') }) if cmd_array.length < 3
_ = cmd_array.shift
path = cmd_array.shift
# Need to break apart the clause
clause_array = parse_commands(cmd_array.shift)[0]
verb = clause_array.shift
# Get the match paths from augeas
result = @aug.match(path) || []
raise(_("Error trying to get path '%{path}'") % { path: path }) if result == -1
# Get the values of the match paths from augeas
values = result.map { |r| @aug.get(r) }
case verb
when 'include'
arg = clause_array.shift
return_value = values.include?(arg)
when 'not_include'
arg = clause_array.shift
return_value = !values.include?(arg)
when '=='
begin
arg = clause_array.shift
new_array = parse_to_array(arg)
return_value = (values == new_array)
rescue
raise(_('Invalid array in command: %{cmd}') % { cmd: cmd_array.join(' ') })
end
when '!='
begin
arg = clause_array.shift
new_array = parse_to_array(arg)
return_value = (values != new_array)
rescue
raise(_('Invalid array in command: %{cmd}') % { cmd: cmd_array.join(' ') })
end
end
!!return_value
end
# Used by the need_to_run? method to process match filters. Returns
# true if there is a match, false if otherwise
def process_match(cmd_array)
return_value = false
# validate and tear apart the command
raise(_('Invalid command: %{cmd}') % { cmd: cmd_array.join(' ') }) if cmd_array.length < 3
_ = cmd_array.shift
path = cmd_array.shift
# Need to break apart the clause
clause_array = parse_commands(cmd_array.shift)[0]
verb = clause_array.shift
# Get the values from augeas
result = @aug.match(path) || []
raise(_("Error trying to match path '%{path}'") % { path: path }) if result == -1
# Now do the work
case verb
when 'size'
raise(_('Invalid command: %{cmd}') % { cmd: cmd_array.join(' ') }) if clause_array.length != 2
comparator = clause_array.shift
arg = clause_array.shift
return_value = case comparator
when '!='
!result.size.send(:==, arg)
else
result.size.send(comparator, arg)
end
when 'include'
arg = clause_array.shift
return_value = result.include?(arg)
when 'not_include'
arg = clause_array.shift
return_value = !result.include?(arg)
when '=='
begin
arg = clause_array.shift
new_array = parse_to_array(arg)
return_value = (result == new_array)
rescue
raise(_('Invalid array in command: %{cmd}') % { cmd: cmd_array.join(' ') })
end
when '!='
begin
arg = clause_array.shift
new_array = parse_to_array(arg)
return_value = (result != new_array)
rescue
raise(_('Invalid array in command: %{cmd}') % { cmd: cmd_array.join(' ') })
end
end
!!return_value
end
# Generate lens load paths from user given paths and local pluginsync dir
def get_load_path(resource)
load_path = []
# Permits colon separated strings or arrays
if resource[:load_path]
load_path = [resource[:load_path]].flatten
load_path.map! { |path| path.split(%r{:}) }
load_path.flatten!
end
if Puppet.run_mode.name == :agent
if Puppet::FileSystem.exist?("#{Puppet[:libdir]}/augeas/lenses")
load_path << "#{Puppet[:libdir]}/augeas/lenses"
end
else
env = Puppet.lookup(:current_environment)
env.each_plugin_directory do |dir|
lenses = File.join(dir, 'augeas', 'lenses')
if File.exist?(lenses)
load_path << lenses
end
end
end
load_path.join(':')
end
def get_augeas_version
@aug.get('/augeas/version') || ''
end
def set_augeas_save_mode(mode)
@aug.set('/augeas/save', mode)
end
def print_load_errors(path)
errors = @aug.match('/augeas//error')
unless errors.empty?
if path && !@aug.match(path).empty?
warning(_('Loading failed for one or more files, see debug for /augeas//error output'))
else
debug('Loading failed for one or more files, output from /augeas//error:')
end
end
print_errors(errors)
end
def print_put_errors
errors = @aug.match("/augeas//error[. = 'put_failed']")
debug('Put failed on one or more files, output from /augeas//error:') unless errors.empty?
print_errors(errors)
end
def print_errors(errors)
errors.each do |errnode|
error = @aug.get(errnode)
debug("#{errnode} = #{error}") unless error.nil?
@aug.match("#{errnode}/*").each do |subnode|
subvalue = @aug.get(subnode)
debug("#{subnode} = #{subvalue}")
end
end
end
# Determines if augeas actually needs to run.
def need_to_run?
force = resource[:force]
return_value = true
begin
open_augeas
filter = resource[:onlyif]
unless filter == ''
cmd_array = parse_commands(filter)[0]
command = cmd_array[0]
begin
case command
when 'get' then return_value = process_get(cmd_array)
when 'values' then return_value = process_values(cmd_array)
when 'match' then return_value = process_match(cmd_array)
end
rescue StandardError => e
raise(_("Error sending command '%{command}' with params %{param}/%{message}") % { command: command, param: cmd_array[1..-1].inspect, message: e.message })
end
end
unless force
# If we have a version of augeas which is at least 0.3.6 then we
# can make the changes now and see if changes were made.
if return_value && versioncmp(get_augeas_version, '0.3.6') >= 0
debug('Will attempt to save and only run if files changed')
# Execute in NEWFILE mode so we can show a diff
set_augeas_save_mode(SAVE_NEWFILE)
do_execute_changes
save_result = @aug.save
unless save_result
print_put_errors
raise(Puppet::Error, _('Save failed, see debug output for details'))
end
saved_files = @aug.match('/augeas/events/saved')
if !saved_files.empty?
root = resource[:root].sub(%r{^/$}, '')
saved_files.map! { |key| @aug.get(key).sub(%r{^/files}, root) }
saved_files.uniq.each do |saved_file|
if Puppet[:show_diff] && @resource[:show_diff]
send(@resource[:loglevel], "\n" + diff(saved_file, saved_file + '.augnew'))
end
File.delete(saved_file + '.augnew')
end
debug('Files changed, should execute')
return_value = true
else
debug('Skipping because no files were changed')
return_value = false
end
end
end
ensure
if !return_value || resource.noop? || !save_result
close_augeas
end
end
return_value
end
def execute_changes
# Workaround Augeas bug where changing the save mode doesn't trigger a
# reload of the previously saved file(s) when we call Augeas#load
@aug.match('/augeas/events/saved').each do |file|
@aug.rm("/augeas#{@aug.get(file)}/mtime")
end
# Reload augeas, and execute the changes for real
set_augeas_save_mode(SAVE_OVERWRITE) if versioncmp(get_augeas_version, '0.3.6') >= 0
@aug.load
do_execute_changes
unless @aug.save
print_put_errors
raise(Puppet::Error, _('Save failed, see debug output for details'))
end
:executed
ensure
close_augeas
end
# Actually execute the augeas changes.
# rubocop:disable Style/GuardClause
def do_execute_changes
commands = parse_commands(resource[:changes])
commands.each do |cmd_array|
raise(_('invalid command %{cmd}') % { value0: cmd_array.join[' '] }) if cmd_array.length < 2
command = cmd_array[0]
cmd_array.shift
begin
case command
when 'set'
debug("sending command '#{command}' with params #{cmd_array.inspect}")
rv = aug.set(cmd_array[0], cmd_array[1])
raise(_("Error sending command '%{command}' with params %{params}") % { command: command, params: cmd_array.inspect }) unless rv
when 'setm'
if aug.respond_to?(command)
debug("sending command '#{command}' with params #{cmd_array.inspect}")
rv = aug.setm(cmd_array[0], cmd_array[1], cmd_array[2])
raise(_("Error sending command '%{command}' with params %{params}") % { command: command, params: cmd_array.inspect }) if rv == -1
else
raise(_("command '%{command}' not supported in installed version of ruby-augeas") % { command: command })
end
when 'rm', 'remove'
debug("sending command '#{command}' with params #{cmd_array.inspect}")
rv = aug.rm(cmd_array[0])
raise(_("Error sending command '%{command}' with params %{params}") % { command: command, params: cmd_array.inspect }) if rv == -1
when 'clear'
debug("sending command '#{command}' with params #{cmd_array.inspect}")
rv = aug.clear(cmd_array[0])
raise(_("Error sending command '%{command}' with params %{params}") % { command: command, params: cmd_array.inspect }) unless rv
when 'clearm'
# Check command exists ... doesn't currently in ruby-augeas 0.4.1
if aug.respond_to?(command)
debug("sending command '#{command}' with params #{cmd_array.inspect}")
rv = aug.clearm(cmd_array[0], cmd_array[1])
raise(_("Error sending command '%{command}' with params %{params}") % { command: command, params: cmd_array.inspect }) unless rv
else
raise(_("command '%{command}' not supported in installed version of ruby-augeas") % { command: command })
end
when 'touch'
debug("sending command '#{command}' (match, set) with params #{cmd_array.inspect}")
if aug.match(cmd_array[0]).empty?
rv = aug.clear(cmd_array[0])
raise(_("Error sending command '%{command}' with params %{params}") % { command: command, params: cmd_array.inspect }) unless rv
end
when 'insert', 'ins'
label = cmd_array[0]
where = cmd_array[1]
path = cmd_array[2]
case where
when 'before' then before = true
when 'after' then before = false
else raise(_("Invalid value '%{where}' for where param") % { where: where })
end
debug("sending command '#{command}' with params #{[label, where, path].inspect}")
rv = aug.insert(path, label, before)
raise(_("Error sending command '%{command}' with params %{params}") % { command: command, params: cmd_array.inspect }) if rv == -1
when 'defvar'
debug("sending command '#{command}' with params #{cmd_array.inspect}")
rv = aug.defvar(cmd_array[0], cmd_array[1])
raise(_("Error sending command '%{command}' with params %{params}") % { command: command, params: cmd_array.inspect }) unless rv
when 'defnode'
debug("sending command '#{command}' with params #{cmd_array.inspect}")
rv = aug.defnode(cmd_array[0], cmd_array[1], cmd_array[2])
raise(_("Error sending command '%{command}' with params %{params}") % { command: command, params: cmd_array.inspect }) unless rv
when 'mv', 'move'
debug("sending command '#{command}' with params #{cmd_array.inspect}")
rv = aug.mv(cmd_array[0], cmd_array[1])
raise(_("Error sending command '%{command}' with params %{params}") % { command: command, params: cmd_array.inspect }) if rv == -1
when 'rename'
debug("sending command '#{command}' with params #{cmd_array.inspect}")
rv = aug.rename(cmd_array[0], cmd_array[1])
raise(_("Error sending command '%{command}' with params %{params}") % { command: command, params: cmd_array.inspect }) if rv == -1
else raise(_("Command '%{command}' is not supported") % { command: command })
end
rescue StandardError => e
raise(_("Error sending command '%{command}' with params %{params}/%{message}") % { command: command, params: cmd_array.inspect, message: e.message })
end
end
end
# rubocop:enable Style/GuardClause
end
@@ -0,0 +1,208 @@
#
# Copyright 2011 Bryan Kearney <bkearney@redhat.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
#
# https://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.
require 'puppet/parameter/boolean'
Puppet::Type.newtype(:augeas) do
include Puppet::Util
feature :parse_commands, 'Parse the command string'
feature :need_to_run?, 'If the command should run'
feature :execute_changes, 'Actually make the changes'
@doc = <<-'EOT'
@summary Apply a change or an array of changes to the filesystem using the augeas tool.
Requires:
- [Augeas](http://www.augeas.net)
- The ruby-augeas bindings
@example Sample usage with a string:
augeas { "test1":
context => "/files/etc/sysconfig/firstboot",
changes => "set RUN_FIRSTBOOT YES",
onlyif => "match other_value size > 0",
}
@example Sample usage with an array and custom lenses:
augeas { "jboss_conf":
context => "/files",
changes => [
"set etc/jbossas/jbossas.conf/JBOSS_IP $ipaddress",
"set etc/jbossas/jbossas.conf/JAVA_HOME /usr",
],
load_path => "$/usr/share/jbossas/lenses",
}
EOT
newparam(:name) do
desc 'The name of this task. Used for uniqueness.'
isnamevar
end
newparam(:context) do
desc "Optional context path. This value is prepended to the paths of all
changes if the path is relative. If the `incl` parameter is set,
defaults to `/files + incl`; otherwise, defaults to the empty string."
defaultto ''
munge do |value|
if value.empty? && resource[:incl]
'/files' + resource[:incl]
else
value
end
end
end
newparam(:onlyif) do
desc "Optional augeas command and comparisons to control the execution of this type.
Note: `values` is not an actual augeas API command. It calls `match` to retrieve an array of paths
in <MATCH_PATH> and then `get` to retrieve the values from each of the returned paths.
Supported onlyif syntax:
* `get <AUGEAS_PATH> <COMPARATOR> <STRING>`
* `values <MATCH_PATH> include <STRING>`
* `values <MATCH_PATH> not_include <STRING>`
* `values <MATCH_PATH> == <AN_ARRAY>`
* `values <MATCH_PATH> != <AN_ARRAY>`
* `match <MATCH_PATH> size <COMPARATOR> <INT>`
* `match <MATCH_PATH> include <STRING>`
* `match <MATCH_PATH> not_include <STRING>`
* `match <MATCH_PATH> == <AN_ARRAY>`
* `match <MATCH_PATH> != <AN_ARRAY>`
where:
* `AUGEAS_PATH` is a valid path scoped by the context
* `MATCH_PATH` is a valid match syntax scoped by the context
* `COMPARATOR` is one of `>, >=, !=, ==, <=,` or `<`
* `STRING` is a string
* `INT` is a number
* `AN_ARRAY` is in the form `['a string', 'another']`"
defaultto ''
end
newparam(:changes) do
desc "The changes which should be applied to the filesystem. This
can be a command or an array of commands. The following commands are supported:
* `set <PATH> <VALUE>` --- Sets the value `VALUE` at location `PATH`
* `setm <PATH> <SUB> <VALUE>` --- Sets multiple nodes (matching `SUB` relative to `PATH`) to `VALUE`
* `rm <PATH>` --- Removes the node at location `PATH`
* `remove <PATH>` --- Synonym for `rm`
* `clear <PATH>` --- Sets the node at `PATH` to `NULL`, creating it if needed
* `clearm <PATH> <SUB>` --- Sets multiple nodes (matching `SUB` relative to `PATH`) to `NULL`
* `touch <PATH>` --- Creates `PATH` with the value `NULL` if it does not exist
* `ins <LABEL> (before|after) <PATH>` --- Inserts an empty node `LABEL` either before or after `PATH`.
* `insert <LABEL> <WHERE> <PATH>` --- Synonym for `ins`
* `mv <PATH> <OTHER PATH>` --- Moves a node at `PATH` to the new location `OTHER PATH`
* `move <PATH> <OTHER PATH>` --- Synonym for `mv`
* `rename <PATH> <LABEL>` --- Rename a node at `PATH` to a new `LABEL`
* `defvar <NAME> <PATH>` --- Sets Augeas variable `$NAME` to `PATH`
* `defnode <NAME> <PATH> <VALUE>` --- Sets Augeas variable `$NAME` to `PATH`, creating it with `VALUE` if needed
If the `context` parameter is set, that value is prepended to any relative `PATH`s."
end
newparam(:root) do
desc 'A file system path; all files loaded by Augeas are loaded underneath `root`.'
defaultto '/'
end
newparam(:load_path) do
desc "Optional colon-separated list or array of directories; these directories are searched for schema definitions.
The agent's `$libdir/augeas/lenses` path will always be added to support pluginsync."
defaultto ''
end
newparam(:force) do
desc "Optional command to force the augeas type to execute even if it thinks changes
will not be made. This does not override the `onlyif` parameter."
defaultto false
end
newparam(:type_check) do
desc 'Whether augeas should perform typechecking. Defaults to false.'
newvalues(:true, :false)
defaultto :false
end
newparam(:lens) do
desc "Use a specific lens, such as `Hosts.lns`. When this parameter is set, you
must also set the `incl` parameter to indicate which file to load.
The Augeas documentation includes [a list of available lenses](http://augeas.net/stock_lenses.html)."
end
newparam(:incl) do
desc "Load only a specific file, such as `/etc/hosts`. This can greatly speed
up the execution the resource. When this parameter is set, you must also
set the `lens` parameter to indicate which lens to use."
end
validate do
has_lens = !self[:lens].nil?
has_incl = !self[:incl].nil?
raise(Puppet::Error, _('You must specify both the lens and incl parameters, or neither.')) if has_lens != has_incl
end
newparam(:show_diff, boolean: true, parent: Puppet::Parameter::Boolean) do
desc "Whether to display differences when the file changes, defaulting to
true. This parameter is useful for files that may contain passwords or
other secret data, which might otherwise be included in Puppet reports or
other insecure outputs. If the global `show_diff` setting
is false, then no diffs will be shown even if this parameter is true."
defaultto :true
end
# This is the actual meat of the code. It forces
# augeas to be run and fails or not based on the augeas return
# code.
newproperty(:returns) do |_property|
include Puppet::Util
desc 'The expected return code from the augeas command. Should not be set.'
defaultto 0
# Make output a bit prettier
def change_to_s(_currentvalue, _newvalue)
_('executed successfully')
end
# if the onlyif resource is provided, then the value is parsed.
# a return value of 0 will stop execution because it matches the
# default value.
def retrieve
if @resource.provider.need_to_run?
:need_to_run
else
0
end
end
# Actually execute the command.
def sync
@resource.provider.execute_changes
end
end
end
@@ -0,0 +1,217 @@
# rubocop:disable Style/Documentation
module PuppetX; end
module PuppetX::Augeas; end
module PuppetX::Augeas::Util; end
# rubocop:enable Style/Documentation
# Container for helpers to parse user provided data contained in manifests.
module PuppetX::Augeas::Util::Parser
TOKEN_ARRAY_CLOSE = %r{\s*\]\s*}.freeze
TOKEN_ARRAY_OPEN = %r{\s*\[\s*}.freeze
TOKEN_ARRAY_SEPARATOR = %r{\s*,\s*}.freeze
TOKEN_CLOSE_CURLY = %r|}|.freeze
TOKEN_DOUBLE_QUOTE = %r{"}.freeze
TOKEN_DOUBLE_QUOTE_ESCAPED_CHAR = %r{\\(["\\abtnvfres0-7xu])}.freeze
TOKEN_DOUBLE_QUOTE_UNESCAPED_CHAR = %r{[^"\\]}.freeze
TOKEN_HEX_CHAR = %r{[0-9a-fA-F]{1,2}}.freeze
TOKEN_OCTAL_CHAR = %r{[0-7]{1,3}}.freeze
TOKEN_OPEN_CURLY = %r|{|.freeze
TOKEN_SINGLE_QUOTE = %r{'}.freeze
TOKEN_SINGLE_QUOTE_ESCAPED_CHAR = %r{\\(['\\])}.freeze
TOKEN_SINGLE_QUOTE_UNESCAPED_CHAR = %r{[^'\\]}.freeze
TOKEN_SPACE = %r{\s}.freeze
TOKEN_UNICODE_LONG_HEX_CHAR = %r{[0-9a-fA-F]{1,6}}.freeze
TOKEN_UNICODE_SHORT_HEX_CHAR = %r{[0-9a-fA-F]{4}}.freeze
# Parse a string into the (nearly) equivalent Ruby array. This only handles
# arrays with string members (double-, or single-quoted), and does not
# support the full quite of escape sequences that Ruby allows in
# double-quoted strings.
#
# @param string [String] The string to be parsed.
# @return [Array<String>] The parsed array elements, including handling any
# escape sequences.
def parse_to_array(string)
s = StringScanner.new(string)
match = array_open(s)
raise "Unexpected character in array at: #{s.rest}" if match.nil?
array_content = array_values(s)
match = array_close(s)
raise "Unexpected character in array at: #{s.rest}" if match.nil? || !s.empty?
array_content
end
def array_open(scanner)
scanner.scan(TOKEN_ARRAY_OPEN)
end
private :array_open
def array_close(scanner)
scanner.scan(TOKEN_ARRAY_CLOSE)
end
private :array_close
def array_separator(scanner)
scanner.scan(TOKEN_ARRAY_SEPARATOR)
end
private :array_separator
def single_quote_unescaped_char(scanner)
scanner.scan(TOKEN_SINGLE_QUOTE_UNESCAPED_CHAR)
end
private :single_quote_unescaped_char
def single_quote_escaped_char(scanner)
scanner.scan(TOKEN_SINGLE_QUOTE_ESCAPED_CHAR) && scanner[1]
end
private :single_quote_escaped_char
def single_quote_char(scanner)
single_quote_escaped_char(scanner) || single_quote_unescaped_char(scanner)
end
private :single_quote_char
def double_quote_unescaped_char(scanner)
scanner.scan(TOKEN_DOUBLE_QUOTE_UNESCAPED_CHAR)
end
private :double_quote_unescaped_char
# This handles the possible Ruby escape sequences in double-quoted strings,
# except for \M-x, \M-\C-x, \M-\cx, \c\M-x, \c?, and \C-?. The full list of
# escape sequences, and their meanings is taken from:
# https://github.com/ruby/ruby/blob/90fdfec11a4a42653722e2ce2a672d6e87a57b8e/doc/syntax/literals.rdoc#strings
def double_quote_escaped_char(scanner)
match = scanner.scan(TOKEN_DOUBLE_QUOTE_ESCAPED_CHAR)
return nil if match.nil?
case scanner[1]
when '\\' then '\\'
when '"' then '"'
when 'a' then "\a"
when 'b' then "\b"
when 't' then "\t"
when 'n' then "\n"
when 'v' then "\v"
when 'f' then "\f"
when 'r' then "\r"
when 'e' then "\e"
when 's' then "\s"
when %r{[0-7]}
# Back the scanner up by one byte so we can grab all of the potential
# octal digits at the same time.
scanner.pos = scanner.pos - 1
octal_character = scanner.scan(TOKEN_OCTAL_CHAR)
octal_character.to_i(8).chr
when 'x'
hex_character = scanner.scan(TOKEN_HEX_CHAR)
return nil if hex_character.nil?
hex_character.to_i(16).chr
when 'u'
unicode_short_hex_character(scanner) || unicode_long_hex_characters(scanner)
else
# Not a valid escape sequence as far as we're concerned.
nil
end
end
private :double_quote_escaped_char
def unicode_short_hex_character(scanner)
unicode_character = scanner.scan(TOKEN_UNICODE_SHORT_HEX_CHAR)
return nil if unicode_character.nil?
[unicode_character.hex].pack 'U'
end
private :unicode_short_hex_character
def unicode_long_hex_characters(scanner)
unicode_string = ''
return nil unless scanner.scan(TOKEN_OPEN_CURLY)
loop do
char = scanner.scan(TOKEN_UNICODE_LONG_HEX_CHAR)
break if char.nil?
unicode_string << [char.hex].pack('U')
separator = scanner.scan(TOKEN_SPACE)
break if separator.nil?
end
return nil if scanner.scan(TOKEN_CLOSE_CURLY).nil? || unicode_string.empty?
unicode_string
end
private :unicode_long_hex_characters
def single_quoted_string(scanner)
quoted_string = ''
match = scanner.scan(TOKEN_SINGLE_QUOTE)
return nil if match.nil?
loop do
match = single_quote_char(scanner)
break if match.nil?
quoted_string << match
end
match = scanner.scan(TOKEN_SINGLE_QUOTE)
return quoted_string if match
nil
end
private :single_quoted_string
def double_quote_char(scanner)
double_quote_escaped_char(scanner) || double_quote_unescaped_char(scanner)
end
private :double_quote_char
def double_quoted_string(scanner)
quoted_string = ''
match = scanner.scan(TOKEN_DOUBLE_QUOTE)
return nil if match.nil?
loop do
match = double_quote_char(scanner)
break if match.nil?
quoted_string << match
end
match = scanner.scan(TOKEN_DOUBLE_QUOTE)
return quoted_string if match
nil
end
private :double_quoted_string
def quoted_string(scanner)
single_quoted_string(scanner) || double_quoted_string(scanner)
end
private :quoted_string
def array_values(scanner)
values = []
loop do
match = quoted_string(scanner)
break if match.nil?
values << match
match = array_separator(scanner)
break if match.nil?
end
values
end
private :array_values
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.
@@ -0,0 +1,5 @@
# frozen_string_literal: true
require 'puppet/util/feature'
Puppet.features.add(:augeas, libs: ['augeas'])
@@ -0,0 +1,906 @@
# frozen_string_literal: true
require 'augeas' if Puppet.features.augeas?
# Base Augeas provider
# Handles basics such as opening, accessing and saving changes via an Augeas
# handle, plus standard configuration from a Puppet resource (e.g. the `target`
# parameter).
#
# To use, include as parent provider:
#
# Puppet::Type.type(:example).provide(
# :augeas,
# :parent => Puppet::Type.type(:augeasprovider).provider(:default)
# ) do
# # [..]
# end
#
Puppet::Type.type(:augeasprovider).provide(:default) do
# Class methods automatically added to a Puppet provider by including the
# {AugeasProviders::Provider} mixin.
# Returns the Augeas version used
#
# @return [String] Augeas version in use
# @api public
def self.aug_version
@aug_version ||= Augeas.open(nil, nil, Augeas::NO_MODL_AUTOLOAD) { |aug| aug.get('/augeas/version') }
end
# Returns whether a feature is supported.
#
# The following features are currently supported:
#
# * `:regexpi`: whether Augeas supports an 'i' flag in regexp expressions
#
# @param [Symbol] feature the feature to check
# @return [Boolean] whether feature is supported
# @api public
def self.supported?(feature)
case feature
when :regexpi
Puppet::Util::Package.versioncmp(aug_version, '1.0.0') >= 0
else
raise Puppet::Error, "Unknown feature '#{feature}'"
end
end
# Returns a node label to use for creating a new entry in an Augeas sequence
# (seq), given the current list, e.g. '1' if it's the first. Supply
# aug.match('$target/*') or similar.
#
# @param [Array<String>] existing paths, from Augeas#match
# @return [String] new node label
def self.next_seq(matches)
last = matches.map { |p| path_label(nil, p).to_i }.max || 0
(last + 1).to_s
end
# Returns a shared Augeas handler for all instances of the class
#
# @return [Augeas] Augeas shared Augeas handle
# @api private
def self.aug_handler
@aug_handler ||= Augeas.open(nil, loadpath, Augeas::NO_MODL_AUTOLOAD)
end
# Close the shared Augeas handler.
#
# @param [Augeas] aug open Augeas handle
# @api public
def self.augclose!(aug)
aug.close
end
# Opens Augeas and returns a handle to use. It loads only the file
# identified by {#target} (and the supplied `resource`) using {#lens}.
#
# If called with a block, this will be yielded to and the Augeas handle.
# Otherwise, the handle will be returned and not closed automatically.
# The handle will be closed by `post_resource_eval`.
#
# If `yield_resource` is set to true, the supplied `resource` will be passed
# as a yieldparam to the block, after the `aug` handle. Any arguments passed
# after `yield_resource` will be added as yieldparams to the block.
#
# @param [Puppet::Resource] resource resource being evaluated
# @param [Boolean] yield_resource whether to send `resource` as a yieldparam
# @param [Splat] yield_params a splat of parameters to pass as yieldparams if `yield_resource` is true
# @return [Augeas] Augeas handle if no block is given
# @yield [aug, resource, *yield_params] block that uses the Augeas handle
# @yieldparam [Augeas] aug open Augeas handle
# @yieldparam [Puppet::Resource] resource the supplied Puppet resource, passed if `yield_resource` is set to true
# @yieldparam [Splat] *yield_params a splat of additional arguments sent to the block, if `yield_resource` is set to true
# @raise [Puppet::Error] if Augeas did not load the file
# @api public
def self.augopen(resource = nil, yield_resource = false, *yield_params, &block)
augopen_internal(resource, yield_resource, *yield_params, &block)
end
# Opens Augeas and returns a handle to use. It loads only the file
# for the current Puppet resource using {AugeasProviders::Provider::ClassMethods#lens}.
# #augsave! is called after the block is evaluated.
#
# If called with a block, this will be yielded to and the Augeas handle.
# Otherwise, the handle will be returned and not closed automatically.
# The handle will be closed by `post_resource_eval`.
#
# If `yield_resource` is set to true, the supplied `resource` will be passed
# as a yieldparam to the block, after the `aug` handle. Any arguments passed
# after `yield_resource` will be added as yieldparams to the block.
#
# @param [Puppet::Resource] resource resource being evaluated
# @param [Boolean] yield_resource whether to send `resource` as a yieldparam
# @param [Splat] yield_params a splat of parameters to pass as yieldparams if `yield_resource` is true
# @return [Augeas] Augeas handle if no block is given
# @yield [aug, resource, *yield_params] block that uses the Augeas handle
# @yieldparam [Augeas] aug open Augeas handle
# @yieldparam [Puppet::Resource] resource the supplied Puppet resource, passed if `yield_resource` is set to true
# @yieldparam [Splat] *yield_params a splat of additional arguments sent to the block, if `yield_resource` is set to true
# @raise [Puppet::Error] if Augeas did not load the file
# @api public
def self.augopen!(resource = nil, yield_resource = false, *yield_params, &block)
augopen_internal(resource, yield_resource, *yield_params, &block)
end
# Saves all changes made in the current Augeas handle and checks for any
# errors while doing so.
# Reloads the tree afterwards to remove specific changes for next resource.
#
# @param [Augeas] aug open Augeas handle
# @param [Boolean] reload whether to reload the tree after saving
# @raise [Augeas::Error] if saving fails
# @api public
def self.augsave!(aug, reload = false)
aug.save!
rescue Augeas::Error
errors = []
aug.match('/augeas//error').each do |errnode|
aug.match("#{errnode}/*").each do |subnode|
subvalue = aug.get(subnode)
errors << "#{subnode} = #{subvalue}"
end
end
debug("Save failure details:\n#{errors.join("\n")}")
raise Augeas::Error, 'Failed to save Augeas tree to file. See debug logs for details.'
ensure
aug.load! if reload
# https://github.com/hercules-team/augeas/commit/eb04250a05671b2d001444b72b8778328d209d75 introduced a bug in libaugeas.so.0.25.0
# bundled with puppet7.
# A temporary fix is to invoke load! twice.
aug.load! if reload && Puppet::Util::Package.versioncmp(aug_version, '1.13.0') >= 0
end
# Define a method with a block passed to #augopen
#
# @param [Symbol] method the name of the method to create
# @yield [aug, resource, *args] block that uses the Augeas handle
# @yieldparam [Augeas] aug open Augeas handle
# @yieldparam [Puppet::Resource] resource the supplied Puppet resource
# @yieldparam [Splat] *args a splat of additional arguments sent to the block
# @api public
def self.define_aug_method(method, &block)
define_method(method) do |*args|
# We are calling the resource's augopen here, not the class
augopen(true, *args, &block)
end
end
# Define a method with a block passed to #augopen!
#
# @param [Symbol] method the name of the method to create
# @yield [aug, resource, *args] block that uses the Augeas handle
# @yieldparam [Augeas] aug open Augeas handle
# @yieldparam [Puppet::Resource] resource the supplied Puppet resource
# @yieldparam [Splat] *args a splat of additional arguments sent to the block
# @api public
def self.define_aug_method!(method, &block)
define_method(method) do |*args|
# We are calling the resource's augopen! here, not the class
augopen!(true, *args, &block)
end
end
# Defines a property getter with a provided implementation. It works from
# a node identified with the given `label` beneath the resource.
#
# Supports three implementations based on the type specified:
#
# :string causes the getter to return the value of the node below
# resource with the label given in opts
#
# :array causes the getter to return an array of values matching the label.
# If sublabel is given, values of matching nodes beneath the
# label node will be returned in an array. If sublabel is :seq, values of
# nodes matching a numbered seq will be returned.
#
# :hash causes the getter to return a hash of the value of each matching
# label node against the value of each sublabel node.
#
# @param [String] name the name of the property
# @param [Hash] opts the options to create the setter
# @option opts [String] label node label to match beneath resource, default is `name.to_s`. When the value is `:resource`, `$resource` will be used as the path to the node
# @option opts [Symbol] type either :string, :array or :hash
# @option opts [String] default default value for hash values if sublabel doesn't exist
# @option opts [String] sublabel label of next node(s) beneath node label, used in array and hash values, or :seq for array values representing a numbered seq
# @api public
def self.attr_aug_reader(name, opts = {})
label = opts[:label] || name.to_s
default = opts[:default] || nil
type = opts[:type] || :string
sublabel = opts[:sublabel] || nil
split_by = opts[:split_by] || nil
rpath = label == :resource ? '$resource' : "$resource/#{label}"
raise(Puppet::Error, 'You must provide a sublabel for type hash') if type == :hash && sublabel.nil?
raise(Puppet::Error, "Invalid type: #{type}") unless %i[string array hash].include? type
# Class getter method using an existing aug handler
# Emulate define_singleton_method for Ruby 1.8
metaclass = class << self; self; end
metaclass.send(:define_method, "attr_aug_reader_#{name}") do |aug, *_args|
case type
when :string
aug.get(rpath)
when :array
return (aug.get(rpath) || '').split(split_by) if split_by
aug.match(rpath).map do |p|
if sublabel.nil?
aug.get(p)
else
sp = sublabel == :seq ? "#{p}/*[label()=~regexp('[0-9]+')]" : "#{p}/#{sublabel}"
aug.match(sp).map { |spp| aug.get(spp) }
end
end.flatten
when :hash
values = {}
aug.match(rpath).each do |p|
sp = "#{p}/#{sublabel}"
values[aug.get(p)] = aug.get(sp) || default
end
values
end
end
# Instance getter method for the instance
define_method("attr_aug_reader_#{name}") do |aug, *args|
self.class.send("attr_aug_reader_#{name}", aug, *args)
end
# We are calling the resource's augopen here, not the class
define_method(name) do |*args|
augopen do |aug|
send("attr_aug_reader_#{name}", aug, *args)
end
end
end
# Defines a property setter using #augopen
#
# @param [String] name the name of the property
# @param [Hash] opts the options to create the setter
# @option opts [String] label node label to match beneath resource, default is `name.to_s`. When the value is `:resource`, `$resource` will be used as the path to the node
# @option opts [Symbol] type either :string, :array or :hash
# @option opts [String] default default value for hash values if sublabel doesn't exist
# @option opts [String] sublabel label of next node(s) beneath node label, used in array and hash values, or :seq for array values representing a numbered seq
# @option opts [Boolean] purge_ident whether to purge other matches (keeps the last one only)
# @option opts [Boolean] rm_node whether setting a string value to `nil` removes the node (default is to clear its value)
# @api public
def self.attr_aug_writer(name, opts = {})
label = opts[:label] || name.to_s
default = opts[:default] || nil
type = opts[:type] || :string
sublabel = opts[:sublabel] || nil
purge_ident = opts[:purge_ident] || false
rm_node = opts[:rm_node] || false
split_by = opts[:split_by] || nil
rpath = label == :resource ? '$resource' : "$resource/#{label}"
raise(Puppet::Error, 'You must provide a sublabel for type hash') if type == :hash && sublabel.nil?
raise(Puppet::Error, "Invalid type: #{type}") unless %i[string array hash].include? type
# Class setter method using an existing aug handler
# Emulate define_singleton_method for Ruby 1.8
metaclass = class << self; self; end
metaclass.send(:define_method, "attr_aug_writer_#{name}") do |aug, *args|
aug.rm("#{rpath}[position() != 1]") if purge_ident
case type
when :string
if args[0]
aug.set(rpath, args[0].to_s)
elsif rm_node
aug.rm(rpath)
else
aug.clear(rpath)
end
when :array
if args[0].nil? || args[0].empty?
aug.rm(rpath)
elsif split_by
aug.set(rpath, args[0].join(split_by))
elsif sublabel.nil?
aug.rm(rpath)
count = 0
args[0].each do |v|
count += 1
aug.set("#{rpath}[#{count}]", v)
end
elsif sublabel == :seq
# Make sure only our values are used
aug.rm("#{rpath}/*[label()=~regexp('[0-9]+')]")
count = 0
args[0].each do |v|
count += 1
aug.set("#{rpath}/#{count}", v)
end
else
# Make sure only our values are used
aug.rm("#{rpath}/#{sublabel}")
count = 0
args[0].each do |v|
count += 1
aug.set("#{rpath}/#{sublabel}[#{count}]", v)
end
end
when :hash
# First get rid of all entries
aug.rm(rpath)
args[0].each do |k, v|
aug.set("#{rpath}[.='#{k}']", k)
aug.set("#{rpath}[.='#{k}']/#{sublabel}", v) unless v == default
end
end
end
# Instance setter method for the instance
define_method("attr_aug_writer_#{name}") do |aug, *args|
self.class.send("attr_aug_writer_#{name}", aug, *args)
end
# We are calling the resource's augopen here, not the class
define_method("#{name}=") do |*args|
augopen! do |aug|
send("attr_aug_writer_#{name}", aug, *args)
end
end
end
# Define getter and setter for a property
#
# @param [Symbol] name the name of the property
# @param [Hash] opts the options to create the setter
# @option opts [String] label node label to match beneath resource, default is `name.to_s`. When the value is `:resource`, `$resource` will be used as the path to the node
# @option opts [Symbol] type either :string, :array or :hash
# @option opts [String] default default value for hash values if sublabel doesn't exist
# @option opts [String] sublabel label of next node(s) beneath node label, used in array and hash values, or :seq for array values representing a numbered seq
# @option opts [Boolean] purge_ident whether to purge other matches (keeps the last one only)
# @api public
def self.attr_aug_accessor(name, opts = {})
attr_aug_reader(name, opts)
attr_aug_writer(name, opts)
end
# Setter for the default file path managed by the provider.
#
# Takes a block to store, but doesn't yield. Will be called when it's
# needed.
#
# @yield block that identifies the default file path managed by the provider
# @yieldreturn [String] default file path
# @api public
def self.default_file(&block)
@default_file_block = block
end
# Getter and setter for the Augeas lens used for this provider.
#
# When called with a block, will only store the block - it doesn't yield.
#
# When called without a block, expects `resource` parameter which is
# passed into the block, which returns the lens to be used.
#
# @param resource [Puppet::Resource] required for getter, resource being evaluated
# @yield [resource] block that identifies the lens to use
# @yieldparam [Puppet::Resource] resource resource being evaluted
# @yieldreturn [String] Augeas lens to use, e.g. `'Hosts.lns'`
# @return [String] Augeas lens to use, e.g. `'Hosts.lns'`
# @raise [Puppet::Error] if no block has been set when getting
# @api public
def self.lens(resource = nil, &block)
if block
@lens_block = block
else
raise(Puppet::Error, 'Lens is not provided') unless @lens_block
@lens_block.call(resource)
end
end
# Wrapper around aug.label for older versions of Augeas
# and values not found in the tree.
#
# @param [Augeas] aug Augeas handler
# @param [String] path expression to get the label from
# @return [String] label of the given path
# @api public
def self.path_label(aug, path)
label = aug.label(path) if aug.respond_to? :label
# Fallback
label || path.split('/')[-1].split('[')[0]
end
# Determine which quote is needed
#
# @param [String] value the value to quote
# @param [String] oldvalue the optional old value, used to auto-detect existing quoting
# @return [String] the quoted value
# @api public
def self.whichquote(value, resource = nil, oldvalue = nil)
oldquote = readquote oldvalue
quote = if resource&.parameters&.include?(:quoted)
resource[:quoted]
else
:auto
end
if quote == :auto
quote = if oldquote
oldquote
elsif value.match?(%r{[|&;()<>\s]})
:double
else
:none
end
end
case quote
when :double
'"'
when :single
"'"
else
''
end
end
# Automatically quote a value
#
# @param [String] value the value to quote
# @param [String] oldvalue the optional old value, used to auto-detect existing quoting
# @return [String] the quoted value
# @api public
def self.quoteit(value, resource = nil, oldvalue = nil)
quote = whichquote(value, resource, oldvalue)
"#{quote}#{value}#{quote}"
end
# Detect what type of quoting a value uses
#
# @param [String] value the value to be analyzed
# @return [Symbol] the type of quoting used (:double, :single or nil)
# @api public
def self.readquote(value)
if value =~ %r{^(["'])(.*)(?:\1)$}
case Regexp.last_match(1)
when '"' then :double
when "'" then :single
end
end
end
# Getter and setter for the Augeas path expression representing an
# individual resource inside a file, that's managed by this provider.
#
# When called with a block, will only store the block - it doesn't yield.
# The block is later used to generate the path expression.
#
# When called without a block, expects `resource` parameter which is
# passed into the block, which returns the path expression representing
# the supplied resource.
#
# If no block has already been set, it returns the path expression
# representing the top-level of the file.
#
# @param resource [Puppet::Resource] required for getter, resource being evaluated
# @yield [resource] block that identifies the path expression
# @yieldparam [Puppet::Resource] resource resource being evaluted
# @yieldreturn [String] Augeas path expression, e.g. `'/files/etc/hosts/1'`
# @return [String] Augeas path expression to use, e.g. `'/files/etc/hosts/1'`
# @raise [Puppet::Error] if no default file block is set and no resource is passed
# @see AugeasProviders::Provider#resource_path
# @see #target
# @api public
def self.resource_path(resource = nil, &block)
if block
@resource_path_block = block
elsif @resource_path_block
@resource_path_block.call(resource)
else
"#{target(resource)}/#{resource[:name]}"
end
end
# Sets useful Augeas variables for the session.
#
# * `$target` points to the root of the target file
# * `$resource` points to path defined by #resource_path
#
# It also sets `/augeas/context` to the target file so
# relative paths can be used, before the variables are set.
#
# If supplied with a resource, it will be used to determine the
# path to the used file.
#
# @param [Augeas] aug Augeas handle
# @param [Puppet::Resource] resource resource being evaluated
# @see #resource_path
# @api public
def self.setvars(aug, resource = nil)
aug.context = "/files#{target(resource)}"
aug.defnode('target', "/files#{target(resource)}", nil)
aug.defvar('resource', resource_path(resource)) if resource
end
# Gets the path expression representing the file being managed.
#
# If supplied with a resource, this will represent the file identified by
# the resource, else the default file that the provider manages.
#
# @param [Puppet::Resource] resource resource being evaluated
# @return [String] path expression representing the file being managed
# @raise [Puppet::Error] if no default block is set and no resource is passed
# @see AugeasProviders::Provider#target
# @see #resource_path
# @api public
def self.target(resource = nil)
file = @default_file_block.call if @default_file_block
file = resource[:target] if resource && resource[:target]
raise(Puppet::Error, 'No target file given') if file.nil?
file.chomp('/')
end
# Automatically unquote a value
#
# @param [String] value the value to unquote
# @return [String] the unquoted value
# @api public
def self.unquoteit(value)
if value =~ %r{^(["'])(.*)(?:\1)$}
Regexp.last_match(2)
else
value
end
end
# Returns whether text is parsed as path using lens
#
# @param [String] text the text to test
# @param [String] path the relative path to test
# @param [String] lens the lens to use for parsing
# @return [Boolean] whether the path was found when parsing text with lens
# @api public
def self.parsed_as?(text, path, lens)
Augeas.open(nil, nil, Augeas::NO_MODL_AUTOLOAD) do |aug|
if aug.respond_to? :text_store
aug.set('/input', text)
return aug.match("/parsed/#{path}").any? if aug.text_store(lens, '/input', '/parsed')
else
# ruby-augeas < 0.5 doesn't support text_store
Tempfile.open('aug_text_store') do |tmpfile|
tmpfile.write(text)
tmpfile.flush
aug.transform(
lens: lens,
name: 'Text_store',
incl: tmpfile.path.to_s,
excl: []
)
aug.load!
return aug.match("/files#{tmpfile.path}/#{path}").any?
end
end
end
false
end
# Sets the post_resource_eval class hook for Puppet
# This allows to clean the shared Augeas handler.
def self.post_resource_eval
augclose!(aug_handler)
@aug_handler = nil
end
# Returns a set of load paths to use when initialising Augeas.
#
# @return [String] colon-separated string of module paths, or nil if defaults are to be used
def self.loadpath
loadpath = nil
plugins = File.join(Puppet[:libdir], 'augeas', 'lenses')
loadpath = loadpath.to_s.split(File::PATH_SEPARATOR).push(plugins).join(File::PATH_SEPARATOR) if File.exist?(plugins)
loadpath
end
# Opens Augeas and returns a handle to use. It loads only the file
# identified by {#target} (and the supplied `resource`) using {#lens}.
#
# If called with a block, this will be yielded to and the Augeas handle.
# Otherwise, the handle will be returned and not closed automatically.
# The handle will be closed by `post_resource_eval`.
#
# If `yield_resource` is set to true, the supplied `resource` will be passed
# as a yieldparam to the block, after the `aug` handle. Any arguments passed
# after `yield_resource` will be added as yieldparams to the block.
#
# @param [Puppet::Resource] resource resource being evaluated
# @param [Boolean] yield_resource whether to send `resource` as a yieldparam
# @param [Splat] yield_params a splat of parameters to pass as yieldparams if `yield_resource` is true
# @return [Augeas] Augeas handle if no block is given
# @yield [aug, resource, *yield_params] block that uses the Augeas handle
# @yieldparam [Augeas] aug open Augeas handle
# @yieldparam [Puppet::Resource] resource the supplied Puppet resource, passed if `yield_resource` is set to true
# @yieldparam [Splat] *yield_params a splat of additional arguments sent to the block, if `yield_resource` is set to true
# @raise [Puppet::Error] if Augeas did not load the file
# @api private
def self.augopen_internal(resource = nil, yield_resource = false, *yield_params, &block)
aug = aug_handler
file = target(resource)
begin
lens_name = lens[%r{[^.]+}]
if aug.match("/augeas/load/#{lens_name}").empty?
aug.transform(
lens: lens,
name: lens_name,
incl: file,
excl: []
)
aug.load!
elsif aug.match("/augeas/load/#{lens_name}/incl[.='#{file}']").empty?
# Only add missing file
aug.set("/augeas/load/#{lens_name}/incl[.='#{file}']", file)
aug.load!
end
if File.exist?(file) && aug.match("/files#{file}").empty?
message = aug.get("/augeas/files#{file}/error/message")
unless aug.match("/augeas/files#{file}/error/pos").empty?
line = aug.get("/augeas/files#{file}/error/line")
char = aug.get("/augeas/files#{file}/error/char")
message += " (line:#{line}, character:#{char})"
end
from = loadpath.nil? ? '' : " from #{loadpath}"
raise(Puppet::Error, "Augeas didn't load #{file} with #{lens}#{from}: #{message}")
end
if block
setvars(aug, resource)
if yield_resource
block.call(aug, resource, *yield_params)
else
block.call(aug)
end
else
aug
end
rescue StandardError
raise
end
end
# Returns the Augeas version used
#
# @return [String] Augeas version in use
# @api public
def aug_version
self.class.aug_version
end
# Returns whether a feature is supported.
#
# The following features are currently supported:
#
# * `:regexpi`: whether Augeas supports an 'i' flag in regexp expressions
#
# @param [Symbol] feature the feature to check
# @return [Boolean] whether feature is supported
# @api public
def supported?(feature)
self.class.supported?(feature)
end
# Opens Augeas and returns a handle to use. It loads only the file
# for the current Puppet resource using {AugeasProviders::Provider::ClassMethods#lens}.
#
# If called with a block, this will be yielded to and the Augeas handle.
# Otherwise, the handle will be returned and not closed automatically.
# The handle will be closed by `post_resource_eval`.
#
# If `yield_resource` is set to true, the supplied `resource` will be passed
# as a yieldparam to the block, after the `aug` handle. Any arguments passed
# after `yield_resource` will be added as yieldparams to the block.
#
# @return [Augeas] Augeas handle if no block is given
# @yield [aug, resource, *yield_params] block that uses the Augeas handle
# @yieldparam [Augeas] aug open Augeas handle
# @yieldparam [Puppet::Resource] resource the supplied Puppet resource, passed if `yield_resource` is set to true
# @yieldparam [Splat] *yield_params a splat of additional arguments sent to the block, if `yield_resource` is set to true
# @raise [Puppet::Error] if Augeas did not load the file
# @api public
def augopen(yield_resource = false, *yield_params, &block)
self.class.augopen(resource, yield_resource, *yield_params, &block)
end
# Opens Augeas and returns a handle to use. It loads only the file
# for the current Puppet resource using {AugeasProviders::Provider::ClassMethods#lens}.
# #augsave! is called after the block is evaluated.
#
# If called with a block, this will be yielded to and the Augeas handle.
# Otherwise, the handle will be returned and not closed automatically.
# The handle will be closed by `post_resource_eval`.
#
# @return [Augeas] Augeas handle if no block is given
# @yield [aug, resource, *yield_params] block that uses the Augeas handle
# @yieldparam [Augeas] aug open Augeas handle
# @yieldparam [Puppet::Resource] resource the supplied Puppet resource, passed if `yield_resource` is set to true
# @yieldparam [Splat] *yield_params a splat of additional arguments sent to the block, if `yield_resource` is set to true
# @raise [Puppet::Error] if Augeas did not load the file
# @api public
def augopen!(yield_resource = false, *yield_params, &block)
self.class.augopen!(resource, yield_resource, *yield_params, &block)
end
# Saves all changes made in the current Augeas handle and checks for any
# errors while doing so.
#
# @param [Augeas] aug open Augeas handle
# @param [Boolean] reload whether to reload the tree after saving
# @raise [Augeas::Error] if saving fails
# @api public
def augsave!(aug, reload = false)
self.class.augsave!(aug, reload)
end
# Close the shared Augeas handler.
#
# @param [Augeas] aug open Augeas handle
# @api public
def augclose!(aug)
self.class.augclose!(aug)
end
# Stores and returns a shared Augeas handler for all instances of the class
#
# @return [Augeas] Augeas shared Augeas handle
# @api private
def aug_handler
self.class.aug_handler
end
# Wrapper around Augeas#label for older versions of Augeas
#
# @param [Augeas] aug Augeas handler
# @param [String] path expression to get the label from
# @return [String] label of the given path
# @api public
def path_label(aug, path)
self.class.path_label(aug, path)
end
# Determine which quote is needed
#
# @param [String] value the value to quote
# @param [String] oldvalue the optional old value, used to auto-detect existing quoting
# @return [String] the quoted value
# @api public
def whichquote(value, oldvalue = nil)
self.class.whichquote(value, resource, oldvalue)
end
# Automatically quote a value
#
# @param [String] value the value to quote
# @param [String] oldvalue the optional old value, used to auto-detect existing quoting
# @return [String] the quoted value
# @api public
def quoteit(value, oldvalue = nil)
self.class.quoteit(value, resource, oldvalue)
end
# Detect what type of quoting a value uses
#
# @param [String] value the value to be analyzed
# @return [Symbol] the type of quoting used (:double, :single or nil)
# @api public
def readquote(value)
self.class.readquote(value)
end
# Gets the Augeas path expression representing the individual resource inside
# the file, that represents the current Puppet resource.
#
# If no block was set by the provider's class method, it returns the path
# expression representing the top-level of the file.
#
# @return [String] Augeas path expression to use, e.g. `'/files/etc/hosts/1'`
# @see AugeasProviders::Provider::ClassMethods#resource_path
# @see #target
# @api public
def resource_path
self.class.resource_path(resource)
end
# Sets useful Augeas variables for the session:
#
# * `$target` points to the root of the target file
# * `$resource` points to path defined by #resource_path
#
# It also sets `/augeas/context` to the target file so
# relative paths can be used, before the variables are set.
#
# If supplied with a resource, it will be used to determine the
# path to the used file.
#
# @param [Augeas] aug Augeas handle
# @see #resource_path
# @api public
def setvars(aug)
self.class.setvars(aug, resource)
end
# Gets the path expression representing the file being managed for the
# current Puppet resource.
#
# @return [String] path expression representing the file being managed
# @see AugeasProviders::Provider::ClassMethods#target
# @see #resource_path
# @api public
def target
self.class.target(resource)
end
# Automatically unquote a value
#
# @param [String] value the value to unquote
# @return [String] the unquoted value
# @api public
def unquoteit(value)
self.class.unquoteit(value)
end
# Returns whether text is parsed as path using lens
#
# @param [String] text the text to test
# @param [String] path the relative path to test
# @param [String] lens the lens to use for parsing
# @return [Boolean] whether the path was found when parsing text with lens
# @api public
def parsed_as?(text, path, lens = nil)
lens ||= self.class.lens(resource)
self.class.parsed_as?(text, path, lens)
end
# Default method to determine the existence of a resource
# can be overridden if necessary
def exists?
augopen do |aug|
!aug.match('$resource').empty?
end
end
# Default method to destroy a resource
# can be overridden if necessary
def destroy
augopen! do |aug|
aug.rm('$resource')
end
end
# Default method to flush a resource
#
# Takes care of saving the tree for the shared Augeas handler.
#
# This method can be overridden in your provider
# but you should make sure to call `super`
# to ensure that the tree will be saved.
def flush
augsave!(aug_handler, true)
end
# Returns a node label to use for creating a new entry in an Augeas sequence
# (seq), given the current list, e.g. '1' if it's the first. Supply
# aug.match('$target/*') or similar.
#
# @param [Array<String>] existing paths, from Augeas#match
# @return [String] new node label
def next_seq(matches)
self.class.next_seq(matches)
end
end
@@ -0,0 +1,7 @@
# frozen_string_literal: true
# Dumb augeasprovider type
Puppet::Type.newtype(:augeasprovider) do
@doc = 'Dumb Augeas provider type'
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.
@@ -0,0 +1,306 @@
# Alternative Augeas-based provider for shellvar type
#
# Copyright (c) 2012 Dominic Cleal
# Licensed under the Apache License, Version 2.0
raise('Missing augeasproviders_core dependency') if Puppet::Type.type(:augeasprovider).nil?
Puppet::Type.type(:shellvar).provide(:augeas, parent: Puppet::Type.type(:augeasprovider).provider(:default)) do
desc 'Uses Augeas API to update shell script variables'
confine feature: :augeas
lens { 'Shellvars.lns' }
resource_path do |resource|
if resource.provider.unset_seq?
"$target/#{resource[:variable]}|$target/@unset/*[.='#{resource[:variable]}']"
else
"$target/#{resource[:variable]}|$target/@unset[.='#{resource[:variable]}']"
end
end
def unset_seq?
return @unset_seq unless @unset_seq.nil?
@unset_seq = Puppet::Util::Package.versioncmp(aug_version, '1.2.0') >= 0
@unset_seq ||= parsed_as?("unset FOO\n", '@unset/1')
end
def unset_path
if unset_seq?
"$target/@unset/*[.='#{resource[:variable]}']"
else
"$target/@unset[.='#{resource[:variable]}']"
end
end
def unset_ins_path
if unset_seq?
"$target/@unset[*='#{resource[:variable]}']"
else
"$target/@unset[.='#{resource[:variable]}']"
end
end
def unset_empty
if unset_seq?
'$target/@unset[count(*)=0]/1'
else
"$target/@unset[.='']"
end
end
def unset_purge(aug)
aug.rm('$target/@unset[count(*)=0]') if unset_seq?
end
def array?(path = nil, aug = nil)
if aug.nil? || path.nil?
augopen do |a|
!a.match("$target/#{resource[:variable]}/1").empty?
end
else
!aug.match("$target/#{resource[:variable]}/1").empty?
end
end
def exported?
augopen do |aug|
!aug.match("$target/#{resource[:variable]}/export").empty?
end
end
def unset?
augopen do |aug|
if unset_seq?
!aug.match("$target/@unset/*[.='#{resource[:variable]}']").empty?
else
!aug.match("$target/@unset[.='#{resource[:variable]}']").empty?
end
end
end
def export
augopen! do |aug|
unless aug.match(unset_ins_path).empty?
aug.insert(unset_ins_path, resource[:variable], false)
set_values('$target', aug, resource[:value])
aug.rm(unset_path)
unset_purge(aug)
end
if array?("$target/#{resource[:variable]}", aug)
aug.insert("$target/#{resource[:variable]}/1", 'export', true)
else
aug.clear("$target/#{resource[:variable]}/export")
end
end
end
def unset
augopen! do |aug|
aug.insert("$target/#{resource[:variable]}", '@unset', false)
aug.set(unset_empty, resource[:variable])
aug.rm("$target/#{resource[:variable]}")
end
end
def unexport
augopen! do |aug|
aug.rm("$target/#{resource[:variable]}/export")
# Values may have changed, too
set_values('$target', aug, resource[:value])
end
end
def ununset
augopen! do |aug|
aug.insert(unset_ins_path, resource[:variable], false)
set_values('$target', aug, resource[:value])
aug.rm(unset_path)
unset_purge(aug)
end
end
def array_type(path = nil, aug = nil)
if resource[:array_type] == :auto
if array?(path, aug)
:array
else
:string
end
else
resource[:array_type]
end
end
def get_values(path, aug)
if array?(path, aug)
aug.match('$resource/*').map { |p| aug.get(p) }
else
value = aug.get('$resource')
if value =~ %r{^(["'])(.*)(\1)$}m
value = Regexp.last_match(2)
end
[value]
end
end
def set_values(path, aug, values)
oldvalue = nil
# Detect array type *before* removing subnodes
my_array_type = array_type(path, aug)
# Remove because we might convert an array to a string
# Only remove seq entries, not unless/export
aug.rm("#{path}/#{resource[:variable]}/*[label()=~regexp('^[0-9]+$')]")
case my_array_type
when :string
oldvalue = aug.get("#{path}/#{resource[:variable]}")
# When dealing with array entries
# try hard to keep spacing by using Shellvars_list
aug.rm('/parsed')
aug.set('/input', "#{resource[:variable]}=#{oldvalue}\n")
if values.size > 1 \
&& aug.respond_to?(:text_store) \
&& aug.text_store('Shellvars_list.lns', '/input', '/parsed')
# Replace all values
aug.rm("/parsed/#{resource[:variable]}/value")
# Set automatic quoting
aug.set("/parsed/#{resource[:variable]}/quote", whichquote(values.join(' '), oldvalue))
values.each do |v|
aug.set("/parsed/#{resource[:variable]}/value[last()+1]", v)
end
# Transform back into Shellvars format
aug.text_retrieve('Shellvars_list.lns', '/input', '/parsed', '/newvalue')
newvalue = aug.get('/newvalue').sub("#{resource[:variable]}=", '').chomp
aug.set("#{path}/#{resource[:variable]}", newvalue)
else
aug.set("#{path}/#{resource[:variable]}", quoteit(values.join(' '), oldvalue))
end
when :array
values.each_with_index do |v, i|
aug.set("#{path}/#{resource[:variable]}/#{i}", quoteit(v))
end
end
end
def create
augopen! do |aug|
# Prefer to create the node next to a commented out entry
commented = aug.match("$target/#comment[.=~regexp('#{resource[:variable]}([^a-z.].*)?')]")
commented_values = []
unless commented.empty?
commented_values = if aug.get(commented.first).include?('=')
value = aug.get(commented.first).split('=')[1]
return nil if value.nil?
unquoteit(value).split(' ')
else
unquoteit(aug.get(commented.first)).split(' ')
end
end
comment_ins = '$resource'
if resource[:ensure] == :unset
if unset_seq?
comment_ins = '$resource/..'
end
unless commented.empty?
aug.insert(commented.first, '@unset', false)
aug.rm(commented.first) if resource[:uncomment] == :true
end
aug.set(unset_empty, resource[:variable])
else
unless commented.empty?
aug.insert(commented.first, resource[:variable], false)
aug.rm(commented.first) if resource[:uncomment] == :true
end
values = if resource[:uncomment] == :true
if resource[:value].nil?
# value is not provided
commented_values
elsif resource[:array_append]
# value is provided and merge requested
commented_values | resource[:value]
else
# value is provided and replacement requested
resource[:value]
end
else
resource[:value]
end
set_values('$target', aug, values)
aug.clear("$target/#{resource[:variable]}/export") if resource[:ensure] == :exported
end
setvars(aug)
if resource[:comment]
aug.insert(comment_ins, '#comment', true)
aug.set("$target/#comment[.='']",
"#{resource[:variable]}: #{resource[:comment]}")
end
end
end
def after_comment_node(resource)
if resource[:ensure] == :unset
if unset_seq?
"@unset[*='#{resource[:variable]}']"
else
"@unset[.='#{resource[:variable]}']"
end
else
resource[:variable]
end
end
def destroy
augopen! do |aug|
after_comment = after_comment_node(resource)
aug.rm("$target/#comment[following-sibling::*[1][self::#{after_comment}]][. =~ regexp('#{resource[:variable]}:.*')]")
aug.rm("$target/#{resource[:variable]}")
aug.rm(unset_path)
unset_purge(aug)
end
end
def value
augopen do |aug|
get_values('$target', aug)
end
end
def value=(value)
augopen! do |aug|
set_values('$target', aug, value)
end
end
def comment
augopen do |aug|
after_comment = after_comment_node(resource)
comment = aug.get("$target/#comment[following-sibling::*[1][self::#{after_comment}]][. =~ regexp('#{resource[:variable]}:.*')]")
comment.sub!(%r{^#{resource[:variable]}:\s*}, '') if comment
comment || ''
end
end
def comment=(value)
augopen! do |aug|
after_comment = after_comment_node(resource)
cmtnode = "$target/#comment[following-sibling::*[1][self::#{after_comment}]][. =~ regexp('#{resource[:variable]}:.*')]"
if value.empty?
aug.rm(cmtnode)
else
if aug.match(cmtnode).empty?
aug.insert("$target/#{resource[:variable]}", '#comment', true)
end
aug.set("$target/#comment[following-sibling::*[1][self::#{after_comment}]]",
"#{resource[:variable]}: #{resource[:comment]}")
end
end
end
end
@@ -0,0 +1,222 @@
# Manages variables in simple shell scripts
#
# Copyright (c) 2012 Dominic Cleal
# Licensed under the Apache License, Version 2.0
Puppet::Type.newtype(:shellvar) do
@doc = 'Manages variables in simple shell scripts.'
ensurable do
desc 'Create or remove the shellvar entry'
defaultvalues
block if block_given?
newvalue(:unset) do
current = retrieve
if current == :absent
provider.create
elsif !provider.unset?
provider.unset
@resource.property(:value).sync if @resource.property(:value)
end
end
newvalue(:exported) do
current = retrieve
if current == :absent
provider.create
elsif !provider.exported?
provider.export
@resource.property(:value).sync if @resource.property(:value)
end
end
def insync?(is)
return true if should == :absent && provider.resource[:array_append] && provider.exists?
return true if should == :unset && is == :present && provider.unset?
return true if should == :exported && is == :present && provider.exported?
return false if should == :present && provider.unset?
return false if should == :present && provider.exported?
super
end
def sync
if should == :present && provider.unset?
provider.ununset
elsif should == :present && provider.exported?
provider.unexport
elsif should == :absent && provider.resource[:array_append]
@resource.property(:value).sync
else
super
end
end
end
newparam(:name) do
desc 'The default namevar'
isnamevar
end
newparam(:variable) do
desc 'The name of the variable, e.g. OPTIONS'
isnamevar
end
newproperty(:value, array_matching: :all) do
desc 'Value to change the variable to.'
munge do |v|
v.to_s
end
def insync?(is)
should_arr = Array(should)
# Join and split to ensure all elements are parsed
is_str = is.is_a?(Array) ? is.join(' ') : is
is_arr = is_str.split(' ')
if provider.resource[:array_append] && provider.resource[:ensure] == :absent
(is_arr - (is_arr - should_arr)).empty?
elsif provider.resource[:array_append]
(should_arr - is_arr).empty?
elsif should.size > 1
should_arr == is_arr
else
should == is
end
end
def sync
if provider.resource[:array_append]
is = @resource.property(:value).retrieve
# Join and split to ensure all elements are parsed
is_str = is.is_a?(Array) ? is.join(' ') : is
is_arr = is_str.split(' ')
provider.value = if provider.resource[:ensure] == :absent
# Remove "should" array from "is" array
is_arr - Array(should)
else
# Merge the two arrays
is_arr | Array(should)
end
else
# Use the should array
provider.value = should
end
end
end
newparam(:quoted) do
desc "Quoting method to use, defaults to `auto`.
* `auto` will quote only if necessary, leaving existing quotes as-is
* `double` and `single` will always quotes
* `none` will remove quotes, which may result in save failures"
newvalues :auto, :double, :single, :none, :false, :true
defaultto :auto
munge do |v|
case v
when true, 'true', :true
:auto
when false, 'false', :false
:none
else
v.to_sym
end
end
end
newparam(:array_type) do
desc "Type of array mapping to use, defaults to `auto`.
* `auto` will detect the current type, and default to `string`
* `string` will render the array as a string and use space-separated values
* `array` will render the array as a shell array"
newvalues :auto, :string, :array
defaultto :auto
end
newparam(:array_append) do
desc 'Whether to add to existing array values or replace all values.'
newvalues :false, :true
defaultto :false
munge do |v|
case v
when true, 'true', :true
true
when false, 'false', :false
false
end
end
end
newparam(:target) do
desc 'The file in which to store the variable.'
isnamevar
end
newproperty(:comment) do
desc 'Text to be stored in a comment immediately above the entry.
It will be automatically prepended with the name of the variable in order
for the provider to know whether it controls the comment or not.'
end
newparam(:uncomment) do
desc 'Whether to remove commented value when found.'
newvalues :true, :false
defaultto :false
munge do |v|
case v
when true, 'true', :true
:true
when false, 'false', :false
:false
end
end
end
def self.title_patterns
[
[
%r{^((\S+)\s+in\s+(\S+))$},
[
[:name],
[:variable],
[:target],
],
],
[
%r{((\S+))},
[
[:name],
[:variable],
],
],
[
%r{(.*)},
[
[:name],
],
],
]
end
autorequire(:file) do
self[:target]
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.
@@ -0,0 +1,18 @@
require 'puppet'
class Puppet::Provider::Ceph < Puppet::Provider
initvars
commands :ceph => 'ceph'
protected
# NOTE(tkajinam): JSON outputs from ceph command includes garbage empty lines
def parse_json(value)
JSON.parse(value.gsub(/^$\n/, '').strip)
end
def ceph_cmd(cluster, args)
ceph('--cluster', cluster, *args)
end
end
@@ -0,0 +1,50 @@
# Copyright (C) Dan Bode <bodepd@gmail.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.
#
# Author: Dan Bode <bodepd@gmail.com>
# Author: Andrew Woodward <xarses>
Puppet::Type.type(:ceph_config).provide(
:ini_setting,
:parent => Puppet::Type.type(:ini_setting).provider(:ruby)
) do
def section
resource[:name].split('/', 2).first
end
def setting
resource[:name].split('/', 2).last
end
def separator
' = '
end
def self.file_path
'/etc/ceph/ceph.conf'
end
# required to be able to hack the path in unit tests
# also required if a user wants to otherwise overwrite the default file_path
# Note: purge will not work on over-ridden file_path
def file_path
if not resource[:path]
self.class.file_path
else
resource[:path]
end
end
end
@@ -0,0 +1,58 @@
require 'puppet'
require 'puppet/provider/ceph'
Puppet::Type.type(:ceph_fs).provide(
:ceph,
:parent => Puppet::Provider::Ceph
) do
desc 'Provider for ceph filesystem'
def create
ceph_cmd(@resource[:cluster], ['fs', 'new', @resource[:name], @resource[:metadata_pool_name], @resource[:data_pool_name]])
end
def destroy
ceph_cmd(@resource[:cluster], ['fs', 'rm', @resource[:name], '--yes-i-really-really-mean-it'])
end
def exists?
fs = find_fs
if fs.nil?
return false
end
return true
end
def metadata_pool_name
fs = find_fs
fs['metadata_pool']
end
def data_pool_name
fs = find_fs
# TODO(tkajinam): data pool is a list. Should we support multiple values ?
fs['data_pools'][0]
end
[
:metadata_pool_name,
:data_pool_name,
].each do |attr|
define_method(attr.to_s + "=") do |value|
fail("Property #{attr.to_s} does not support being updated")
end
end
private
def find_fs
fs_list = parse_json(
ceph_cmd(@resource[:cluster], ['fs', 'ls', '-f', 'json']))
fs_list.each do |fs|
if fs['name'] == @resource[:name]
return fs
end
end
return nil
end
end
@@ -0,0 +1,81 @@
require 'puppet'
require 'puppet/provider/ceph'
Puppet::Type.type(:ceph_pool).provide(
:ceph,
:parent => Puppet::Provider::Ceph
) do
desc 'Provider for ceph pools'
def create
args = []
args << @resource[:pg_num]
if @resource[:pgp_num]
args << @resource[:pgp_num]
end
ceph_cmd(@resource[:cluster], ['osd', 'pool', 'create', @resource[:name], *args])
if @resource[:size]
set_pool_property('size', @resource[:size])
end
if @resource[:application]
ceph_cmd(@resource[:cluster], ['osd', 'pool', 'application','enable', @resource[:name], @resource[:application]])
end
end
def destroy
ceph_cmd(@resource[:cluster], ['osd', 'pool', 'delete', @resource[:name], @resource[:name], '--yes-i-really-really-mean-it'])
end
def exists?
pools = parse_json(ceph_cmd(@resource[:cluster], ['osd', 'pool', 'ls', '-f', 'json']))
pools.include?(@resource[:name])
end
def size
get_pool_property('size')
end
def size=(value)
set_pool_property('size', value)
end
def pg_num
get_pool_property('pg_num')
end
def pg_num=(value)
set_pool_property('pg_num', value)
end
def pgp_num
get_pool_property('pgp_num')
end
def pgp_num=(value)
set_pool_property('pgp_num', value)
end
def application
val = parse_json(ceph_cmd(@resource[:cluster], ['osd', 'pool', 'application', 'get', @resource[:name], '-f', 'json']))
val.keys[0]
end
def application=(value)
if application.nil?
ceph_cmd(@resource[:cluster], ['osd', 'pool', 'application', 'enable', @resource[:name], value])
else
raise Puppet::Error, "The pool #{@resource[:name]} already has application set"
end
end
private
def get_pool_property(key)
parse_json(ceph_cmd(@resource[:cluster], ['osd', 'pool', 'get', @resource[:name], key, '-f', 'json']))[key]
end
def set_pool_property(key, value)
ceph_cmd(@resource[:cluster], ['osd', 'pool', 'set', @resource[:name], key, value])
end
end
@@ -0,0 +1,75 @@
# Copyright (C) Dan Bode <bodepd@gmail.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.
#
# Author: Dan Bode <bodepd@gmail.com>
# Author: Mathieu Gagne <mgagne>
Puppet::Type.newtype(:ceph_config) do
ensurable
newparam(:name, :namevar => true) do
desc 'Section/setting name to manage from ./ceph.conf'
newvalues(/\S+\/\S+/)
end
# required in order to be able to unit test file contents
# Note: purge will not work on over-ridden file_path
# lifted from ini_file
newparam(:path) do
desc 'A file path to over ride the default file path if necessary (DEPRECATED)'
validate do |value|
warning('The path property is deprecated and will be removed in a future release')
unless value =~ /^\//
raise(Puppet::Error, "File paths must be fully qualified, not '#{value}'")
end
end
defaultto false
end
newproperty(:value) do
desc 'The value of the setting to be defined.'
munge do |value|
value = value.to_s.strip
value.downcase! if value =~ /^(true|false)$/i
value
end
def is_to_s( currentvalue )
if resource.secret?
return '[old secret redacted]'
else
return currentvalue
end
end
def should_to_s( newvalue )
if resource.secret?
return '[new secret redacted]'
else
return newvalue
end
end
end
newparam(:secret, :boolean => true) do
desc 'Whether to hide the value from Puppet logs. Defaults to `false`.'
newvalues(:true, :false)
defaultto false
end
end
@@ -0,0 +1,59 @@
Puppet::Type.newtype(:ceph_fs) do
ensurable
newparam(:name) do
isnamevar
desc 'Name of the file system'
newvalues(/.+/)
end
newparam(:cluster) do
isnamevar
defaultto 'ceph'
desc 'Name of the cluster'
newvalues(/.+/)
end
newproperty(:metadata_pool_name) do
desc 'Name of the metadata pool'
newvalues(/.+/)
end
newproperty(:data_pool_name) do
desc 'Name of the data pool'
newvalues(/.+/)
end
autorequire(:ceph_pool) do
[self[:metadata_pool_name], self[:data_pool_name]]
end
validate do
if ! self[:metadata_pool_name]
raise(Puppet::Error, 'metadata_pool_name is required')
end
if ! self[:data_pool_name]
raise(Puppet::Error, 'data_pool_name is required')
end
end
def self.title_patterns
cluster = Regexp.new(/[^\/]+/)
name = Regexp.new(/.+/)
[
[
/^(#{cluster})\/(#{name})$/,
[
[:cluster],
[:name]
]
],
[
/^(#{name})$/,
[
[:name]
]
]
]
end
end
@@ -0,0 +1,91 @@
Puppet::Type.newtype(:ceph_pool) do
ensurable
newparam(:name) do
isnamevar
desc 'Name of the pool'
newvalues(/.+/)
end
newparam(:cluster) do
isnamevar
desc 'Name of the cluster'
newvalues(/.+/)
end
newproperty(:pg_num) do
desc 'Number of PGs'
defaultto 64
validate do |v|
if v.is_a?(Integer)
if v <= 0
raise ArgumentError, "Invalid pg_num #{value}. Requires a positive value, not #{value.class}"
end
else
raise ArgumentError, "Invalid pg_num #{value}. Requires an Integer, not a #{value.class}"
end
return true
end
end
newproperty(:pgp_num) do
desc 'Number of PGs for placement'
validate do |v|
if v.is_a?(Integer)
if v <= 0
raise ArgumentError, "Invalid pgp_num #{value}. Requires a positive value, not #{value.class}"
end
else
raise ArgumentError, "Invalid pgp_num #{value}. Requires an Integer, not a #{value.class}"
end
return true
end
end
newproperty(:size) do
desc 'Pool size'
validate do |v|
if v.is_a?(Integer)
if v <= 0
raise ArgumentError, "Invalid size #{value}. Requires a positive value, not #{value.class}"
end
else
raise ArgumentError, "Invalid size #{value}. Requires an Integer, not a #{value.class}"
end
return true
end
end
newproperty(:application) do
desc 'Associated application'
newvalues(/.+/)
end
validate do
if self[:pgp_num]
if self[:pgp_num] > self[:pg_num]
raise(Puppet::Error, 'pgp_num should not exceed pg_num')
end
end
end
def self.title_patterns
cluster = Regexp.new(/[^\/]+/)
name = Regexp.new(/.+/)
[
[
/^(#{cluster})\/(#{name})$/,
[
[:cluster],
[:name]
]
],
[
/^(#{name})$/,
[
[:name]
]
]
]
end
end
@@ -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.
@@ -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,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
@@ -0,0 +1,315 @@
# frozen_string_literal: true
require 'puppet/util/filetype'
# Forward declaration
module PuppetX; end
module PuppetX::FileMapper
# Copy all desired resource properties into this resource for generation upon flush
#
# This method is necessary for the provider to be ensurable
def create
raise Puppet::Error, "#{self.class} is in an error state" if self.class.failed?
@resource.class.validproperties.each do |property|
@property_hash[property] = @resource.should(property) if @resource.should(property)
end
dirty!
end
# Use the prefetched status to determine of the resource exists.
#
# This method is necessary for the provider to be ensurable
#
# @return [TrueClass || FalseClass]
def exists?
@property_hash[:ensure] && @property_hash[:ensure] == :present
end
# Update the property hash to mark this resource as absent for flushing
#
# This method is necessary for the provider to be ensurable
def destroy
@property_hash[:ensure] = :absent
dirty!
end
# Mark the file associated with this resource as dirty
def dirty!
file = select_file
self.class.dirty_file!(file)
end
# When processing on this resource is complete, trigger a flush on the file
# that this resource belongs to.
def flush
self.class.flush_file(select_file)
end
def self.included(klass)
klass.extend PuppetX::FileMapper::ClassMethods
klass.mk_property_methods
klass.initvars
end
module ClassMethods
# @!attribute [rw] unlink_empty_files
# @return [TrueClass || FalseClass] Whether empty files will be removed
attr_accessor :unlink_empty_files
# @!attribute [rw] filetype
# @return [Symbol] The FileType to use when interacting with target files
attr_accessor :filetype
# @!attribute [r] mapped_files
# @return [Hash<filepath => Hash<:dirty => Bool, :filetype => Filetype>>]
# A data structure representing the file paths and filetypes backing this
# provider.
attr_reader :mapped_files
def initvars
super
@mapped_files = Hash.new { |h, k| h[k] = {} }
@unlink_empty_files = false
@filetype = :flat
@failed = false
@all_providers = []
end
def failed?
@failed
end
def failed!
@failed = true
end
# Register all provider instances with the class
#
# In order to flush all provider instances to a given file, we need to be
# able to track them all. When provider#flush is called and the file
# associated with that provider instance is dirty, the file needs to be
# flushed and all provider instances associated with that file will be
# passed to self.flush_file
def new(*args)
obj = super
@all_providers << obj
obj
end
# Returns all instances of the provider using this mixin.
#
# @return [Array<Puppet::Provider>]
def instances
provider_hashes = load_all_providers_from_disk
provider_hashes.map do |h|
h[:provider] = name
h[:ensure] = :present
new(h)
end
rescue StandardError
# If something failed while loading instances, mark the provider class
# as failed and pass the exception along
failed!
raise
end
# Validate that the required methods are available.
#
# @raise Puppet::DevError if an expected method is unavailable
def validate_class!
required_class_hooks = %i[target_files parse_file format_file]
required_instance_hooks = [:select_file]
required_class_hooks.each do |method|
raise Puppet::DevError, "#{self} has not implemented `self.#{method}`" unless respond_to? method
end
required_instance_hooks.each do |method|
raise Puppet::DevError, "#{self} has not implemented `##{method}`" unless method_defined? method
end
end
# Reads all files from disk and returns an array of hashes representing
# provider instances.
#
# @return [Array<Hash<String, Hash<Symbol, Object>>>]
# An array containing a set of hashes, keyed with a file path and values
# being a hash containing the state of the file and the filetype associated
# with it.
#
# @example
# IncludingProvider.load_all_providers_from_disk
# # => [
# # { "/path/to/file" => {
# # :dirty => false,
# # :filetype => #<Puppet::Util::FileTypeFlat:0x007fbf5b05ff10>,
# # },
# # { "/path/to/another/file" => {
# # :dirty => false,
# # :filetype => #<Puppet::Util::FileTypeFlat:0x007fbf5b05c108,
# # },
# #
#
def load_all_providers_from_disk
validate_class!
# Retrieve a list of files to fetch, and cache a copy of a filetype
# for each one
target_files.each do |file|
@mapped_files[file][:filetype] = Puppet::Util::FileType.filetype(filetype).new(file)
@mapped_files[file][:dirty] = false
end
# Read and parse each file.
provider_hashes = []
@mapped_files.each_pair do |filename, file_attrs|
# The filetype path must be a type pathname, or it must respond to to_str
# If it doesn't meet these criteria go to next file
path = file_attrs[:filetype].path
next unless path.is_a?(Pathname) || path.respond_to?(:to_str)
arr = parse_file(filename, file_attrs[:filetype].read)
raise Puppet::DevError, "expected #{self}.parse_file to return an Array, got a #{arr.class}" unless arr.is_a? Array
provider_hashes.concat arr
end
provider_hashes
end
# Match up all resources that have existing providers.
#
# Pass over all provider instances, and see if there is a resource with the
# same namevar as a provider instance. If such a resource exists, set the
# provider field of that resource to the existing provider.
#
# This is a hook method that will be called by Puppet::Transaction#prefetch
#
# @param [Hash<String, Puppet::Resource>] resources
def prefetch(resources = {})
# generate hash of {provider_name => provider}
providers = instances.each_with_object({}) do |instance, hash|
# name is not necessarily the name_var.
# n.b. the following will fall flat for composite namevars.
namevar = resource_type.key_attributes.first
hash[instance.send(namevar)] = instance
end
# For each prefetched resource, try to match it to a provider
resources.each_pair do |resource_name, resource|
resource.provider = providers[resource_name] if providers[resource_name]
end
end
# Create attr_accessors for properties and mark the provider as dirty on change.
def mk_property_methods
resource_type.validproperties.each do |attr|
attr = attr.intern if attr.respond_to?(:intern) && !attr.is_a?(Symbol)
# Generate the attr_reader method
define_method(attr) do
if @property_hash[attr].nil?
:absent
else
@property_hash[attr]
end
end
# Generate the attr_writer and have it mark the resource as dirty when called
define_method("#{attr}=") do |val|
@property_hash[attr] = val
dirty!
end
end
end
# Generate an array of providers that should be flushed to a specific file
#
# Only providers that should be present will be returned regardless of
# the containing file.
#
# @param [String] filename The name of the file to find providers for
#
# @return [Array<Puppet::Provider>]
def collect_providers_for_file(filename)
@all_providers.select do |provider|
provider.select_file == filename && provider.ensure == :present
end
end
def dirty_file!(filename)
@mapped_files[filename][:dirty] = true
end
# Flush provider instances associated with the given file and call any defined hooks
#
# If the provider is in a failure state, the provider class will refuse to
# flush any file, since we're in an unknown state.
#
# This method respects two method hooks: `pre_flush_hook` and `post_flush_hook`.
# These methods must accept one argument, the path of the file being flushed.
# `post_flush_hook` is guaranteed to be called after the flush has occurred.
#
# @param [String] filename The path of the file to be flushed
def flush_file(filename)
if failed?
err "#{name} is in an error state, refusing to flush file #{filename}"
return
end
if @mapped_files[filename][:dirty]
# Collect all providers that should be present and pass them to the
# including class for formatting.
target_providers = collect_providers_for_file(filename)
file_contents = format_file(filename, target_providers)
raise Puppet::DevError, "expected #{self}.format_file to return a String, got a #{file_contents.class}" unless file_contents.is_a? String
# Call the `pre_flush_hook` method if it's defined
pre_flush_hook(filename) if respond_to? :pre_flush_hook
begin
file_contents.empty? && unlink_empty_files ? remove_empty_file(filename) : perform_write(filename, file_contents)
ensure
post_flush_hook(filename) if respond_to? :post_flush_hook
end
else
Puppet.debug "#{name} was requested to flush the file #{filename}, but it was not marked as dirty - doing nothing."
end
rescue StandardError
# If something failed during the flush process, mark the provider as failed. There's not
# much we can do about any file that's already been flushed but we can stop smashing things.
@failed = true
raise
end
# We have a dirty file and the new contents ready, back up the file and perform the flush.
#
# @param [String] filename The destination filename
# @param [String] contents The new file contents
def perform_write(filename, contents)
@mapped_files[filename][:filetype] ||= Puppet::Util::FileType.filetype(filetype).new(filename)
filetype = @mapped_files[filename][:filetype]
filetype.backup if filetype.respond_to? :backup
filetype.write(contents)
end
# Back up and remove a file, if it exists
#
# @param [String] filename The file to remove
def remove_empty_file(filename)
return unless File.exist? filename
@mapped_files[filename][:filetype] ||= Puppet::Util::FileType.filetype(filetype).new(filename)
filetype = @mapped_files[filename][:filetype]
filetype.backup if filetype.respond_to? :backup
File.unlink(filename)
end
end
end
@@ -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.
@@ -0,0 +1,2 @@
class Puppet::Provider::Firewall::Firewall
end
@@ -0,0 +1,2 @@
class Puppet::Provider::Firewallchain::Firewallchain
end
File diff suppressed because it is too large Load Diff
@@ -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.
@@ -0,0 +1,2 @@
Puppet::Type.type(:grafana_plugin).provide(:grafana_cli) do
end
@@ -0,0 +1,187 @@
# frozen_string_literal: true
require 'toml'
require 'puppet/parameter/boolean'
Puppet::Type.newtype(:grafana_ldap_config) do
@doc = 'Manage Grafana LDAP configuration'
@toml_header = <<~EOF
#
# Grafana LDAP configuration
#
# generated by Puppet module puppet-grafana
# https://github.com/voxpupuli/puppet-grafana
#
# *** Edit at your own peril ***
#
# ############################################# #
EOF
# currently not ensurable as we are not parsing the LDAP toml config.
# ensurable
newparam(:title, namevar: true) do
desc 'Path to ldap.toml'
validate do |value|
raise ArgumentError, _('name/title must be a String') unless value.is_a?(String)
end
end
newparam(:owner) do
desc 'Owner of the LDAP configuration-file either as String or Integer (default: root)'
defaultto 'root'
validate do |value|
raise ArgumentError, _('owner must be a String or Integer') unless value.is_a?(String) || value.is_a?(Integer)
end
end
newparam(:group) do
desc 'Group of the LDAP configuration file either as String or Integer (default: grafana)'
defaultto 'grafana'
validate do |value|
raise ArgumentError, _('group must be a String or Integer') unless value.is_a?(String) || value.is_a?(Integer)
end
end
newparam(:mode) do
desc 'File-permissions mode of the LDAP configuration file as String'
defaultto '0440'
validate do |value|
raise ArgumentError, _('file-permissions must be a String') unless value.is_a?(String)
raise ArgumentError, _('file-permissions must be a String') if value.empty?
# regex-pattern stolen from here - all credis to them!
# https://github.com/puppetlabs/puppetlabs-stdlib/blob/master/types/filemode.pp
# currently disabled, as it fails when implicitly called.
#
# raise ArgumentError, _('file-permissions is not valid') unless value.to_s.match(%r{/\A(([0-7]{1,4})|(([ugoa]*([-+=]([rwxXst]*|[ugo]))+|[-+=][0-7]+)(,([ugoa]*([-+=]([rwxXst]*|[ugo]))+|[-+=][0-7]+))*))\z/})
end
end
newparam(:replace, boolean: true, parent: Puppet::Parameter::Boolean) do
desc 'Replace existing files'
defaultto true
end
newparam(:backup, boolean: true, parent: Puppet::Parameter::Boolean) do
desc 'Backup existing files before replacing them into the file-bucket'
defaultto false
end
newparam(:validate_cmd) do
desc 'A command to validate the new Grafana LDAP configuration before actually replacing it'
validate do |value|
raise ArgumentError, _('validate_cmd must be a String or undef') unless value.nil? || value.is_a?(String)
end
end
def ldap_servers
catalog.resources.each_with_object({}) do |resource, memo|
next unless resource.is_a?(Puppet::Type.type(:grafana_ldap_server))
next unless resource[:name].is_a?(String)
memo[resource[:name]] = resource
memo
end
end
def should_content
return @generated_config if @generated_config
@generated_config = {}
ldap_servers.each do |server_k, server_v|
# convert symbols to strings
server_params = server_v.original_parameters.transform_keys(&:to_s)
server_attributes = server_params['attributes']
server_params.delete('attributes')
# grafana-syntax for multiple hosts is a space-separate list.
server_params['host'] = server_params['hosts'].join(' ')
server_params.delete('hosts')
server_group_mappings = server_v.group_mappings
server_block = {
'servers' => [server_params],
'servers.attributes' => server_attributes,
'servers.group_mappings' => server_group_mappings
}.compact
@generated_config[server_k] = server_block
end
@generated_config.compact
end
def generate
file_opts = {}
# currently not ensurable
# file_opts = {
# ensure: (self[:ensure] == :absent) ? :absent : :file,
# }
[:name,
:owner,
:group,
:mode,
:replace,
:backup,
# this we have currently not implemented
# :selinux_ignore_defaults,
# :selrange,
# :selrole,
# :seltype,
# :seluser,
# :show_diff,
:validate_cmd].each do |param|
file_opts[param] = self[param] unless self[param].nil?
end
metaparams = Puppet::Type.metaparams
excluded_metaparams = %w[before notify require subscribe tag]
metaparams.reject! { |param| excluded_metaparams.include? param }
metaparams.each do |metaparam|
file_opts[metaparam] = self[metaparam] unless self[metaparam].nil?
end
[Puppet::Type.type(:file).new(file_opts)]
end
def eval_generate
ldap_servers = should_content
if !ldap_servers.nil? && !ldap_servers.empty?
toml_contents = []
toml_contents << @toml_header
toml_contents << ldap_servers.map do |k, v|
str = []
str << "\n\n"
str << <<~EOF
#
# #{k}
#
EOF
str << TOML::Generator.new(v).body
str.join
end
catalog.resource("File[#{self[:name]}]")[:content] = toml_contents.join
end
[catalog.resource("File[#{self[:name]}]")]
end
autonotify(:class) do
'grafana::service'
end
end
@@ -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.
@@ -0,0 +1,154 @@
# frozen_string_literal: true
require File.expand_path('../../util/ini_file', __dir__)
Puppet::Type.type(:ini_setting).provide(:ruby) do
def self.instances
desc '
Creates new ini_setting file, a specific config file with a provider that uses
this as its parent and implements the method
self.file_path, and that will provide the value for the path to the
ini file.'
raise(Puppet::Error, 'Ini_settings only support collecting instances when a file path is hard coded') unless respond_to?(:file_path)
# figure out what to do about the seperator
ini_file = Puppet::Util::IniFile.new(file_path, '=')
resources = []
ini_file.section_names.each do |section_name|
ini_file.get_settings(section_name).each do |setting, value|
resources.push(
new(
name: namevar(section_name, setting),
value: value,
ensure: :present,
),
)
end
end
resources
end
def self.namevar(section_name, setting)
setting.nil? ? section_name : "#{section_name}/#{setting}"
end
def exists?
if setting.nil?
ini_file.section_names.include?(section)
elsif ini_file.section?(section)
!ini_file.get_value(section, setting).nil?
elsif resource.parameters.key?(:force_new_section_creation) && !resource[:force_new_section_creation]
# for backwards compatibility, if a user is using their own ini_setting
# types but does not have this parameter, we need to fall back to the
# previous functionality which was to create the section. Anyone
# wishing to leverage this setting must define it in their provider
# type. See comments on
# https://github.com/puppetlabs/puppetlabs-inifile/pull/286
resource[:ensure] = :absent
resource[:force_new_section_creation]
elsif resource.parameters.key?(:force_new_section_creation) && resource[:force_new_section_creation]
!resource[:force_new_section_creation]
else
false
end
end
def create
if setting.nil? && resource[:value].nil?
ini_file.set_value(section)
else
ini_file.set_value(section, setting, separator, resource[:value])
end
ini_file.save
@ini_file = nil
end
def destroy
ini_file.remove_setting(section, setting)
ini_file.save
@ini_file = nil
end
def value
ini_file.get_value(section, setting)
end
def value=(_value)
if setting.nil? && resource[:value].nil?
ini_file.set_value(section)
else
ini_file.set_value(section, setting, separator, resource[:value])
end
ini_file.save
end
def section
# this method is here so that it can be overridden by a child provider
resource[:section]
end
def setting
# this method is here so that it can be overridden by a child provider
resource[:setting]
end
def file_path
# this method is here to support purging and sub-classing.
# if a user creates a type and subclasses our provider and provides a
# 'file_path' method, then they don't have to specify the
# path as a parameter for every ini_setting declaration.
# This implementation allows us to support that while still
# falling back to the parameter value when necessary.
if self.class.respond_to?(:file_path)
self.class.file_path
else
resource[:path]
end
end
def separator
if resource.class.validattr?(:key_val_separator)
resource[:key_val_separator] || '='
else
'='
end
end
def section_prefix
if resource.class.validattr?(:section_prefix)
resource[:section_prefix] || '['
else
'['
end
end
def section_suffix
if resource.class.validattr?(:section_suffix)
resource[:section_suffix] || ']'
else
']'
end
end
def indent_char
if resource.class.validattr?(:indent_char)
resource[:indent_char] || ' '
else
' '
end
end
def indent_width
if resource.class.validattr?(:indent_width)
resource[:indent_width] || nil
else
nil
end
end
private
def ini_file
@ini_file ||= Puppet::Util::IniFile.new(file_path, separator, section_prefix, section_suffix, indent_char, indent_width)
end
end
@@ -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,32 @@
# frozen_string_literal: true
module Puppet::Util # rubocop:disable Style/ClassAndModuleChildren
#
# external_iterator.rb
#
class ExternalIterator
def initialize(coll)
@coll = coll
@cur_index = -1
end
def next
@cur_index += 1
item_at(@cur_index)
end
def peek
item_at(@cur_index + 1)
end
private
def item_at(index)
if @coll.length > index
[@coll[index], index]
else
[nil, nil]
end
end
end
end
@@ -0,0 +1,338 @@
# frozen_string_literal: true
require File.expand_path('external_iterator', __dir__)
require File.expand_path('ini_file/section', __dir__)
module Puppet::Util # rubocop:disable Style/ClassAndModuleChildren
#
# ini_file.rb
#
class IniFile
def initialize(path, key_val_separator = ' = ', section_prefix = '[', section_suffix = ']',
indent_char = ' ', indent_width = nil)
k_v_s = (key_val_separator =~ %r{^\s+$}) ? ' ' : key_val_separator.strip
@section_prefix = section_prefix
@section_suffix = section_suffix
@indent_char = indent_char
@indent_width = indent_width&.to_i
@section_regex = section_regex
@setting_regex = %r{^(\s*)([^#;\s]|[^#;\s].*?[^\s#{k_v_s}])(\s*#{k_v_s}[ \t]*)(.*)\s*$}
@commented_setting_regex = %r{^(\s*)[#;]+(\s*)(.*?[^\s#{k_v_s}])(\s*#{k_v_s}[ \t]*)(.*)\s*$}
@path = path
@key_val_separator = key_val_separator
@section_names = []
@sections_hash = {}
parse_file
end
def section_regex
# Only put in prefix/suffix if they exist
r_string = '^\s*'
r_string += Regexp.escape(@section_prefix)
r_string += '(.*)'
r_string += Regexp.escape(@section_suffix)
r_string += '\s*$'
%r{#{r_string}}
end
attr_reader :section_names
def get_settings(section_name)
section = @sections_hash[section_name]
section.setting_names.each_with_object({}) do |setting, result|
result[setting] = section.get_value(setting)
end
end
def section?(section_name)
@sections_hash.key?(section_name)
end
def get_value(section_name, setting)
@sections_hash[section_name].get_value(setting) if @sections_hash.key?(section_name)
end
def set_value(*args)
case args.size
when 1
section_name = args[0]
when 3
# Backwards compatible set_value function, See MODULES-5172
(section_name, setting, value) = args
when 4
(section_name, setting, separator, value) = args
end
complete_setting = {
setting: setting,
separator: separator,
value: value
}
add_section(Section.new(section_name, nil, nil, nil, nil)) unless @sections_hash.key?(section_name)
section = @sections_hash[section_name]
if section.existing_setting?(setting)
update_line(section, setting, value)
section.update_existing_setting(setting, value)
elsif find_commented_setting(section, setting)
# So, this stanza is a bit of a hack. What we're trying
# to do here is this: for settings that don't already
# exist, we want to take a quick peek to see if there
# is a commented-out version of them in the section.
# If so, we'd prefer to add the setting directly after
# the commented line, rather than at the end of the section.
# If we get here then we found a commented line, so we
# call "insert_inline_setting_line" to update the lines array
insert_inline_setting_line(find_commented_setting(section, setting), section, complete_setting)
# Then, we need to tell the setting object that we hacked
# in an inline setting
section.insert_inline_setting(setting, value)
# Finally, we need to update all of the start/end line
# numbers for all of the sections *after* the one that
# was modified.
section_index = @section_names.index(section_name)
increment_section_line_numbers(section_index + 1)
elsif !setting.nil? || !value.nil?
section.set_additional_setting(setting, value)
end
end
def remove_setting(section_name, setting)
section = @sections_hash[section_name]
return unless section.existing_setting?(setting)
# If the setting is found, we have some work to do.
# First, we remove the line from our array of lines:
remove_line(section, setting)
# Then, we need to tell the setting object to remove
# the setting from its state:
section.remove_existing_setting(setting)
# Finally, we need to update all of the start/end line
# numbers for all of the sections *after* the one that
# was modified.
section_index = @section_names.index(section_name)
decrement_section_line_numbers(section_index + 1)
return unless section.empty?
# By convention, it's time to remove this newly emptied out section
lines.delete_at(section.start_line)
decrement_section_line_numbers(section_index + 1)
@section_names.delete_at(section_index)
@sections_hash.delete(section.name)
end
def save
global_empty = @sections_hash[''].empty? && @sections_hash[''].additional_settings.empty?
File.open(@path, 'w') do |fh|
@section_names.each_index do |index|
name = @section_names[index]
section = @sections_hash[name]
# We need a buffer to cache lines that are only whitespace
whitespace_buffer = []
if section.new_section? && !section.global?
fh.puts('') if (index == 1 && !global_empty) || index > 1
fh.puts("#{@section_prefix}#{section.name}#{@section_suffix}")
end
unless section.new_section?
# write all of the pre-existing lines
(section.start_line..section.end_line).each do |line_num|
line = lines[line_num]
# We buffer any lines that are only whitespace so that
# if they are at the end of a section, we can insert
# any new settings *before* the final chunk of whitespace
# lines.
if line.match?(%r{^\s*$})
whitespace_buffer << line
else
# If we get here, we've found a non-whitespace line.
# We'll flush any cached whitespace lines before we
# write it.
flush_buffer_to_file(whitespace_buffer, fh)
fh.puts(line)
end
end
end
# write new settings, if there are any
section.additional_settings.each_pair do |key, value|
fh.puts("#{@indent_char * (@indent_width || section.indentation || 0)}#{key}#{@key_val_separator}#{value}")
end
if !whitespace_buffer.empty?
flush_buffer_to_file(whitespace_buffer, fh)
elsif section.new_section? && !section.additional_settings.empty? && (index < @section_names.length - 1)
# We get here if there were no blank lines at the end of the
# section.
#
# If we are adding a new section with a new setting,
# and if there are more sections that come after this one,
# we'll write one blank line just so that there is a little
# whitespace between the sections.
# if (section.end_line.nil? &&
fh.puts('')
end
end
end
end
private
def add_section(section)
@sections_hash[section.name] = section
@section_names << section.name
end
def parse_file
line_iter = create_line_iter
# We always create a "global" section at the beginning of the file, for
# anything that appears before the first named section.
section = read_section('', 0, line_iter)
add_section(section)
line, line_num = line_iter.next
while line
if (match = @section_regex.match(line))
section = read_section(match[1], line_num, line_iter)
add_section(section)
end
line, line_num = line_iter.next
end
end
def read_section(name, start_line, line_iter)
settings = {}
end_line_num = start_line
min_indentation = nil
empty = true
empty_line_count = 0
loop do
line, line_num = line_iter.peek
if line_num.nil? || @section_regex.match(line)
# the global section always exists, even when it's empty;
# when it's empty, we must be sure it's thought of as new,
# which is signalled with a nil ending line
end_line_num = nil if name == '' && empty
return Section.new(name, start_line, end_line_num, settings, min_indentation, empty_line_count)
end
if (match = @setting_regex.match(line))
settings[match[2]] = match[4]
indentation = match[1].length
min_indentation = [indentation, min_indentation || indentation].min
end
end_line_num = line_num
empty_line_count += 1 if line == "\n"
empty = false
line_iter.next
end
end
def update_line(section, setting, value)
(section.start_line..section.end_line).each do |line_num|
next unless (match = @setting_regex.match(lines[line_num]))
lines[line_num] = "#{match[1]}#{match[2]}#{match[3]}#{value}" if match[2] == setting
end
end
def remove_line(section, setting)
(section.start_line..section.end_line).each do |line_num|
next unless (match = @setting_regex.match(lines[line_num]))
lines.delete_at(line_num) if match[2] == setting
end
end
def create_line_iter
ExternalIterator.new(lines)
end
def lines
@lines ||= IniFile.readlines(@path)
end
# This is mostly here because it makes testing easier--we don't have
# to try to stub any methods on File.
def self.readlines(path) # rubocop:disable Lint/IneffectiveAccessModifier : Attempting to change breaks tests
# If this type is ever used with very large files, we should
# write this in a different way, using a temp
# file; for now assuming that this type is only used on
# small-ish config files that can fit into memory without
# too much trouble.
File.file?(path) ? File.readlines(path) : []
end
# This utility method scans through the lines for a section looking for
# commented-out versions of a setting. It returns `nil` if it doesn't
# find one. If it does find one, then it returns a hash containing
# two keys:
#
# :line_num - the line number that contains the commented version
# of the setting
# :match - the ruby regular expression match object, which can
# be used to mimic the whitespace from the comment line
def find_commented_setting(section, setting)
return nil if section.new_section?
(section.start_line..section.end_line).each do |line_num|
next unless (match = @commented_setting_regex.match(lines[line_num]))
return { match: match, line_num: line_num } if match[3] == setting
end
nil
end
# This utility method is for inserting a line into the existing
# lines array. The `result` argument is expected to be in the
# format of the return value of `find_commented_setting`.
def insert_inline_setting_line(result, section, complete_setting)
line_num = result[:line_num]
s = complete_setting
lines.insert(line_num + 1, "#{@indent_char * (@indent_width || section.indentation || 0)}#{s[:setting]}#{s[:separator]}#{s[:value]}")
end
# Utility method; given a section index (index into the @section_names
# array), decrement the start/end line numbers for that section and all
# all of the other sections that appear *after* the specified section.
def decrement_section_line_numbers(section_index)
@section_names[section_index..(@section_names.length - 1)].each do |name|
section = @sections_hash[name]
section.decrement_line_nums
end
end
# Utility method; given a section index (index into the @section_names
# array), increment the start/end line numbers for that section and all
# all of the other sections that appear *after* the specified section.
def increment_section_line_numbers(section_index)
@section_names[section_index..(@section_names.length - 1)].each do |name|
section = @sections_hash[name]
section.increment_line_nums
end
end
def flush_buffer_to_file(buffer, file)
return if buffer.empty?
buffer.each { |l| file.puts(l) }
buffer.clear
end
end
end
@@ -0,0 +1,96 @@
# frozen_string_literal: true
class Puppet::Util::IniFile # rubocop:disable Style/ClassAndModuleChildren
#
# section.rb
#
class Section
# Some implementation details:
#
# * `name` will be set to the empty string for the 'global' section.
# * there will always be a 'global' section, with a `start_line` of 0,
# but if the file actually begins with a real section header on
# the first line, then the 'global' section will have an
# `end_line` of `nil`.
# * `start_line` and `end_line` will be set to `nil` for a new non-global
# section.
def initialize(name, start_line, end_line, settings, indentation, empty_line_count = 0)
@name = name
@start_line = start_line
@end_line = end_line
@existing_settings = settings.nil? ? {} : settings
@additional_settings = {}
@indentation = indentation
@empty_line_count = empty_line_count
end
attr_reader :name, :start_line, :end_line, :additional_settings, :indentation
def global?
@name == ''
end
def new_section?
# a new section (global or named) will always have `end_line`
# set to `nil`
@end_line.nil?
end
def setting_names
@existing_settings.keys | @additional_settings.keys
end
def get_value(setting_name)
@existing_settings[setting_name] || @additional_settings[setting_name]
end
def existing_setting?(setting_name)
@existing_settings.key?(setting_name)
end
# the global section is empty whenever it's new;
# other sections are empty when they have no lines
def empty?
global? ? new_section? : (start_line == end_line || (end_line && (end_line - @empty_line_count)) == start_line)
end
def update_existing_setting(setting_name, value)
@existing_settings[setting_name] = value
end
def remove_existing_setting(setting_name)
@end_line -= 1 if @existing_settings.delete(setting_name) && @end_line
end
# This is a hacky method; it's basically called when we need to insert
# a new setting but we don't want it to appear at the very end of the
# section. Instead we hack it into the existing settings list and
# increment our end_line number--this assumes that the caller (`ini_file`)
# is doing some babysitting w/rt the other sections and the actual data
# of the lines.
def insert_inline_setting(setting_name, value)
@existing_settings[setting_name] = value
@end_line += 1 if @end_line
end
def set_additional_setting(setting_name, value)
@additional_settings[setting_name] = value
end
# Decrement the start and end line numbers for the section (if they are
# defined); this is intended to be called when a setting is removed
# from a section that comes before this section in the ini file.
def decrement_line_nums
@start_line -= 1 if @start_line
@end_line -= 1 if @end_line
end
# Increment the start and end line numbers for the section (if they are
# defined); this is intended to be called when an inline setting is added
# to a section that comes before this section in the ini file.
def increment_line_nums
@start_line += 1 if @start_line
@end_line += 1 if @end_line
end
end
end
@@ -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.
@@ -0,0 +1,4 @@
require 'puppet/resource_api/simple_provider'
class Puppet::Provider::MinioClientAlias::MinioClientAlias < Puppet::ResourceApi::SimpleProvider
end
@@ -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.
@@ -0,0 +1,2 @@
class Puppet::Provider::MysqlLoginPath::IniFile < Puppet::Provider
end
@@ -0,0 +1,4 @@
require 'puppet/resource_api/simple_provider'
class Puppet::Provider::MysqlLoginPath::MysqlLoginPath < Puppet::ResourceApi::SimpleProvider
end
@@ -0,0 +1,2 @@
class Puppet::Provider::MysqlLoginPath::Sensitive < Puppet::Pops::Types::PSensitiveType::Sensitive
end
@@ -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
@@ -0,0 +1,320 @@
require 'puppetx/filemapper'
Puppet::Type.type(:network_config).provide(:interfaces) do
# Debian network_config interfaces provider.
#
# This provider uses the filemapper mixin to map the interfaces file to a
# collection of network_config providers, and back.
#
# @see http://wiki.debian.org/NetworkConfiguration
# @see http://packages.debian.org/squeeze/ifupdown
include PuppetX::FileMapper
desc 'Debian interfaces style provider'
confine osfamily: :debian
defaultfor osfamily: :debian
has_feature :provider_options
has_feature :hotpluggable
def select_file
'/etc/network/interfaces'
end
def self.target_files
['/etc/network/interfaces']
end
class MalformedInterfacesError < Puppet::Error
def initialize(msg = nil)
msg ||= 'Malformed debian interfaces file; cannot instantiate network_config resources'
super
end
end
def self.raise_malformed
@failed = true
raise MalformedInterfacesError
end
class Instance
attr_reader :name
# Booleans
attr_accessor :onboot, :hotplug
# These fields are going to get rearranged to resolve issue 16
# https://github.com/adrienthebo/puppet-network/issues/16
attr_accessor :ipaddress, :netmask, :family, :method, :mtu, :mode
# Options hash
attr_reader :options
def initialize(name)
@name = name
@options = Hash.new { |hash, key| hash[key] = [] }
end
def to_hash
h = {
name: @name,
onboot: @onboot,
hotplug: @hotplug,
ipaddress: @ipaddress,
netmask: @netmask,
family: @family,
method: @method,
mtu: @mtu,
mode: @mode,
options: squeeze_options
}
h.each_with_object({}) do |(key, val), hash|
hash[key] = val if val
end
end
def squeeze_options
@options.each_with_object({}) do |(key, value), hash|
hash[key] = if value.size <= 1
value.pop
else
value
end
hash
end
end
class << self
def reset!
@interfaces = {}
end
# @return [Array<Instance>] All class instances
def all_instances
@interfaces ||= {}
@interfaces
end
def [](name)
if all_instances[name]
obj = all_instances[name]
else
obj = new(name)
all_instances[name] = obj
end
obj
end
end
end
def self.parse_file(_filename, contents)
# Debian has a very irregular format for the interfaces file. The
# parse_file method is somewhat derived from the ifup executable
# supplied in the debian ifupdown package. The source can be found at
# http://packages.debian.org/squeeze/ifupdown
# The debian interfaces implementation requires global state while parsing
# the file; namely, the stanza being parsed as well as the interface being
# parsed.
status = :none
current_interface = nil
lines = contents.split("\n")
# TODO: Join lines that end with a backslash
# Iterate over all lines and determine what attributes they create
lines.each do |line|
# Strip off any trailing comments
line.sub!(%r{#.*$}, '')
case line
when %r{^\s*#|^\s*$}
# Ignore comments and blank lines
next
when %r{^source|^source-directory}
# ignore source|source-directory sections, it makes this provider basically useless
# with Debian Jessie. Please refer to man 5 interfaces
next
when %r{^auto|^allow-auto}
# Parse out any auto sections
interfaces = line.split(' ')
interfaces.delete_at(0)
interfaces.each do |name|
Instance[name].onboot = true
end
# Reset the current parse state
current_interface = nil
when %r{^allow-hotplug}
# parse out allow-hotplug lines
interfaces = line.split(' ')
interfaces.delete_at(0)
interfaces.each do |name|
Instance[name].hotplug = true
end
# Don't reset Reset the current parse state
when %r{^iface}
# Format of the iface line:
#
# iface <iface> <family> <method>
# zero or more options for <iface>
raise_malformed unless line.match(%r{^iface\s+(\S+)\s+(\S+)\s+(\S+)}) do |matched|
name = matched[1]
family = matched[2]
method = matched[3]
# If an iface block for this interface has been seen, the file is
# malformed.
raise_malformed if Instance[name] && Instance[name].family
status = :iface
current_interface = name
# This is done automatically
# Instance[name].name = name
Instance[name].family = family
Instance[name].method = method
# for the vlan naming conventions (a mess), see
# man 5 vlan-interfaces
Instance[name].mode = case name
# 'vlan22'
when %r{^vlan}
:vlan
# 'eth2.0003' or 'br1.2'
when %r{^[a-z]{1,}[0-9]{1,}\.[0-9]{1,4}}
:vlan
else
:raw
end
end
when %r{^mapping}
# XXX dox
status = :mapping
raise Puppet::DevError, 'Debian interfaces mapping parsing not implemented.'
else
# We're currently examining a line that is within a mapping or iface
# stanza, so we need to validate the line and add the options it
# specifies to the known state of the interface.
case status
when :iface
raise_malformed unless line.match(%r{(\S+)\s+(\S.*)}) do |matched|
# If we're parsing an iface stanza, then we should receive a set of
# lines that contain two or more space delimited strings. Append
# them as options to the iface in an array.
key = matched[1]
val = matched[2]
name = current_interface
case key # rubocop:disable Metrics/BlockNesting
when 'address' then Instance[name].ipaddress = val
when 'netmask' then Instance[name].netmask = val
when 'mtu' then Instance[name].mtu = val
else Instance[name].options[key] << val
end
end
when :mapping
raise Puppet::DevError, 'Debian interfaces mapping parsing not implemented.'
when :none
raise_malformed
end
end
end
Instance.all_instances.map { |_name, instance| instance.to_hash }
end
# Generate an array of sections
def self.format_file(_filename, providers)
contents = []
contents << header
# Add onboot interfaces
auto_interfaces = providers.select { |provider| provider.onboot == true }
unless auto_interfaces.empty?
stanza = []
stanza << ('auto ' + auto_interfaces.map(&:name).sort.join(' '))
contents << stanza.join("\n")
end
# Add hotpluggable interfaces
hotplug_interfaces = providers.select { |provider| provider.hotplug == true }
unless hotplug_interfaces.empty?
stanza = []
stanza << ('allow-hotplug ' + hotplug_interfaces.map(&:name).sort.join(' '))
contents << stanza.join("\n")
end
# Build iface stanzas
providers.sort_by(&:name).each do |provider|
# TODO: add validation method
raise Puppet::Error, "#{provider.name} does not have a method." if provider.method.nil?
raise Puppet::Error, "#{provider.name} does not have a family." if provider.family.nil?
stanza = []
stanza << %(iface #{provider.name} #{provider.family} #{provider.method})
# add the vlan-raw-device only when explicitely set in interfaces(5) stanza
# otherwise it's already assumed given the stanza name (ethX.NN)
if provider.mode == :vlan
if provider.options['vlan-raw-device']
stanza << "vlan-raw-device #{provider.options['vlan-raw-device']}"
else
vlan_range_regex = %r{[1-3]?\d{1,3}|40[0-8]\d|409[0-5]}
raise Puppet::Error, "Interface #{provider.name}: missing vlan-raw-device or wrong VLAN ID in the iface name " unless provider.name =~ %r{\A([a-z]+\d+)(?::\d+|\.#{vlan_range_regex})\Z}
end
end
[
[:ipaddress, 'address'],
[:netmask, 'netmask'],
[:mtu, 'mtu']
].each do |(property, section)|
stanza << "#{section} #{provider.send property}" if provider.send(property) && provider.send(property) != :absent
end
if provider.options && provider.options != :absent
provider.options.each_pair do |key, val|
if val.is_a? String
# dont print property because we've already added it to the stanza
stanza << " #{key} #{val}" if key != 'vlan-raw-device'
elsif val.is_a? Array
val.each { |entry| stanza << " #{key} #{entry}" }
else
raise Puppet::Error, "#{self} options key #{key} expects a String or Array, got #{val.class}"
end
end
end
contents << stanza.join("\n")
end
contents.map { |line| line + "\n\n" }.join
end
def self.header
<<~HEADER
# HEADER: This file is being managed by puppet. Changes to
# HEADER: interfaces that are not being managed by puppet will persist;
# HEADER: however changes to interfaces that are being managed by puppet will
# HEADER: be overwritten. In addition, file order is NOT guaranteed.
# HEADER: Last generated at: #{Time.now}
HEADER
end
end
@@ -0,0 +1,242 @@
require 'puppetx/filemapper'
Puppet::Type.type(:network_config).provide(:redhat) do
# Red Hat network_config network scripts provider.
#
# This provider manages the contents of /etc/networks-scripts/ifcfg-* to
# manage non-volatile network configuration.
#
# @see https://access.redhat.com/knowledge/docs/en-US/Red_Hat_Enterprise_Linux/6/html/Deployment_Guide/s1-networkscripts-interfaces.html "Red Hat Interface Configuration Files"
include PuppetX::FileMapper
desc 'Redhat network-scripts provider'
confine osfamily: :redhat
defaultfor osfamily: :redhat
has_feature :hotpluggable
has_feature :provider_options
# @return [String] The path to network-script directory on redhat systems
SCRIPT_DIRECTORY = '/etc/sysconfig/network-scripts'.freeze
# The valid vlan ID range is 0-4095; 4096 is out of range
VLAN_RANGE_REGEX = %r{[1-3]?\d{1,3}|40[0-8]\d|409[0-5]}
# aliases are almost free game, redhat rejects some, and max total length is 15 characters
# 15 minus at least 2 for the interface name, and a colon leaves 12 characters for the alias
ALIAS_REGEX = %r{.{1,12}(?<!~|\.bak|\.old|\.orig|\.rpmnew|\.rpmorig|\.rpmsave)}
# @return [Regexp] The regular expression for interface scripts on redhat systems
SCRIPT_REGEX = %r{\Aifcfg-[a-z]+[a-z_\d]+(?::#{ALIAS_REGEX}|\.#{VLAN_RANGE_REGEX})?\Z}
NAME_MAPPINGS = {
ipaddress: 'IPADDR',
netmask: 'NETMASK',
method: 'BOOTPROTO',
onboot: 'ONBOOT',
name: 'DEVICE',
hotplug: 'HOTPLUG',
mtu: 'MTU'
}.freeze
# Map provider instances to files based on their name
#
# @return [String] The path of the file for the given interface resource
#
# @example
# prov = RedhatProvider.new(:name => 'eth1')
# prov.select_file # => '/etc/sysconfig/network-scripts/ifcfg-eth1'
#
def select_file
"#{SCRIPT_DIRECTORY}/ifcfg-#{name}"
end
# Scan all files in the networking directory for interfaces
#
# @param script_dir [String] The path to the networking scripts, defaults to
# {#SCRIPT_DIRECTORY}
#
# @return [Array<String>] All network-script config files on this machine.
#
# @example
# RedhatProvider.target_files
# # => ['/etc/sysconfig/network-scripts/ifcfg-eth0', '/etc/sysconfig/network-scripts/ifcfg-eth1']
def self.target_files(script_dir = SCRIPT_DIRECTORY)
entries = Dir.entries(script_dir).select { |entry| entry.match SCRIPT_REGEX }
entries.map { |entry| File.join(SCRIPT_DIRECTORY, entry) }
end
# Convert a redhat network script into a hash
#
# This is a hook method that will be called by PuppetX::Filemapper
#
# @param [String] filename The path of the interfaces file being parsed
# @param [String] contents The contents of the given file
#
# @return [Array<Hash<Symbol, String>>] A single element array containing
# the key/value pairs of properties parsed from the file.
#
# @example
# RedhatProvider.parse_file('/etc/sysconfig/network-scripts/ifcfg-eth0', #<String:0xdeadbeef>)
# # => [
# # {
# # :name => 'eth0',
# # :ipaddress => '169.254.0.1',
# # :netmask => '255.255.0.0',
# # },
# # ]
def self.parse_file(filename, contents)
# Split up the file into lines
lines = contents.split("\n")
# Strip out all comments
lines.map! { |line| line.sub(%r{#.*$}, '') }
# Remove all blank lines
lines.reject! { |line| line =~ %r{^\s*$} }
pair_regex = %r{^\s*(.+?)\s*=\s*(.*)\s*$}
# INFO: It is valid ifcfg format to include certain functions and strings these should not be reported as errors, but silently removed before parsing
# https://bugs.centos.org/bug_view_page.php?bug_id=475
# Remove lines with no = sign
lines.select! { |line| line =~ %r{^.*=.*$} }
# Convert the data into key/value pairs
pairs = lines.each_with_object({}) do |line, hash|
raise Puppet::Error, %(#{filename} is malformed; "#{line}" did not match "#{pair_regex}") unless line.match(pair_regex) do |m|
key = m[1].strip
val = m[2].strip
hash[key] = val
end
hash
end
props = munge(pairs)
# TODO: remove duct tape for #13
#
# The :family property is making less and less sense because it seems that
# ipv6 configuration should add new properties instead of trying to collide
# with the ipv4 addresses. But right now, the :inet property is never used
# and it's creating a change on each resource update. This is a patch until
# the :family property is ripped out.
#
# See https://github.com/adrienthebo/puppet-network/issues/13 for the full
# issue that caused this, and https://github.com/adrienthebo/puppet-network/issues/16
# for the resolution.
#
props[:family] = :inet
# If there is no DEVICE property in the interface configuration we retrieve
# the interface name from the file name itself
props[:name] = filename.split('ifcfg-')[1] unless props.key?(:name)
# The FileMapper mixin expects an array of providers, so we return the
# single interface wrapped in an array
[props]
end
# @api private
def self.munge(pairs)
props = {}
# Unquote all values
pairs.each_pair do |key, val|
if (munged = val.gsub(%r{['"]}, ''))
pairs[key] = munged
end
end
# For each interface attribute that we recognize it, add the value to the
# hash with our expected label
NAME_MAPPINGS.each_pair do |type_name, redhat_name|
next unless (val = pairs[redhat_name])
pairs.delete(redhat_name)
props[type_name] = val
end
# if we encounter VLAN=yes set the interface mode to :vlan
pairs.each_pair do |key, val|
props[:mode] = :vlan if key == 'VLAN' && val == 'yes'
end
pairs.delete('VLAN')
# mode is a property so it should always have a value
props[:mode] ||= :raw
# For all of the remaining values, blindly toss them into the options hash.
props[:options] = pairs
%i[onboot hotplug].each do |bool_property|
props[bool_property] = (props[bool_property] == 'yes') unless props[bool_property].nil?
end
props[:method] = 'static' unless %w[bootp dhcp].include? props[:method]
props
end
def self.format_file(filename, providers)
return '' if providers.empty?
if providers.length > 1
raise Puppet::DevError,
"Unable to support multiple interfaces [#{providers.map(&:name).join(',')}] in a single file #{filename}"
end
provider = providers[0]
props = {}
props = provider.options if provider.options && provider.options != :absent
# Map everything to a flat hash
NAME_MAPPINGS.keys.each do |type_name|
if (val = provider.send(type_name)) && val != :absent
props[type_name] = val
end
end
# :mode does not exist in NAME_MAPPINGS so we have to fetch it manually
# note that the inverse operation is in .munge instead of parse_file
val = provider.send(:mode)
props['VLAN'] = 'yes' if val == :vlan
pairs = unmunge props
pairs.each_with_object('') do |(key, value), str|
str << %(#{key}=#{value}\n)
end
end
def self.unmunge(props)
pairs = {}
%i[onboot hotplug].each do |bool_property|
unless props[bool_property].nil?
props[bool_property] = (props[bool_property] == true ? 'yes' : 'no')
end
end
NAME_MAPPINGS.each_pair do |type_name, redhat_name|
if (val = props[type_name])
props.delete(type_name)
pairs[redhat_name] = val
end
end
pairs.merge! props
pairs.each_pair do |key, val|
pairs[key] = %("#{val}") if val.is_a?(String) && val.match(%r{\s+})
end
pairs
end
def self.post_flush_hook(filename)
File.chmod(0o644, filename)
end
end
@@ -0,0 +1,235 @@
require 'puppetx/filemapper'
Puppet::Type.type(:network_config).provide(:sles) do
# SLES network_config network scripts provider.
#
# This provider manages the contents of /etc/networks/ifcfg-* to
# manage non-volatile network configuration.
#
# @see https://documentation.suse.com/sles/15-SP1/html/SLES-all/cha-network.html#sec-network-manconf-files-ifcfg
include PuppetX::FileMapper
desc 'SLES network-scripts provider'
confine osfamily: :suse
defaultfor osfamily: :suse
has_feature :startmode
has_feature :provider_options
# @return [String] The path to network-script directory on sles systems
SLES_SCRIPT_DIRECTORY = '/etc/sysconfig/network'.freeze # rubocop:disable Lint/ConstantDefinitionInBlock
# The valid vlan ID range is 0-4095; 4096 is out of range
SLES_VLAN_RANGE_REGEX = %r{[1-3]?\d{1,3}|40[0-8]\d|409[0-5]}.freeze # rubocop:disable Lint/ConstantDefinitionInBlock
# aliases are almost free game, sles rejects some, and max total length is 15 characters
# 15 minus at least 2 for the interface name, and a colon leaves 12 characters for the alias
SLES_ALIAS_REGEX = %r{.{1,12}(?<!~|\.bak|\.old|\.orig|\.rpmnew|\.rpmorig|\.rpmsave|\.scpmbackup)}.freeze # rubocop:disable Lint/ConstantDefinitionInBlock
# @return [Regexp] The regular expression for interface scripts on sles systems
SLES_SCRIPT_REGEX = %r{\Aifcfg-[a-z]+[a-z\d]+(?::#{SLES_ALIAS_REGEX}|\.#{SLES_VLAN_RANGE_REGEX})?\Z}.freeze # rubocop:disable Lint/ConstantDefinitionInBlock
# rubocop:disable Lint/ConstantDefinitionInBlock
SLES_NAME_MAPPINGS = {
ipaddress: 'IPADDR',
netmask: 'NETMASK',
method: 'BOOTPROTO',
mtu: 'MTU',
startmode: 'STARTMODE',
}.freeze
# rubocop:enable Lint/ConstantDefinitionInBlock
# Map provider instances to files based on their name
#
# @return [String] The path of the file for the given interface resource
#
# @example
# prov = SLESProvider.new(:name => 'eth1')
# prov.select_file # => '/etc/sysconfig/network/ifcfg-eth1'
#
def select_file
"#{SLES_SCRIPT_DIRECTORY}/ifcfg-#{name}"
end
# Scan all files in the networking directory for interfaces
#
# @param script_dir [String] The path to the networking scripts, defaults to
# {#SLES_SCRIPT_DIRECTORY}
#
# @return [Array<String>] All network-script config files on this machine.
#
# @example
# SLESProvider.target_files
# # => ['/etc/sysconfig/network/ifcfg-eth0', '/etc/sysconfig/network/ifcfg-eth1']
def self.target_files(script_dir = SLES_SCRIPT_DIRECTORY)
entries = Dir.entries(script_dir).select { |entry| entry.match SCRIPT_REGEX }
entries.map { |entry| File.join(SLES_SCRIPT_DIRECTORY, entry) }
end
# Convert a SLES network script into a hash
#
# This is a hook method that will be called by PuppetX::Filemapper
#
# @param [String] filename The path of the interfaces file being parsed
# @param [String] contents The contents of the given file
#
# @return [Array<Hash<Symbol, String>>] A single element array containing
# the key/value pairs of properties parsed from the file.
#
# @example
# SLESProvider.parse_file('/etc/sysconfig/network/ifcfg-eth0', #<String:0xdeadbeef>)
# # => [
# # {
# # :name => 'eth0',
# # :ipaddress => '169.254.0.1',
# # :netmask => '255.255.0.0',
# # },
# # ]
def self.parse_file(filename, contents)
# Split up the file into lines
lines = contents.split("\n")
# Strip out all comments
lines.map! { |line| line.sub(%r{#.*$}, '') }
# Remove all blank lines
lines.reject! { |line| line =~ %r{^\s*$} }
pair_regex = %r{^\s*(.+?)\s*=\s*(.*)\s*$}
# INFO: It is valid ifcfg format to include certain functions and strings these should not be reported as errors, but silently removed before parsing
# https://bugs.centos.org/bug_view_page.php?bug_id=475
# Remove lines with no = sign
lines.select! { |line| line =~ %r{^.*=.*$} }
# Convert the data into key/value pairs
pairs = lines.each_with_object({}) do |line, hash|
raise Puppet::Error, %(#{filename} is malformed; "#{line}" did not match "#{pair_regex}") unless line.match(pair_regex) do |m|
key = m[1].strip
val = m[2].strip
hash[key] = val
end
hash
end
props = munge(pairs)
# TODO: remove duct tape for #13
#
# The :family property is making less and less sense because it seems that
# ipv6 configuration should add new properties instead of trying to collide
# with the ipv4 addresses. But right now, the :inet property is never used
# and it's creating a change on each resource update. This is a patch until
# the :family property is ripped out.
#
# See https://github.com/adrienthebo/puppet-network/issues/13 for the full
# issue that caused this, and https://github.com/adrienthebo/puppet-network/issues/16
# for the resolution.
#
props[:family] = :inet
# If there is no DEVICE property in the interface configuration we retrieve
# the interface name from the file name itself
props[:name] = filename.split('ifcfg-')[1] unless props.key?(:name)
# Set the field to the default to prevent changes to the resource
props[:onboot] = true
# The FileMapper mixin expects an array of providers, so we return the
# single interface wrapped in an array
[props]
end
# @api private
def self.munge(pairs)
props = {}
# Unquote all values
pairs.each_pair do |key, val|
if (munged = val.gsub(%r{['"]}, ''))
pairs[key] = munged
end
end
# For each interface attribute that we recognize it, add the value to the
# hash with our expected label
SLES_NAME_MAPPINGS.each_pair do |type_name, sles_name|
next unless (val = pairs[sles_name])
pairs.delete(sles_name)
props[type_name] = val
end
# if we encounter VLAN_ID parameter, set the interface mode to :vlan
pairs.each_pair do |key, _val|
props[:mode] = :vlan if key == 'VLAN_ID'
end
pairs.delete('VLAN_ID')
# mode is a property so it should always have a value
props[:mode] ||= :raw
# For all of the remaining values, blindly toss them into the options hash.
props[:options] = pairs
props[:method] = 'static' unless %w[none bootp dhcp].include? props[:method]
props
end
def self.format_file(filename, providers)
return '' if providers.empty?
if providers.length > 1
raise Puppet::DevError,
"Unable to support multiple interfaces [#{providers.map(&:name).join(',')}] in a single file #{filename}"
end
provider = providers[0]
props = {}
props = provider.options if provider.options && provider.options != :absent
# Map everything to a flat hash
SLES_NAME_MAPPINGS.each_key do |type_name|
if (val = provider.send(type_name)) && val != :absent
props[type_name] = val
end
end
# :mode does not exist in SLES_NAME_MAPPINGS so we have to fetch it manually
# note that the inverse operation is in .munge instead of parse_file
val = provider.send(:mode)
props['VLAN_ID'] = provider.options['VLAN_ID'] if val == :vlan
pairs = unmunge props
pairs.each_with_object('') do |(key, value), str|
str << %(#{key}=#{value}\n)
end
end
def self.unmunge(props)
pairs = {}
SLES_NAME_MAPPINGS.each_pair do |type_name, sles_name|
if (val = props[type_name])
props.delete(type_name)
pairs[sles_name] = val
end
end
pairs.merge! props
pairs.each_pair do |key, val|
pairs[key] = %("#{val}") if val.is_a?(String) && val.match(%r{\s+})
end
pairs
end
def self.post_flush_hook(filename)
File.chmod(0o644, filename)
end
end
@@ -0,0 +1,117 @@
require 'ipaddr'
require 'puppetx/filemapper'
Puppet::Type.type(:network_route).provide(:redhat) do
# RHEL network_route routes provider.
#
# This provider uses the filemapper mixin to map the routes file to a
# collection of network_route providers, and back.
#
# @see https://access.redhat.com/knowledge/docs/en-US/Red_Hat_Enterprise_Linux/6/html/Deployment_Guide/s1-networkscripts-static-routes.html
include PuppetX::FileMapper
desc 'RHEL style routes provider'
confine osfamily: :redhat
defaultfor osfamily: :redhat
has_feature :provider_options
def select_file
"/etc/sysconfig/network-scripts/route-#{interface}"
end
def self.target_files(script_dir = '/etc/sysconfig/network-scripts')
entries = Dir.entries(script_dir).select { |entry| entry.match %r{route-.*} }
entries.map { |entry| File.join(script_dir, entry) }
end
def self.parse_file(_filename, contents)
routes = []
lines = contents.split("\n")
lines.each do |line|
# Strip off any trailing comments
line.sub!(%r{#.*$}, '')
if line =~ %r{^\s*#|^\s*$}
# Ignore comments and blank lines
next
end
route = line.split(' ', 6)
raise Puppet::Error, 'Malformed redhat route file, cannot instantiate network_route resources' if route.length < 4
route = line.split(' ', 5) if route[0] == 'local'
new_route = {}
if route[0] == 'local'
new_route[:interface] = route[3]
new_route[:options] = route[4] if route[4]
else
new_route[:gateway] = route[2]
new_route[:interface] = route[4]
new_route[:options] = route[5] if route[5]
end
if route[0] == 'local'
new_route[:name] = route[1]
new_route[:network] = 'local'
elsif ['default', '0.0.0.0'].include? route[0]
new_route[:name] = 'default' # FIXME: Must match :name in order for changes to be detected
new_route[:network] = 'default'
new_route[:netmask] = '0.0.0.0'
else
ip = IPAddr.new(route[0])
netmask_addr = ip.prefix <= 32 ? '255.255.255.255' : 'ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff'
netmask = IPAddr.new("#{netmask_addr}/#{ip.prefix}")
new_route[:name] = "#{ip}/#{ip.prefix}" # FIXME: Must match :name in order for changes to be detected
new_route[:network] = ip.to_s
new_route[:netmask] = netmask.to_s
end
routes << new_route
end
routes
end
# Generate an array of sections
def self.format_file(_filename, providers)
contents = []
contents << header
# Build routes
providers.sort_by(&:name).each do |provider|
%w[network interface].each do |prop|
raise Puppet::Error, "#{provider.name} is missing the required parameter '#{prop}'." if provider.send(prop).nil?
end
%w[netmask gateway].each do |prop|
raise Puppet::Error, "#{provider.name} is missing the required parameter '#{prop}'." if provider.send(prop).nil? && provider.send('network').to_s != 'local'
end
contents << if provider.network == 'default'
"#{provider.network} via #{provider.gateway} dev #{provider.interface}"
elsif provider.network == 'local'
"#{provider.network} #{provider.name} dev #{provider.interface}"
else
ip = IPAddr.new("#{provider.network}/#{provider.netmask}")
"#{ip}/#{ip.prefix} via #{provider.gateway} dev #{provider.interface}"
end
contents << (provider.options == :absent ? "\n" : " #{provider.options}\n")
end
contents.join
end
def self.header
<<~HEADER
# HEADER: This file is being managed by puppet. Changes to
# HEADER: routes that are not being managed by puppet will persist;
# HEADER: however changes to routes that are being managed by puppet will
# HEADER: be overwritten. In addition, file order is NOT guaranteed.
# HEADER: Last generated at: #{Time.now}
HEADER
end
def self.post_flush_hook(filename)
File.chmod(0o644, filename)
end
end
@@ -0,0 +1,117 @@
require 'ipaddr'
require 'puppetx/filemapper'
Puppet::Type.type(:network_route).provide(:routes) do
# Debian network_route routes provider.
#
# This provider uses the filemapper mixin to map the routes file to a
# collection of network_route providers, and back.
#
# @see http://wiki.debian.org/NetworkConfiguration
# @see http://packages.debian.org/squeeze/ifupdown-extras
include PuppetX::FileMapper
desc 'Debian routes style provider'
confine osfamily: :debian
# $ dpkg -S /etc/network/if-up.d/20static-routes
# ifupdown-extra: /etc/network/if-up.d/20static-routes
confine exists: '/etc/network/if-up.d/20static-routes'
defaultfor osfamily: :debian
has_feature :provider_options
def select_file
'/etc/network/routes'
end
def self.target_files
['/etc/network/routes']
end
class MalformedRoutesError < Puppet::Error
def initialize(msg = nil)
msg = 'Malformed debian routes file; cannot instantiate network_route resources' if msg.nil?
super
end
end
def self.raise_malformed
@failed = true
raise MalformedRoutesError
end
def self.parse_file(_filename, contents)
# Build out an empty hash for new routes for storing their configs.
route_hash = Hash.new do |hash, key|
hash[key] = {}
hash[key][:name] = key
hash[key]
end
lines = contents.split("\n")
lines.each do |line|
# Strip off any trailing comments
line.sub!(%r{#.*$}, '')
if line =~ %r{^\s*#|^\s*$}
# Ignore comments and blank lines
next
end
route = line.split(' ', 5)
raise_malformed if route.length < 4
if route[0] == 'default'
name = 'default'
route_hash[name][:network] = 'default'
route_hash[name][:netmask] = '0.0.0.0'
else
# use the CIDR version of the target as :name
name = "#{route[0]}/#{IPAddr.new(route[1]).to_i.to_s(2).count('1')}"
route_hash[name][:network] = route[0]
route_hash[name][:netmask] = route[1]
end
route_hash[name][:gateway] = route[2]
route_hash[name][:interface] = route[3]
route_hash[name][:options] = route[4] if route[4]
end
route_hash.values
end
# Generate an array of sections
def self.format_file(_filename, providers)
contents = []
contents << header
# Build routes
providers.sort_by(&:name).each do |provider|
raise Puppet::Error, "#{provider.name} is missing the required parameter 'network'." if provider.network.nil?
raise Puppet::Error, "#{provider.name} is missing the required parameter 'netmask'." if provider.netmask.nil?
raise Puppet::Error, "#{provider.name} is missing the required parameter 'gateway'." if provider.gateway.nil?
raise Puppet::Error, "#{provider.name} is missing the required parameter 'interface'." if provider.interface.nil?
netmask = (provider.name == 'default' ? '0.0.0.0' : provider.netmask)
contents << "#{provider.network} #{netmask} #{provider.gateway} #{provider.interface}"
contents << (provider.options == :absent ? "\n" : " #{provider.options}\n")
end
contents.join
end
def self.header
<<~HEADER
# HEADER: This file is being managed by puppet. Changes to
# HEADER: routes that are not being managed by puppet will persist;
# HEADER: however changes to routes that are being managed by puppet will
# HEADER: be overwritten. In addition, file order is NOT guaranteed.
# HEADER: Last generated at: #{Time.now}
HEADER
end
end
@@ -0,0 +1,102 @@
require 'ipaddr'
require 'puppetx/filemapper'
Puppet::Type.type(:network_route).provide(:sles) do
# SLES network_route routes provider.
#
# This provider uses the filemapper mixin to map the routes file to a
# collection of network_route providers, and back.
#
# @see https://documentation.suse.com/sles/15-SP4/html/SLES-all/cha-network.html#sec-network-manconf-files-routes
include PuppetX::FileMapper
desc 'SLES style routes provider'
confine osfamily: :suse
defaultfor osfamily: :suse
has_feature :provider_options
def select_file
"/etc/sysconfig/network/ifroute-#{interface}"
end
def self.target_files(script_dir = '/etc/sysconfig/network')
entries = Dir.entries(script_dir).select { |entry| entry.match %r{ifroute-.*} }
entries.map { |entry| File.join(script_dir, entry) }
end
def self.parse_file(_filename, contents)
routes = []
lines = contents.split("\n")
lines.each do |line|
# Strip off any trailing comments
line.sub!(%r{#.*$}, '')
if line =~ %r{^\s*#|^\s*$}
# Ignore comments and blank lines
next
end
route = line.split(' ', 5)
raise Puppet::Error, 'Malformed SLES route file, cannot instantiate network_route resources' if route.length < 4
new_route = {}
new_route[:gateway] = route[1]
new_route[:interface] = route[3]
new_route[:options] = route[4] if route[4]
if ['default', '0.0.0.0'].include? route[0]
new_route[:name] = 'default' # FIXME: Must match :name in order for changes to be detected
new_route[:network] = 'default'
new_route[:netmask] = '0.0.0.0'
else
ip = IPAddr.new(route[0])
netmask_addr = ip.prefix <= 32 ? '255.255.255.255' : 'ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff'
netmask = IPAddr.new("#{netmask_addr}/#{ip.prefix}")
new_route[:name] = "#{ip}/#{ip.prefix}" # FIXME: Must match :name in order for changes to be detected
new_route[:network] = ip.to_s
new_route[:netmask] = netmask.to_s
end
routes << new_route
end
routes
end
# Generate an array of sections
def self.format_file(_filename, providers)
contents = []
contents << header
# Build routes
providers.sort_by(&:name).each do |provider|
%w[network netmask gateway interface].each do |prop|
raise Puppet::Error, "#{provider.name} is missing the required parameter '#{prop}'." if provider.send(prop).nil?
end
contents << if provider.network == 'default'
"#{provider.network} #{provider.gateway} - #{provider.interface}"
else
ip = IPAddr.new("#{provider.network}/#{provider.netmask}")
"#{ip}/#{ip.prefix} #{provider.gateway} - #{provider.interface}"
end
contents << (provider.options == :absent ? "\n" : " #{provider.options}\n")
end
contents.join
end
def self.header
<<~HEADER
# HEADER: This file is being managed by puppet. Changes to
# HEADER: routes that are not being managed by puppet will persist;
# HEADER: however changes to routes that are being managed by puppet will
# HEADER: be overwritten. In addition, file order is NOT guaranteed.
# HEADER: Last generated at: #{Time.now}
HEADER
end
def self.post_flush_hook(filename)
File.chmod(0o644, filename)
end
end
@@ -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,85 @@
require 'ipaddr'
require_relative '../../puppet_x/voxpupuli/utils'
Puppet::Type.newtype(:network_route) do
@doc = 'Manage non-volatile route configuration information'
feature :provider_options, <<-EOD
The provider can accept a hash of arbitrary options. The semantics of
these options will depend on the provider.
EOD
include PuppetX::Voxpupuli::Utils
ensurable
newparam(:name) do
isnamevar
desc 'The name of the network route'
end
newproperty(:network) do
isrequired
desc 'The target network address'
validate do |value|
unless %w[default local].include?(value)
a = PuppetX::Voxpupuli::Utils.try { IPAddr.new(value) }
raise("Invalid value for parameter 'network': #{value}") unless a
end
end
end
newproperty(:netmask) do
desc 'The subnet mask to apply to the route'
validate do |value|
raise("Invalid value for parameter 'netmask': #{value}") unless value.length <= 3 || PuppetX::Voxpupuli::Utils.try { IPAddr.new(value) }
end
munge do |value|
# '255.255.255.255'.to_i will return 255, so we try to convert it back:
if value.to_i.to_s == value
# what are the chances someone is using /16 for their IPv6 network?
addr = value.to_i <= 32 ? '255.255.255.255' : 'ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff'
IPAddr.new(addr).mask(value.strip.to_i).to_s
elsif PuppetX::Voxpupuli::Utils.try { IPAddr.new(value).ipv6? }
IPAddr.new('ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff').mask(value).to_s
elsif PuppetX::Voxpupuli::Utils.try { IPAddr.new(value).ipv4? }
IPAddr.new('255.255.255.255').mask(value).to_s
else
raise("Invalid value for parameter 'netmask': #{value}")
end
end
end
newproperty(:gateway) do
desc 'The gateway to use for the route'
validate do |value|
IPAddr.new(value)
rescue ArgumentError
raise("Invalid value for parameter 'gateway': #{value}")
end
end
newproperty(:interface) do
isrequired
desc 'The interface to use for the route'
end
# `:options` provides an arbitrary passthrough for provider properties, so
# that provider specific behavior doesn't clutter up the main type but still
# allows for more powerful actions to be taken.
newproperty(:options, required_features: :provider_options) do
desc 'Provider specific options to be passed to the provider'
validate do |value|
raise ArgumentError, "#{self.class} requires a string for the options property" unless value.is_a?(String)
end
end
validate do
raise "Network_route[#{self[:name]}] must have netmask defined" if self[:network] != 'local' && self[:netmask].nil?
raise "Network_route[#{self[:name]}] must have gateway defined" if self[:network] != 'local' && self[:gateway].nil?
end
end
@@ -0,0 +1,11 @@
module PuppetX
module Voxpupuli
module Utils
def self.try(catch = ArgumentError, nope = false)
yield
rescue catch
nope
end
end
end
end
@@ -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.
@@ -0,0 +1,236 @@
# frozen_string_literal: true
require 'tempfile'
class Puppet::Provider::Openldap < Puppet::Provider
initvars # without this, commands won't work
commands original_slapcat: 'slapcat',
original_ldapmodify: 'ldapmodify',
original_ldapadd: 'ldapadd'
def self.slapcat(filter, dn = '', base = 'cn=config')
arguments = [
'-b', base,
'-o', 'ldif-wrap=no',
'-H', "ldap:///#{dn}???#{filter}"
]
original_slapcat(*arguments)
end
def slapcat(*args)
self.class.slapcat(*args)
end
def self.ldapadd(path)
original_ldapadd('-cQY', 'EXTERNAL', '-H', 'ldapi:///', '-f', path)
end
def ldapadd(*args)
self.class.ldapadd(*args)
end
# Unwrap LDIF and return each attribute beginning with "olc" also removing
# that occurance of "olc" at the beginning.
def self.get_lines(items)
items.strip.
gsub("\n ", '').
split("\n").
grep(%r{^olc}).
map { |entry| entry.gsub(%r{^olc}, '') }
end
def get_lines(*args)
self.class.get_lines(*args)
end
# Unwrap LDIF and return each entry as array of lines.
#
# Example LDIF:
# dn: cn=config
# ...
#
# dn: cn=schema,cn=config
# ...
#
# Results in:
#
# [['dn: cn=config', '...'],
# ['dn: cn=schema,cn=config', '...']]
#
def self.get_entries(items)
items.strip.
split("\n\n").
map do |paragraph|
paragraph.
gsub("\n ", '').
split("\n")
end
end
def get_entries(*args)
self.class.get_entries(*args)
end
def self.last_of_split(line, by = ' ')
line.split(by, 2).last
end
def last_of_split(*args)
self.class.last_of_split(*args)
end
def self.ldapmodify(path)
original_ldapmodify('-Y', 'EXTERNAL', '-H', 'ldapi:///', '-f', path)
end
def ldapmodify(*args)
self.class.ldapmodify(*args)
end
def self.temp_ldif(name = 'openldap_ldif')
Tempfile.new(name)
end
def temp_ldif(*args)
self.class.temp_ldif(*args)
end
def delimit
"-\n"
end
def cn_config
dn('cn=config')
end
def dn(dn)
"dn: #{dn}\n"
end
def changetype(t)
"changetype: #{t}\n"
end
def add(key)
"add: olc#{key}\n"
end
def del(key)
"delete: olc#{key}\n"
end
def replace_key(key)
"replace: olc#{key}\n"
end
def key_value(key, value)
"olc#{key}: #{value}\n"
end
def add_or_replace_key(key, force_replace = :false)
# This list of possible attributes of cn=config has been extracted from a
# running slapd with the following command:
# ldapsearch -s base -b cn=Subschema attributeTypes -o ldif-wrap=no | \
# grep SINGLE-VALUE | grep "NAME 'olc" | \
# sed -e "s|.*NAME '||g" \
# -e "s|' SYNTAX.*||g" \
# -e "s|' EQUALITY.*||g" \
# -e "s|' DESC.*||g"
single_value_attributes = %w[
ConfigFile
ConfigDir
AddContentAcl
ArgsFile
AuthzPolicy
Backend
Concurrency
ConnMaxPending
ConnMaxPendingAuth
Database
DefaultSearchBase
GentleHUP
Hidden
IdleTimeout
IndexSubstrIfMinLen
IndexSubstrIfMaxLen
IndexSubstrAnyLen
IndexSubstrAnyStep
IndexIntLen
LastMod
ListenerThreads
LocalSSF
LogFile
MaxDerefDepth
MirrorMode
ModulePath
Monitoring
MultiProvider
Overlay
PasswordCryptSaltFormat
PidFile
PluginLogFile
ReadOnly
Referral
ReplicaArgsFile
ReplicaPidFile
ReplicationInterval
ReplogFile
ReverseLookup
RootDN
RootPW
SaslAuxprops
SaslHost
SaslRealm
SaslSecProps
SchemaDN
SizeLimit
SockbufMaxIncoming
SockbufMaxIncomingAuth
Subordinate
SyncUseSubentry
Threads
TLSCACertificateFile
TLSCACertificatePath
TLSCertificateFile
TLSCertificateKeyFile
TLSCipherSuite
TLSCRLCheck
TLSCRLFile
TLSRandFile
TLSVerifyClient
TLSDHParamFile
TLSProtocolMin
ToolThreads
UpdateDN
WriteTimeout
DbDirectory
DbCheckpoint
DbNoSync
DbMaxReaders
DbMaxSize
DbMode
DbSearchStack
PPolicyDefault
PPolicyHashCleartext
PPolicyForwardUpdates
PPolicyUseLockout
MemberOfDN
MemberOfDangling
MemberOfRefInt
MemberOfGroupOC
MemberOfMemberAD
MemberOfMemberOfAD
MemberOfDanglingError
SpCheckpoint
SpSessionlog
SpNoPresent
SpReloadHint
]
use_replace = single_value_attributes.include?(key.to_s) || force_replace == :true
use_replace ? replace_key(key) : add(key)
end
end
@@ -0,0 +1,206 @@
# frozen_string_literal: true
require File.expand_path(File.join(File.dirname(__FILE__), %w[.. openldap]))
require 'tempfile'
# rubocop:disable Naming/VariableName
# rubocop:disable Naming/MethodName
# rubocop:disable Lint/AssignmentInCondition
Puppet::Type.
type(:openldap_access).
provide(:olc, parent: Puppet::Provider::Openldap) do
# TODO: Use ruby bindings (can't find one that support IPC)
defaultfor osfamily: %i[debian freebsd redhat suse]
mk_resource_methods
def self.instances
# TODO: restict to bdb, hdb and globals
i = []
slapcat('(olcAccess=*)').split("\n\n").map do |paragraph|
access = nil
suffix = nil
position = nil
paragraph.gsub("\n ", '').split("\n").map do |line|
case line
when %r{^olcDatabase: }
suffix = "cn=#{line.split[1].gsub(%r{\{-?\d+\}}, '')}"
when %r{^olcSuffix: }
suffix = line.split[1]
when %r{^olcAccess: }
begin
position, what, bys = line.match(%r{^olcAccess:\s+\{(\d+)\}to\s+(\S+(?:\s+filter=\S+)?(?:\s+attrs=\S+)?(?:\s+val=\S+)?)(\s+by\s+.*)+$}).captures
rescue StandardError
raise Puppet::Error, "Failed to parse olcAccess for suffix '#{suffix}': #{line}"
end
access = []
bys.split(%r{(?= by .+)}).each do |b|
access << b.lstrip
end
i << new(
name: "#{position} on #{suffix}",
ensure: :present,
position: position,
what: what,
access: access,
suffix: suffix
)
end
end
end
i
end
def self.prefetch(resources)
accesses = instances
resources.each_key do |name|
next unless provider = accesses.find do |access|
if resources[name][:position]
access.suffix == resources[name][:suffix] &&
access.position == resources[name][:position].to_s
else
access.suffix == resources[name][:suffix] &&
access.access.flatten == resources[name][:access].flatten &&
access.what == resources[name][:what]
end
end
resources[name].provider = provider
end
end
def self.getDn(suffix)
case suffix
when 'cn=frontend'
'olcDatabase={-1}frontend,cn=config'
when 'cn=config'
'olcDatabase={0}config,cn=config'
when 'cn=monitor'
slapcat('(olcDatabase=monitor)').split("\n").map do |line|
return line.split[1] if line =~ %r{^dn: }
end
else
slapcat("(olcSuffix=#{suffix})").split("\n").map do |line|
return line.split[1] if line =~ %r{^dn: }
end
end
end
def getDn(*args)
self.class.getDn(*args)
end
def exists?
@property_hash[:ensure] == :present
end
def create
t = Tempfile.new('openldap_access')
t << "dn: #{getDn(resource[:suffix])}\n"
t << "add: olcAccess\n"
t << if resource[:position]
"olcAccess: {#{resource[:position]}}to #{resource[:what]}\n"
else
"olcAccess: to #{resource[:what]}\n"
end
resource[:access].flatten.each do |a|
t << " #{a}\n"
end
t.close
Puppet.debug(File.read(t.path))
begin
ldapmodify(t.path)
rescue StandardError => e
raise Puppet::Error, "LDIF content:\n#{File.read t.path}\nError message: #{e.message}"
end
end
def destroy
t = Tempfile.new('openldap_access')
t << "dn: #{getDn(@property_hash[:suffix])}\n"
t << "changetype: modify\n"
t << "delete: olcAccess\n"
t << "olcAccess: {#{@property_hash[:position]}}\n"
t.close
Puppet.debug(File.read(t.path))
begin
ldapmodify(t.path)
rescue StandardError => e
raise Puppet::Error, "LDIF content:\n#{File.read t.path}\nError message: #{e.message}"
end
end
def initialize(value = {})
super(value)
@property_flush = {}
end
def access=(value)
@property_flush[:access] = value.flatten
end
def self.getCountOfOlcAccess(suffix)
countOfElement = 0
slapcat('(olcAccess=*)', getDn(suffix).to_s).split("\n\n").map do |paragraph|
paragraph.gsub("\n ", '').split("\n").map do |line|
case line
when %r{^olcAccess: }
countOfElement += 1
end
end
end
countOfElement
end
def getCurrentOlcAccess(suffix)
i = []
slapcat('(olcAccess=*)', getDn(suffix).to_s).split("\n\n").map do |paragraph|
paragraph.gsub("\n ", '').split("\n").map do |line|
case line
when %r{^olcAccess: }
position, content = line.match(%r{^olcAccess:\s+\{(\d+)\}(.*)$}).captures
i << {
position: position,
content: content,
}
end
end
end
i
end
def flush
unless @property_flush.empty?
current_olcAccess = getCurrentOlcAccess(resource[:suffix])
t = Tempfile.new('openldap_access')
t << "dn: #{getDn(resource[:suffix])}\n"
t << "changetype: modify\n"
t << "replace: olcAccess\n"
position = resource[:position] || @property_hash[:position]
current_olcAccess.each do |olc_access|
if olc_access[:position].to_i == position.to_i
t << "olcAccess: {#{position}}to #{resource[:what]}\n"
resource[:access].flatten.each do |a|
t << " #{a}\n"
end
else
t << "olcAccess: {#{olc_access[:position]}}#{olc_access[:content]}\n"
end
end
self.class.getCountOfOlcAccess(resource[:suffix])
t.close
Puppet.debug(File.read(t.path))
begin
ldapmodify(t.path)
rescue StandardError => e
raise Puppet::Error, "LDIF content:\n#{File.read t.path}\nError message: #{e.message}"
end
end
@property_hash = resource.to_hash
end
end
# rubocop:enable Naming/VariableName
# rubocop:enable Naming/MethodName
# rubocop:enable Lint/AssignmentInCondition
@@ -0,0 +1,435 @@
# frozen_string_literal: true
require File.expand_path(File.join(File.dirname(__FILE__), %w[.. openldap]))
require 'base64'
Puppet::Type.
type(:openldap_database).
provide(:olc, parent: Puppet::Provider::Openldap) do
# TODO: Use ruby bindings (can't find one that support IPC)
defaultfor osfamily: %i[debian freebsd redhat suse]
mk_resource_methods
def self.instances
databases = slapcat('(|(olcDatabase=monitor)(olcDatabase={0}config)(&(objectClass=olcDatabaseConfig)(|(objectClass=olcBdbConfig)(objectClass=olcHdbConfig)(objectClass=olcMdbConfig)(objectClass=olcMonitorConfig)(objectClass=olcRelayConfig)(objectClass=olcLDAPConfig))))')
databases.split("\n\n").map do |paragraph|
suffix = nil
relay = nil
index = nil
backend = nil
directory = nil
rootdn = nil
rootpw = nil
readonly = nil
sizelimit = nil
dbmaxsize = nil
timelimit = nil
updateref = nil
dboptions = {}
mirrormode = nil
multiprovider = nil
syncusesubentry = nil
syncrepl = nil
limits = []
security = {}
paragraph.gsub("\n ", '').split("\n").map do |line|
case line
when %r{^olcDatabase: }
index, backend = line.match(%r{^olcDatabase: \{(\d+)\}(bdb|hdb|mdb|monitor|config|relay|ldap)$}).captures
when %r{^olcDbDirectory: }
directory = line.split[1]
when %r{^olcRootDN: }
rootdn = line.split[1]
when %r{^olcRootPW:: }
rootpw = Base64.decode64(line.split[1])
when %r{^olcSuffix: }
suffix = line.split[1]
when %r{^olcRelay: }
relay = line.split[1]
when %r{^olcReadOnly: }i
readonly = line.split[1]
when %r{^olcSizeLimit: }i
sizelimit = line.split[1]
when %r{^olcDbMaxSize: }i
dbmaxsize = line.split[1]
when %r{^olcTimeLimit: }i
timelimit = line.split[1]
when %r{^olcUpdateref: }i
updateref = line.split[1]
when %r{^olcDb\S+: }i
optname, optvalue = line.split(': ', 2)
optname.downcase!
case optname
when 'olcdbconfig'
dboptions['dbconfig'] = [] unless dboptions['dbconfig']
optvalue = optvalue.match(%r{^\{\d+\}(.+)$}).captures[0] if optvalue =~ %r{^\{\d+\}.+$}
dboptions['dbconfig'].push(optvalue)
when 'olcdbnosync'
dboptions['dbnosync'] = optvalue
when 'olcdbpasesize'
dboptions['dbpagesize'] = optvalue
else
ldifoptname = optname.match(%r{^olcDb(\S+)$}i).captures[0]
if dboptions[ldifoptname] && !dboptions[ldifoptname].is_a?(Array)
dboptions[ldifoptname] = [dboptions[ldifoptname]]
dboptions[ldifoptname].push(optvalue)
elsif dboptions[ldifoptname]
dboptions[ldifoptname].push(optvalue)
else
dboptions[optname.match(%r{^olcDb(\S+)$}i).captures[0]] = optvalue
end
end
when %r{^olcMirrorMode: }
mirrormode = line.split[1] == 'TRUE' ? :true : :false
when %r{^olcMultiProvider: }
multiprovider = line.split[1] == 'TRUE' ? :true : :false
when %r{^olcSyncUseSubentry: }
syncusesubentry = line.split(' ', 2)[1]
when %r{^olcSyncrepl: }
syncrepl ||= []
optvalue = line.split(' ', 2)[1]
syncrepl.push(optvalue.match(%r{^(\{\d+\})?(.+)$}).captures[1])
when %r{^olcLimits: }
limit = line.match(%r{^olcLimits:\s+(\{\d+\})?(.+)$}).captures[1]
limits << limit
when %r{^olcSecurity: }
line.split(': ')[1].split.each do |variable|
values = variable.split('=')
security[values[0]] = values[1].to_i
end
end
end
suffix = "cn=#{backend}" if backend.match(%r{monitor}i) && !suffix
suffix = "cn=#{backend}" if backend.match(%r{config}i) && !suffix
suffix = "cn=#{backend}" if backend.match(%r{ldap}i) && !suffix
new(
ensure: :present,
name: suffix,
suffix: suffix,
relay: relay,
index: index.to_i,
backend: backend,
directory: directory,
rootdn: rootdn,
rootpw: rootpw,
readonly: readonly,
sizelimit: sizelimit,
timelimit: timelimit,
dbmaxsize: dbmaxsize,
updateref: updateref,
dboptions: dboptions,
mirrormode: mirrormode,
multiprovider: multiprovider,
syncusesubentry: syncusesubentry,
syncrepl: syncrepl,
limits: limits,
security: security
)
end
end
def self.prefetch(resources)
databases = instances
resources.each_key do |name|
if (provider = databases.find { |database| database.name == name })
resources[name].provider = provider
end
end
end
def exists?
@property_hash[:ensure] == :present
end
def fetch_index
slapcat("(&(objectClass=olc#{@property_hash[:backend].to_s.capitalize}Config)(olcSuffix=#{@property_hash[:suffix]}))").split("\n").map do |line|
@property_hash[:index] = line.match(%r{^olcDatabase: \{(\d+)\}#{@property_hash[:backend]}$}).captures[0].to_i if line =~ %r{^olcDatabase: }
end
end
def destroy
default_confdir = {
'Debian' => '/etc/ldap/slapd.d',
'RedHat' => '/etc/openldap/slapd.d',
'FreeBSD' => '/usr/local/etc/openldap/slapd.d',
}[Facter.value(:osfamily)]
backend = @property_hash[:backend]
fetch_index
`service slapd stop`
File.delete("#{default_confdir}/cn=config/olcDatabase={#{@property_hash[:index]}}#{backend}.ldif")
slapcat("(objectClass=olc#{backend.to_s.capitalize}Config)").
split("\n").
grep(%r{^dn: }).
select { |dn| dn.match(%r{^dn: olcDatabase={(\d+)}#{backend},cn=config$}).captures[0].to_i > @property_hash[:index] }.
each do |dn|
index = dn[%r{\d+}].to_i
old_filename = "#{default_confdir}/cn=config/olcDatabase={#{index}}#{backend}.ldif"
new_filename = "#{default_confdir}/cn=config/olcDatabase={#{index - 1}}#{backend}.ldif"
File.rename(old_filename, new_filename)
text = File.read(new_filename)
replace = text.gsub!("{#{index}}#{backend}", "{#{index - 1}}#{backend}")
File.open(new_filename, 'w') { |file| file.puts replace }
end
`service slapd start`
@property_hash.clear
end
def initdb
t = Tempfile.new('openldap_database')
t << "dn: #{resource[:suffix]}\n"
t << "changetype: add\n"
t << "objectClass: top\n"
t << "objectClass: dcObject\n" if resource[:suffix].start_with?('dc=')
t << "objectClass: organization\n"
t << "dc: #{resource[:suffix].split(%r{,?dc=}).delete_if(&:empty?)[0]}\n" if resource[:suffix].start_with?('dc=')
t << "o: #{resource[:organization]}\n" if resource[:organization]
if resource[:rootdn]
t << "\n"
t << "dn: #{resource[:rootdn]}\n"
t << "objectClass: simpleSecurityObject\n" if resource[:rootpw]
t << "objectClass: organizationalRole\n"
t << "cn: #{resource[:rootdn].split(%r{,|=})[1]}\n"
t << "description: LDAP administrator\n"
t << "userPassword: #{resource[:rootpw]}\n" if resource[:rootpw]
end
t.close
Puppet.debug(File.read(t.path))
begin
ldapadd(t.path)
rescue StandardError => e
raise Puppet::Error, "LDIF content:\n#{File.read t.path}\nError message: #{e.message}"
end
t.delete
end
def create
if resource[:rootpw] && resource[:rootpw] !~ %r{^\{(CRYPT|MD5|SMD5|SSHA|SHA(256|384|512)?)\}.+}
require 'securerandom'
salt = SecureRandom.random_bytes(4)
@resource[:rootpw] = "{SSHA}#{Base64.encode64("#{Digest::SHA1.digest("#{resource[:rootpw]}#{salt}")}#{salt}").chomp}"
end
t = Tempfile.new('openldap_database')
t << "dn: olcDatabase=#{resource[:backend]},cn=config\n"
t << "changetype: add\n"
t << "objectClass: olcDatabaseConfig\n"
t << "objectClass: olc#{resource[:backend].to_s.capitalize}Config\n"
t << "olcDatabase: #{resource[:backend]}\n"
case resource[:backend].to_s
when 'relay'
t << "olcRelay: #{resource[:relay]}\n" unless resource[:relay].empty?
t << "olcSuffix: #{resource[:suffix]}\n" if resource[:suffix]
when 'monitor'
# WRITE HERE FOR MONITOR ONLY
when 'ldap'
# WRITE HERE FOR LDAP ONLY
t << "olcSuffix: #{resource[:suffix]}\n" if resource[:suffix]
else
t << "olcDbDirectory: #{resource[:directory]}\n" if resource[:directory]
t << "olcSuffix: #{resource[:suffix]}\n" if resource[:suffix]
t << "olcDbIndex: objectClass eq\n" if !resource[:dboptions] || !resource[:dboptions]['index']
end
t << "olcRootDN: #{resource[:rootdn]}\n" if resource[:rootdn]
t << "olcRootPW: #{resource[:rootpw]}\n" if resource[:rootpw]
t << "olcReadOnly: #{resource[:readonly] == :true ? 'TRUE' : 'FALSE'}\n" if resource[:readonly]
t << "olcSizeLimit: #{resource[:sizelimit]}\n" if resource[:sizelimit]
t << "olcDbMaxSize: #{resource[:dbmaxsize]}\n" if resource[:dbmaxsize]
t << "olcTimeLimit: #{resource[:timelimit]}\n" if resource[:timelimit]
t << "olcUpdateref: #{resource[:updateref]}\n" if resource[:updateref]
resource[:dboptions]&.each do |k, v|
t << case k
when 'dbnosync'
"olcDbNosync: #{v}\n"
when 'dbpagesize'
"olcDbPagesize: #{v}\n"
when 'dbconfig'
v.map { |x| "olcDbConfig: #{x}\n" }.join
else
if v.is_a?(Array)
v.map { |x| "olcDb#{k}: #{x}\n" }.join
else
"olcDb#{k}: #{v}\n"
end
end
end
t << (resource[:syncrepl].map { |x| "olcSyncrepl: #{x}\n" }.join) if resource[:syncrepl]
t << "olcMirrorMode: #{resource[:mirrormode] == :true ? 'TRUE' : 'FALSE'}\n" if resource[:mirrormode]
t << "olcMultiProvider: #{resource[:multiprovider] == :true ? 'TRUE' : 'FALSE'}\n" if resource[:multiprovider]
t << "olcSyncUseSubentry: #{resource[:syncusesubentry]}\n" if resource[:syncusesubentry]
t << "#{resource[:limits].map { |x| "olcLimits: #{x}" }.join("\n")}\n" if resource[:limits] && !resource[:limits].empty?
t << "#{resource[:security].map { |k, v| "olcSecurity: #{k}=#{v}" }.join("\n")}\n" if resource[:security] && !resource[:security].empty?
t << "olcAccess: to * by dn.exact=gidNumber=0+uidNumber=0,cn=peercred,cn=external,cn=auth manage by * break\n"
admin = resource[:rootdn] || "cn=admin,#{resource[:suffix]}"
t << "olcAccess: to attrs=userPassword\n"
t << " by self write\n"
t << " by anonymous auth\n"
t << " by dn=\"#{admin}\" write\n"
t << " by * none\n"
t << "olcAccess: to dn.base=\"\" by * read\n"
t << "olcAccess: to *\n"
t << " by self write\n"
t << " by dn=\"#{admin}\" write\n"
t << " by * read\n"
t.close
Puppet.debug(File.read(t.path))
begin
ldapmodify(t.path)
rescue StandardError => e
raise Puppet::Error, "LDIF content:\n#{File.read t.path}\nError message: #{e.message}"
end
t.delete
initdb if resource[:initdb] == :true
@property_hash[:ensure] = :present
slapcat("(&(objectClass=olc#{resource[:backend].to_s.capitalize}Config)(olcSuffix=#{resource[:suffix]}))").
split("\n").map do |line|
@property_hash[:index] = line.match(%r{^olcDatabase: \{(\d+)\}#{resource[:backend]}$}).captures[0] if line =~ %r{^olcDatabase: }
end
end
def initialize(value = {})
super(value)
@property_flush = {}
end
def directory=(value)
@property_flush[:directory] = value
end
def rootdn=(value)
@property_flush[:rootdn] = value
end
def rootpw=(value)
@property_flush[:rootpw] = value
end
def suffix=(value)
@property_flush[:suffix] = value
end
def relay=(value)
@property_flush[:relay] = value
end
def readonly=(value)
@property_flush[:readonly] = value
end
def sizelimit=(value)
@property_flush[:sizelimit] = value
end
def timelimit=(value)
@property_flush[:timelimit] = value
end
def dbmaxsize=(value)
@property_flush[:dbmaxsize] = value
end
def updateref=(value)
@property_flush[:updateref] = value
end
def dboptions=(value)
@property_flush[:dboptions] = value
end
def mirrormode=(value)
@property_flush[:mirrormode] = value
end
def multiprovider=(value)
@property_flush[:multiprovider] = value
end
def syncusesubentry=(value)
@property_flush[:syncusesubentry] = value
end
def syncrepl=(value)
@property_flush[:syncrepl] = value
end
def limits=(value)
@property_flush[:limits] = value
end
def security=(value)
@property_flush[:security] = value
end
def flush
unless @property_flush.empty?
t = Tempfile.new('openldap_database')
t << "dn: olcDatabase={#{@property_hash[:index]}}#{resource[:backend]},cn=config\n"
t << "changetype: modify\n"
t << "replace: olcDbDirectory\nolcDbDirectory: #{resource[:directory]}\n-\n" if @property_flush[:directory]
t << "replace: olcRootDN\nolcRootDN: #{resource[:rootdn]}\n-\n" if @property_flush[:rootdn]
t << "replace: olcRootPW\nolcRootPW: #{resource[:rootpw]}\n-\n" if @property_flush[:rootpw]
t << "replace: olcSuffix\nolcSuffix: #{resource[:suffix]}\n-\n" if @property_flush[:suffix]
t << "replace: olcRelay\nolcRelay: #{resource[:relay]}\n-\n" if @property_flush[:relay]
t << "replace: olcReadOnly\nolcReadOnly: #{resource[:readonly] == :true ? 'TRUE' : 'FALSE'}\n-\n" if @property_flush[:readonly]
t << "replace: olcSizeLimit\nolcSizeLimit: #{resource[:sizelimit]}\n-\n" if @property_flush[:sizelimit]
t << "replace: olcTimeLimit\nolcTimeLimit: #{resource[:timelimit]}\n-\n" if @property_flush[:timelimit]
t << "replace: olcDbMaxSize\nolcDbMaxSize: #{resource[:dbmaxsize]}\n-\n" if @property_flush[:dbmaxsize]
if @property_flush[:dboptions]
# rubocop:disable Metrics/BlockNesting
if resource[:synctype].to_s == 'inclusive' && !@property_hash[:dboptions].empty?
@property_hash[:dboptions].each_key do |k|
t << case k
when 'dbnosync'
"delete: olcDbNosync\n-\n"
when 'dbpagesize'
"delete: olcDbPagesize\n-\n"
when 'dbconfig'
"delete: olcDbConfig\n-\n"
else
"delete: olcDb#{k}\n-\n"
end
end
end
@property_flush[:dboptions].each do |k, v|
t << case k
when 'dbnosync'
"replace: olcDbNosync\nolcDbNosync: #{v}\n-\n"
when 'dbpagesize'
"replace: olcDbPagesize\nolcDbPagesize: #{v}\n-\n"
when 'dbconfig'
"replace: olcDbConfig\n#{v.map { |x| "olcDbConfig: #{x}" }.join("\n")}\n-\n"
else
if v.is_a?(Array)
"replace: olcDb#{k}\n#{v.map { |x| "olcDb#{k}: #{x}" }.join("\n")}\n-\n"
else
"replace: olcDb#{k}\nolcDb#{k}: #{v}\n-\n"
end
end
end
# rubocop:enable Metrics/BlockNesting
end
t << "replace: olcSyncrepl\n#{resource[:syncrepl].map { |x| "olcSyncrepl: #{x}" }.join("\n")}\n-\n" if @property_flush[:syncrepl]
t << "replace: olcUpdateref\nolcUpdateref: #{resource[:updateref]}\n-\n" if @property_flush[:updateref]
t << "replace: olcMirrorMode\nolcMirrorMode: #{resource[:mirrormode] == :true ? 'TRUE' : 'FALSE'}\n-\n" if @property_flush[:mirrormode]
t << "replace: olcMultiProvider\nolcMultiProvider: #{resource[:multiprovider] == :true ? 'TRUE' : 'FALSE'}\n-\n" if @property_flush[:multiprovider]
t << "replace: olcSyncUseSubentry\nolcSyncUseSubentry: #{resource[:syncusesubentry]}\n-\n" if @property_flush[:syncusesubentry]
t << "replace: olcLimits\n#{@property_flush[:limits].map { |x| "olcLimits: #{x}" }.join("\n")}\n-\n" if @property_flush[:limits]
t << "replace: olcSecurity\n#{@property_flush[:security].map { |k, v| "olcSecurity: #{k}=#{v}" }.join("\n")}\n-\n" if @property_flush[:security]
t.close
Puppet.debug(File.read(t.path))
begin
ldapmodify(t.path)
rescue StandardError => e
raise Puppet::Error, "LDIF content:\n#{File.read t.path}\nError message: #{e.message}"
end
initdb if @property_flush[:directory]
end
@property_hash = resource.to_hash
end
end
@@ -0,0 +1,120 @@
# frozen_string_literal: true
require File.expand_path(File.join(File.dirname(__FILE__), %w[.. openldap]))
# rubocop:disable Naming/VariableName
# rubocop:disable Naming/MethodName
# rubocop:disable Lint/AssignmentInCondition
Puppet::Type.
type(:openldap_dbindex).
provide(:olc, parent: Puppet::Provider::Openldap) do
# TODO: Use ruby bindings (can't find one that support IPC)
defaultfor osfamily: %i[debian freebsd redhat suse]
mk_resource_methods
def self.instances
# TODO: restict to bdb and hdb
i = []
slapcat('(olcDbIndex=*)').split("\n\n").map do |paragraph|
suffix = nil
attrlist = nil
indices = nil
paragraph.gsub("\n ", '').split("\n").map do |line|
case line
when %r{^olcSuffix: }
suffix = line.split[1]
when %r{^olcDbIndex: }
attrlist, indices = line.match(%r{^olcDbIndex: (\S+)(?:\s+(.+))?$}).captures
i << new(
name: "#{attrlist} on #{suffix}",
ensure: :present,
attribute: attrlist,
suffix: suffix,
indices: indices
)
end
end
end
i
end
def self.prefetch(resources)
dbindexes = instances
resources.each_key do |name|
next unless provider = dbindexes.find do |access|
access.attribute == resources[name][:attribute] && access.suffix == resources[name][:suffix]
end
resources[name].provider = provider
end
end
def getDn(suffix)
slapcat("(olcSuffix=#{suffix})").split("\n").map do |line|
return line.split[1] if line =~ %r{^dn: }
end
end
def exists?
@property_hash[:ensure] == :present
end
def create
t = Tempfile.new('openldap_dbindex')
t << "dn: #{getDn(resource[:suffix])}\n"
t << "add: olcDbIndex\n"
t << "olcDbIndex: #{resource[:attribute]} #{resource[:indices]}\n"
t.close
Puppet.debug(File.read(t.path))
begin
ldapmodify(t.path)
rescue StandardError => e
raise Puppet::Error, "LDIF content:\n#{File.read t.path}\nError message: #{e.message}"
end
end
def indices=(_value)
current_olcDbIndex = getCurrentOlcDbIndex(resource[:suffix])
t = Tempfile.new('openldap_dbindex')
t << "dn: #{getDn(resource[:suffix])}\n"
t << "changetype: modify\n"
t << "replace: olcDbIndex\n"
current_olcDbIndex.each do |olc_db_index|
t << if olc_db_index[:attribute].to_s == resource[:attribute].to_s
"olcDbIndex: #{resource[:attribute]} #{resource[:indices]}\n"
else
"olcDbIndex: #{olc_db_index[:attribute]} #{olc_db_index[:indices]}\n"
end
end
t.close
Puppet.debug(File.read(t.path))
begin
ldapmodify(t.path)
rescue StandardError => e
raise Puppet::Error, "LDIF content:\n#{File.read t.path}\nError message: #{e.message}"
end
end
def getCurrentOlcDbIndex(suffix)
i = []
slapcat('(olcDbIndex=*)', getDn(suffix)).split("\n\n").map do |paragraph|
paragraph.gsub("\n ", '').split("\n").map do |line|
case line
when %r{^olcDbIndex: }
attribute, indices = line.match(%r{^olcDbIndex:\s+(\S+)\s+(.*)$}).captures
i << {
attribute: attribute,
indices: indices,
}
end
end
end
i
end
end
# rubocop:enable Naming/VariableName
# rubocop:enable Naming/MethodName
# rubocop:enable Lint/AssignmentInCondition

Some files were not shown because too many files have changed in this diff Show More