kruby-controller 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- checksums.yaml +7 -0
- data/LICENSE +201 -0
- data/README.md +117 -0
- data/Rakefile +8 -0
- data/exe/kruby-controller +32 -0
- data/lib/kruby-controller.rb +8 -0
- data/lib/kruby_controller/builder/controller_builder.rb +52 -0
- data/lib/kruby_controller/cache/cache.rb +100 -0
- data/lib/kruby_controller/cache/deep_copy.rb +32 -0
- data/lib/kruby_controller/cache/delta.rb +12 -0
- data/lib/kruby_controller/cache/informer.rb +453 -0
- data/lib/kruby_controller/cache/request_error.rb +55 -0
- data/lib/kruby_controller/cache/store.rb +92 -0
- data/lib/kruby_controller/cache/watch_stream.rb +144 -0
- data/lib/kruby_controller/cli/create_api_command.rb +335 -0
- data/lib/kruby_controller/cli/flag_parser.rb +85 -0
- data/lib/kruby_controller/cli/init_command.rb +383 -0
- data/lib/kruby_controller/controller.rb +200 -0
- data/lib/kruby_controller/crd.rb +141 -0
- data/lib/kruby_controller/election/leader_elector.rb +212 -0
- data/lib/kruby_controller/finalizer/finalizer_manager.rb +31 -0
- data/lib/kruby_controller/generator/crd_generator.rb +109 -0
- data/lib/kruby_controller/gvk.rb +59 -0
- data/lib/kruby_controller/handler/enqueued_object.rb +18 -0
- data/lib/kruby_controller/handler/enqueued_owner.rb +51 -0
- data/lib/kruby_controller/handler/predicated.rb +21 -0
- data/lib/kruby_controller/kubernetes_object_client.rb +77 -0
- data/lib/kruby_controller/logger.rb +11 -0
- data/lib/kruby_controller/manager.rb +291 -0
- data/lib/kruby_controller/owner/owner_reference.rb +23 -0
- data/lib/kruby_controller/queue/rate_limiter.rb +51 -0
- data/lib/kruby_controller/queue/work_queue.rb +375 -0
- data/lib/kruby_controller/reconciler.rb +18 -0
- data/lib/kruby_controller/request.rb +59 -0
- data/lib/kruby_controller/result.rb +50 -0
- data/lib/kruby_controller/status/status_updater.rb +29 -0
- data/lib/kruby_controller/version.rb +5 -0
- data/lib/kruby_controller.rb +87 -0
- metadata +138 -0
|
@@ -0,0 +1,144 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
require "json"
|
|
4
|
+
|
|
5
|
+
module KrubyController
|
|
6
|
+
module Cache
|
|
7
|
+
# A minimal watch stream over the framework's ApiClient: one HTTP
|
|
8
|
+
# connection, newline-delimited JSON events, no automatic reconnection.
|
|
9
|
+
#
|
|
10
|
+
# It exists because kruby's Kubernetes::Watch reconnects internally on a
|
|
11
|
+
# 410 Gone — resetting the resourceVersion and watching from "now" —
|
|
12
|
+
# which silently drops every event between the stale RV and the
|
|
13
|
+
# reconnect. This stream yields EVERY parsed event (including ERROR and
|
|
14
|
+
# BOOKMARK events — classification is the informer's responsibility, so
|
|
15
|
+
# it raises WatchStream::Error subclasses from its event handler and
|
|
16
|
+
# this stream surfaces them after the transfer completes) and leaves all
|
|
17
|
+
# reconnection policy to the informer.
|
|
18
|
+
class WatchStream
|
|
19
|
+
# A watch request failure. +code+ is the HTTP code, +retry_after+ the
|
|
20
|
+
# server's Retry-After in seconds.
|
|
21
|
+
class Error < RequestError; end
|
|
22
|
+
|
|
23
|
+
# A 410 Gone: the resourceVersion the watch started from is no longer
|
|
24
|
+
# served. The informer must relist from a fresh LIST.
|
|
25
|
+
class Gone < Error; end
|
|
26
|
+
|
|
27
|
+
# Typhoeus: 0 disables the total timeout so an idle watch stream is
|
|
28
|
+
# not killed mid-poll (the connection-establishment timeout still
|
|
29
|
+
# applies).
|
|
30
|
+
WATCH_IDLE_TIMEOUT = 0
|
|
31
|
+
|
|
32
|
+
def initialize(api_client)
|
|
33
|
+
@api_client = api_client
|
|
34
|
+
end
|
|
35
|
+
|
|
36
|
+
# Streams watch events from +path+ (which carries the resourceVersion
|
|
37
|
+
# query). Yields each parsed event Hash — including ERROR and
|
|
38
|
+
# BOOKMARK events; classification is the informer's responsibility.
|
|
39
|
+
# Raises Error for non-200 responses (with Retry-After when present)
|
|
40
|
+
# and transport failures, and surfaces WatchStream::Error subclasses
|
|
41
|
+
# raised by the event handler after the transfer completes. A clean
|
|
42
|
+
# server-side close returns normally once the buffered tail (an event
|
|
43
|
+
# without its trailing newline) has been processed.
|
|
44
|
+
def connect(path)
|
|
45
|
+
request = @api_client.build_request("GET", path, auth_names: ["BearerToken"])
|
|
46
|
+
request.options[:timeout] = WATCH_IDLE_TIMEOUT
|
|
47
|
+
|
|
48
|
+
buffer = +""
|
|
49
|
+
error = nil
|
|
50
|
+
headers_seen = nil
|
|
51
|
+
request.on_headers { |headers| headers_seen = headers }
|
|
52
|
+
request.on_body do |chunk|
|
|
53
|
+
next if error
|
|
54
|
+
next if chunk.nil?
|
|
55
|
+
next if headers_seen && !success_code?(headers_seen)
|
|
56
|
+
|
|
57
|
+
buffer << chunk
|
|
58
|
+
lines, buffer = split_complete_lines(buffer)
|
|
59
|
+
lines.each do |line|
|
|
60
|
+
event = parse_event(line)
|
|
61
|
+
next unless event
|
|
62
|
+
|
|
63
|
+
begin
|
|
64
|
+
yield event
|
|
65
|
+
rescue WatchStream::Error => e
|
|
66
|
+
# Classified errors (410 Gone, ERROR events) surface after the
|
|
67
|
+
# transfer completes, so the HTTP machinery is never left in a
|
|
68
|
+
# half-aborted state.
|
|
69
|
+
error = e
|
|
70
|
+
break
|
|
71
|
+
end
|
|
72
|
+
end
|
|
73
|
+
end
|
|
74
|
+
|
|
75
|
+
response = request.run
|
|
76
|
+
raise error if error
|
|
77
|
+
|
|
78
|
+
check_response(response, headers_seen)
|
|
79
|
+
event = parse_event(buffer)
|
|
80
|
+
yield event if event
|
|
81
|
+
end
|
|
82
|
+
|
|
83
|
+
private
|
|
84
|
+
|
|
85
|
+
def success_code?(headers_or_response)
|
|
86
|
+
code = headers_or_response.code.to_i
|
|
87
|
+
(200..299).cover?(code)
|
|
88
|
+
end
|
|
89
|
+
|
|
90
|
+
def check_response(response, headers_seen)
|
|
91
|
+
return if transfer_ok?(response, headers_seen)
|
|
92
|
+
|
|
93
|
+
source = response || headers_seen
|
|
94
|
+
|
|
95
|
+
# Some API servers reject a stale watch resourceVersion with an HTTP
|
|
96
|
+
# 410 response instead of a streamed ERROR event; both forms must
|
|
97
|
+
# take the same recovery path (immediate relist, no backoff).
|
|
98
|
+
if response && response.code.to_i == 410
|
|
99
|
+
raise WatchStream::Gone.new("watch resourceVersion expired (410 Gone)", code: 410)
|
|
100
|
+
end
|
|
101
|
+
|
|
102
|
+
raise WatchStream::Error.from_response("Watch request failed", source)
|
|
103
|
+
end
|
|
104
|
+
|
|
105
|
+
# A transfer is clean when the completed response reports success. A
|
|
106
|
+
# Typhoeus response can keep code == 200 (read from the headers) while
|
|
107
|
+
# success? is false after the body transfer failed mid-stream — that
|
|
108
|
+
# must surface as an error (so the informer backs off) rather than a
|
|
109
|
+
# clean close. When only headers exist (no completed response), the
|
|
110
|
+
# status code is all we have, so fall back to the code check.
|
|
111
|
+
def transfer_ok?(response, headers_seen)
|
|
112
|
+
# A completed response knows about body-transfer failures the status
|
|
113
|
+
# code alone does not reflect, so trust success? when we have one.
|
|
114
|
+
return response.success? if response && response.respond_to?(:success?)
|
|
115
|
+
|
|
116
|
+
# Headers only: no body, so the status code is the whole picture.
|
|
117
|
+
return false if headers_seen.nil?
|
|
118
|
+
|
|
119
|
+
success_code?(headers_seen)
|
|
120
|
+
end
|
|
121
|
+
|
|
122
|
+
# Splits +buffer+ into the complete newline-terminated lines and the
|
|
123
|
+
# remainder that is still waiting for its newline.
|
|
124
|
+
def split_complete_lines(buffer)
|
|
125
|
+
index = buffer.rindex("\n")
|
|
126
|
+
return [[], buffer] unless index
|
|
127
|
+
|
|
128
|
+
[buffer[0..index].split("\n"), buffer[(index + 1)..]]
|
|
129
|
+
end
|
|
130
|
+
|
|
131
|
+
def parse_event(line)
|
|
132
|
+
return nil if line.nil? || line.strip.empty?
|
|
133
|
+
|
|
134
|
+
event = JSON.parse(line)
|
|
135
|
+
return nil unless event.is_a?(Hash)
|
|
136
|
+
|
|
137
|
+
event
|
|
138
|
+
rescue JSON::ParserError => e
|
|
139
|
+
KrubyController.logger.warn("WatchStream: failed to parse watch event: #{e.message}")
|
|
140
|
+
nil
|
|
141
|
+
end
|
|
142
|
+
end
|
|
143
|
+
end
|
|
144
|
+
end
|
|
@@ -0,0 +1,335 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
require "fileutils"
|
|
4
|
+
require "yaml"
|
|
5
|
+
require "kruby_controller/cli/flag_parser"
|
|
6
|
+
require "kruby_controller/generator/crd_generator"
|
|
7
|
+
|
|
8
|
+
module KrubyController
|
|
9
|
+
module CLI
|
|
10
|
+
# `kruby-controller create api` — scaffolds a CRD class, reconciler,
|
|
11
|
+
# CRD YAML, RBAC, and manager wiring (design doc §2.10.3).
|
|
12
|
+
class CreateApiCommand
|
|
13
|
+
PROJECT_FILE = ".kruby-controller.yml"
|
|
14
|
+
ALLOWED_FLAGS = %w[
|
|
15
|
+
--group --version --kind --resource
|
|
16
|
+
--cluster-scoped --no-controller --make --force
|
|
17
|
+
-g -v -k -h --help
|
|
18
|
+
].freeze
|
|
19
|
+
|
|
20
|
+
USAGE = <<~USAGE
|
|
21
|
+
Usage: kruby-controller create api --group <G> --kind <K> [options]
|
|
22
|
+
|
|
23
|
+
Creates a new API type inside a kruby-controller project
|
|
24
|
+
(requires .kruby-controller.yml; run `kruby-controller init` first).
|
|
25
|
+
|
|
26
|
+
Options:
|
|
27
|
+
-g, --group <group> API group prefix; the full group is
|
|
28
|
+
"<group>.<domain>" from the project file (required)
|
|
29
|
+
-k, --kind <kind> Kind name, e.g. CronTask (required)
|
|
30
|
+
-v, --version <version> API version (default: v1)
|
|
31
|
+
--resource <resource> Plural resource name override
|
|
32
|
+
--cluster-scoped Resource is cluster-scoped (default: namespaced)
|
|
33
|
+
--no-controller Skip the reconciler and manager wiring
|
|
34
|
+
--make Syntax-check generated Ruby files after scaffolding
|
|
35
|
+
--force Overwrite existing generated files
|
|
36
|
+
-h, --help Show this help
|
|
37
|
+
USAGE
|
|
38
|
+
|
|
39
|
+
KIND_PATTERN = /\A[A-Z][A-Za-z0-9]*\z/
|
|
40
|
+
GROUP_PATTERN = /\A[a-z0-9]([a-z0-9-]*[a-z0-9])?\z/
|
|
41
|
+
VERSION_PATTERN = /\A[a-z0-9]+(-[a-z0-9]+)*\z/
|
|
42
|
+
|
|
43
|
+
def initialize(args, root: Dir.pwd)
|
|
44
|
+
@args = args
|
|
45
|
+
@root = root
|
|
46
|
+
end
|
|
47
|
+
|
|
48
|
+
def run
|
|
49
|
+
if FlagParser.help?(@args)
|
|
50
|
+
puts USAGE
|
|
51
|
+
return 0
|
|
52
|
+
end
|
|
53
|
+
|
|
54
|
+
group = FlagParser.flag(@args, "--group", "-g")
|
|
55
|
+
version = FlagParser.flag(@args, "--version", "-v") || "v1"
|
|
56
|
+
kind = FlagParser.flag(@args, "--kind", "-k")
|
|
57
|
+
resource = FlagParser.flag(@args, "--resource")
|
|
58
|
+
cluster_scoped = FlagParser.flag?(@args, "--cluster-scoped")
|
|
59
|
+
no_controller = FlagParser.flag?(@args, "--no-controller")
|
|
60
|
+
make = FlagParser.flag?(@args, "--make")
|
|
61
|
+
force = FlagParser.flag?(@args, "--force")
|
|
62
|
+
FlagParser.check_known!(@args, ALLOWED_FLAGS)
|
|
63
|
+
|
|
64
|
+
FlagParser.require!(group, flag_name: "--group", usage: USAGE)
|
|
65
|
+
FlagParser.require!(kind, flag_name: "--kind", usage: USAGE)
|
|
66
|
+
|
|
67
|
+
unless KIND_PATTERN.match?(kind)
|
|
68
|
+
raise UsageError, "kind must start with an uppercase letter (got #{kind.inspect})"
|
|
69
|
+
end
|
|
70
|
+
unless GROUP_PATTERN.match?(group)
|
|
71
|
+
raise UsageError, "group must be a lowercase DNS label (got #{group.inspect})"
|
|
72
|
+
end
|
|
73
|
+
unless VERSION_PATTERN.match?(version)
|
|
74
|
+
raise UsageError, "version must be lowercase alphanumerics separated by '-' (got #{version.inspect})"
|
|
75
|
+
end
|
|
76
|
+
|
|
77
|
+
# A valid lowercase DNS label also rejects '/' and other path
|
|
78
|
+
# separators, so the value cannot escape config/crd/bases or alter
|
|
79
|
+
# the generated Ruby when interpolated.
|
|
80
|
+
if resource && !FlagParser.dns_label?(resource)
|
|
81
|
+
raise UsageError, "invalid --resource #{resource.inspect}; must be a lowercase DNS label (e.g. crontasks)"
|
|
82
|
+
end
|
|
83
|
+
|
|
84
|
+
@project = load_project!
|
|
85
|
+
@domain = @project["domain"] || "example.com"
|
|
86
|
+
unless FlagParser.dns_subdomain?(@domain)
|
|
87
|
+
raise UsageError, "invalid domain #{@domain.inspect} in #{PROJECT_FILE}; must be a DNS subdomain"
|
|
88
|
+
end
|
|
89
|
+
|
|
90
|
+
@name = @project["name"] || FlagParser.normalize_dns_label(File.basename(@root)) || File.basename(@root)
|
|
91
|
+
@group = "#{group}.#{@domain}"
|
|
92
|
+
@version = version
|
|
93
|
+
@kind = kind
|
|
94
|
+
@resource = resource
|
|
95
|
+
@namespaced = !cluster_scoped
|
|
96
|
+
@force = force
|
|
97
|
+
@snake = snake_case(kind)
|
|
98
|
+
# Kubernetes RBAC object names are DNS subdomains (no underscores),
|
|
99
|
+
# so derive a hyphenated name for the ClusterRole/Binding while
|
|
100
|
+
# @snake keeps the underscores for Ruby file names.
|
|
101
|
+
@rbac_name = @snake.tr("_", "-")
|
|
102
|
+
@plural = resource || default_plural
|
|
103
|
+
@created = []
|
|
104
|
+
|
|
105
|
+
scaffold_crd_class
|
|
106
|
+
scaffold_rbac
|
|
107
|
+
unless no_controller
|
|
108
|
+
scaffold_reconciler
|
|
109
|
+
update_manager
|
|
110
|
+
end
|
|
111
|
+
make_check if make
|
|
112
|
+
|
|
113
|
+
puts "Created API: #{@group}/#{@version} Kind=#{@kind} (scope: #{@namespaced ? 'Namespaced' : 'Cluster'})"
|
|
114
|
+
@created.each { |p| puts " #{p}" }
|
|
115
|
+
puts "Done."
|
|
116
|
+
0
|
|
117
|
+
end
|
|
118
|
+
|
|
119
|
+
private
|
|
120
|
+
|
|
121
|
+
def load_project!
|
|
122
|
+
path = File.join(@root, PROJECT_FILE)
|
|
123
|
+
unless File.file?(path)
|
|
124
|
+
raise UsageError,
|
|
125
|
+
"not a kruby-controller project (no #{PROJECT_FILE} in #{Dir.pwd}); run `kruby-controller init` first"
|
|
126
|
+
end
|
|
127
|
+
|
|
128
|
+
YAML.safe_load(File.read(path)) || {}
|
|
129
|
+
end
|
|
130
|
+
|
|
131
|
+
def default_plural
|
|
132
|
+
word = @kind.downcase
|
|
133
|
+
if word.end_with?("s", "x", "z", "ch", "sh")
|
|
134
|
+
"#{word}es"
|
|
135
|
+
elsif word.end_with?("y") && !%w[a e i o u].include?(word[-2])
|
|
136
|
+
"#{word[0..-2]}ies"
|
|
137
|
+
else
|
|
138
|
+
"#{word}s"
|
|
139
|
+
end
|
|
140
|
+
end
|
|
141
|
+
|
|
142
|
+
def snake_case(str)
|
|
143
|
+
str.sub(/([A-Z\d]+)([A-Z][a-z])/, '\1_\2')
|
|
144
|
+
.sub(/([a-z\d])([A-Z])/, '\1_\2')
|
|
145
|
+
.downcase
|
|
146
|
+
end
|
|
147
|
+
|
|
148
|
+
def crd_class_path
|
|
149
|
+
File.join(@root, "pkg/crds", "#{@snake}.rb")
|
|
150
|
+
end
|
|
151
|
+
|
|
152
|
+
def scaffold_crd_class
|
|
153
|
+
namespaced_line = " self.namespaced = #{@namespaced}\n"
|
|
154
|
+
plural_line = @resource ? " self.plural = \"#{@resource}\"\n" : ""
|
|
155
|
+
content = +<<~RUBY
|
|
156
|
+
# frozen_string_literal: true
|
|
157
|
+
|
|
158
|
+
require "kruby-controller"
|
|
159
|
+
|
|
160
|
+
# #{@kind} is the Schema for the #{@group} #{@plural} API.
|
|
161
|
+
class #{@kind}
|
|
162
|
+
include KrubyController::CRD
|
|
163
|
+
|
|
164
|
+
self.group = "#{@group}"
|
|
165
|
+
self.version = "#{@version}"
|
|
166
|
+
self.kind = "#{@kind}"
|
|
167
|
+
RUBY
|
|
168
|
+
content << plural_line if @resource
|
|
169
|
+
content << namespaced_line
|
|
170
|
+
content << <<~RUBY
|
|
171
|
+
|
|
172
|
+
# Spec
|
|
173
|
+
attribute :example, type: :string, description: "TODO: describe this field"
|
|
174
|
+
|
|
175
|
+
# Status
|
|
176
|
+
status_attribute :example, type: :string, description: "TODO: describe this field"
|
|
177
|
+
end
|
|
178
|
+
RUBY
|
|
179
|
+
|
|
180
|
+
write_generated(crd_class_path, content)
|
|
181
|
+
scaffold_crd_yaml
|
|
182
|
+
end
|
|
183
|
+
|
|
184
|
+
def scaffold_crd_yaml
|
|
185
|
+
if Object.const_defined?(@kind, false)
|
|
186
|
+
raise UsageError, "top-level constant #{@kind} is already defined; choose a different --kind"
|
|
187
|
+
end
|
|
188
|
+
|
|
189
|
+
code = File.read(crd_class_path)
|
|
190
|
+
# Force the class declaration onto Object so eval does not nest the
|
|
191
|
+
# constant inside the CLI class's lexical scope.
|
|
192
|
+
code = code.sub(/^class\s+#{Regexp.escape(@kind)}\b/m) { |m| m.sub(@kind, "::#{@kind}") }
|
|
193
|
+
yaml =
|
|
194
|
+
begin
|
|
195
|
+
eval(code, binding, crd_class_path) # rubocop:disable Security/Eval
|
|
196
|
+
Generator::CrdGenerator.new(Object.const_get(@kind)).generate_yaml
|
|
197
|
+
ensure
|
|
198
|
+
Object.send(:remove_const, @kind) if Object.const_defined?(@kind, false)
|
|
199
|
+
end
|
|
200
|
+
|
|
201
|
+
write_generated(File.join(@root, "config/crd/bases", "#{@group}_#{@plural}.yaml"), yaml)
|
|
202
|
+
end
|
|
203
|
+
|
|
204
|
+
def scaffold_rbac
|
|
205
|
+
role = <<~YAML
|
|
206
|
+
apiVersion: rbac.authorization.k8s.io/v1
|
|
207
|
+
kind: ClusterRole
|
|
208
|
+
metadata:
|
|
209
|
+
name: #{@rbac_name}-role
|
|
210
|
+
rules:
|
|
211
|
+
- apiGroups: ["#{@group}"]
|
|
212
|
+
resources: ["#{@plural}"]
|
|
213
|
+
verbs: ["get", "list", "watch", "create", "update", "patch", "delete"]
|
|
214
|
+
- apiGroups: ["#{@group}"]
|
|
215
|
+
resources: ["#{@plural}/status"]
|
|
216
|
+
verbs: ["get", "update", "patch"]
|
|
217
|
+
YAML
|
|
218
|
+
# Bind this API's ClusterRole to the manager ServiceAccount so the
|
|
219
|
+
# deployment can access the custom resource.
|
|
220
|
+
binding = <<~YAML
|
|
221
|
+
---
|
|
222
|
+
apiVersion: rbac.authorization.k8s.io/v1
|
|
223
|
+
kind: ClusterRoleBinding
|
|
224
|
+
metadata:
|
|
225
|
+
name: #{@name}-#{@rbac_name}-rolebinding
|
|
226
|
+
roleRef:
|
|
227
|
+
apiGroup: rbac.authorization.k8s.io
|
|
228
|
+
kind: ClusterRole
|
|
229
|
+
name: #{@rbac_name}-role
|
|
230
|
+
subjects:
|
|
231
|
+
- kind: ServiceAccount
|
|
232
|
+
name: #{@name}-manager
|
|
233
|
+
namespace: #{@name}
|
|
234
|
+
YAML
|
|
235
|
+
write_generated(File.join(@root, "config/rbac", "#{@snake}_role.yaml"), role + binding)
|
|
236
|
+
end
|
|
237
|
+
|
|
238
|
+
def reconciler_path
|
|
239
|
+
File.join(@root, "pkg/reconcilers", "#{@snake}_reconciler.rb")
|
|
240
|
+
end
|
|
241
|
+
|
|
242
|
+
def scaffold_reconciler
|
|
243
|
+
content = <<~RUBY
|
|
244
|
+
# frozen_string_literal: true
|
|
245
|
+
|
|
246
|
+
require "kruby-controller"
|
|
247
|
+
|
|
248
|
+
class #{@kind}Reconciler < KrubyController::Reconciler
|
|
249
|
+
def reconcile(request)
|
|
250
|
+
# TODO: implement the reconcile logic for #{@kind}.
|
|
251
|
+
# Read the object (cache / api client), reconcile the desired
|
|
252
|
+
# state, then return one of:
|
|
253
|
+
# KrubyController::Result.ok
|
|
254
|
+
# KrubyController::Result.retry_after(30)
|
|
255
|
+
# KrubyController::Result.requeue
|
|
256
|
+
KrubyController::Result.ok
|
|
257
|
+
end
|
|
258
|
+
end
|
|
259
|
+
RUBY
|
|
260
|
+
write_generated(reconciler_path, content)
|
|
261
|
+
end
|
|
262
|
+
|
|
263
|
+
def manager_path
|
|
264
|
+
File.join(@root, "cmd/manager.rb")
|
|
265
|
+
end
|
|
266
|
+
|
|
267
|
+
def update_manager
|
|
268
|
+
path = manager_path
|
|
269
|
+
unless File.file?(path)
|
|
270
|
+
warn "warning: #{path} not found; skipping manager wiring"
|
|
271
|
+
return
|
|
272
|
+
end
|
|
273
|
+
|
|
274
|
+
content = File.read(path)
|
|
275
|
+
changed = false
|
|
276
|
+
|
|
277
|
+
require_line = "require_relative \"../pkg/crds/#{@snake}\""
|
|
278
|
+
unless content.include?(require_line)
|
|
279
|
+
content = content.sub(/(require "kruby-controller")/) { |m| "#{m}\n#{require_line}" }
|
|
280
|
+
changed = true
|
|
281
|
+
end
|
|
282
|
+
|
|
283
|
+
reconciler_require = "require_relative \"../pkg/reconcilers/#{@snake}_reconciler\""
|
|
284
|
+
unless content.include?(reconciler_require)
|
|
285
|
+
crd_line = "require_relative \"../pkg/crds/#{@snake}\""
|
|
286
|
+
content = content.sub(crd_line) { |m| "#{m}\n#{reconciler_require}" }
|
|
287
|
+
changed = true
|
|
288
|
+
end
|
|
289
|
+
|
|
290
|
+
add_line = "manager.add(#{@kind}Reconciler, for: #{@kind})"
|
|
291
|
+
unless content.include?(add_line)
|
|
292
|
+
if content.match?(/^manager\.start\s*$/)
|
|
293
|
+
content = content.sub(/^manager\.start\s*$/,
|
|
294
|
+
"manager.add(#{@kind}Reconciler, for: #{@kind})\nmanager.start")
|
|
295
|
+
else
|
|
296
|
+
warn "warning: could not find `manager.start` in #{path}; add `#{add_line}` manually"
|
|
297
|
+
return
|
|
298
|
+
end
|
|
299
|
+
changed = true
|
|
300
|
+
end
|
|
301
|
+
|
|
302
|
+
return unless changed
|
|
303
|
+
|
|
304
|
+
File.write(path, content)
|
|
305
|
+
@created << relative_to_root(path)
|
|
306
|
+
end
|
|
307
|
+
|
|
308
|
+
def write_generated(path, content)
|
|
309
|
+
if File.exist?(path) && !@force
|
|
310
|
+
raise UsageError, "file exists: #{relative_to_root(path)} (use --force to overwrite)"
|
|
311
|
+
end
|
|
312
|
+
|
|
313
|
+
FileUtils.mkdir_p(File.dirname(path))
|
|
314
|
+
File.write(path, content)
|
|
315
|
+
@created << relative_to_root(path)
|
|
316
|
+
end
|
|
317
|
+
|
|
318
|
+
def make_check
|
|
319
|
+
ruby_files = @created.select { |p| p.end_with?(".rb") }.map { |p| File.join(@root, p) }
|
|
320
|
+
return if ruby_files.empty?
|
|
321
|
+
|
|
322
|
+
ruby_files.each do |file|
|
|
323
|
+
ok = system("ruby", "-c", file, out: File::NULL, err: File::NULL)
|
|
324
|
+
raise UsageError, "syntax check failed for #{relative_to_root(file)}" unless ok
|
|
325
|
+
end
|
|
326
|
+
|
|
327
|
+
puts "make: syntax check passed (#{ruby_files.size} file(s))"
|
|
328
|
+
end
|
|
329
|
+
|
|
330
|
+
def relative_to_root(path)
|
|
331
|
+
path.sub(%r{\A#{Regexp.escape(@root)}/}, "")
|
|
332
|
+
end
|
|
333
|
+
end
|
|
334
|
+
end
|
|
335
|
+
end
|
|
@@ -0,0 +1,85 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
module KrubyController
|
|
4
|
+
module CLI
|
|
5
|
+
# Raised for invalid command line usage (missing/unknown flags, bad values).
|
|
6
|
+
class UsageError < StandardError; end
|
|
7
|
+
|
|
8
|
+
# Minimal ARGV-style flag parser shared by CLI commands.
|
|
9
|
+
module FlagParser
|
|
10
|
+
module_function
|
|
11
|
+
|
|
12
|
+
HELP_FLAGS = %w[-h --help].freeze
|
|
13
|
+
|
|
14
|
+
def help?(args)
|
|
15
|
+
args.any? { |a| HELP_FLAGS.include?(a) }
|
|
16
|
+
end
|
|
17
|
+
|
|
18
|
+
# True if any of the boolean flags is present.
|
|
19
|
+
def flag?(args, *names)
|
|
20
|
+
names.any? { |name| args.include?(name) }
|
|
21
|
+
end
|
|
22
|
+
|
|
23
|
+
# Value of the first present value flag (nil when absent). Raises
|
|
24
|
+
# UsageError when a located value flag is unterminated (present but with
|
|
25
|
+
# no following value), so `init --repo --force` is reported as malformed
|
|
26
|
+
# instead of silently scaffolding into the current directory.
|
|
27
|
+
def flag(args, *names)
|
|
28
|
+
names.each do |name|
|
|
29
|
+
idx = args.index(name)
|
|
30
|
+
next unless idx
|
|
31
|
+
|
|
32
|
+
value = args[idx + 1]
|
|
33
|
+
raise UsageError, "flag #{name} requires a value" if value.nil? || value.start_with?("-")
|
|
34
|
+
|
|
35
|
+
return value
|
|
36
|
+
end
|
|
37
|
+
nil
|
|
38
|
+
end
|
|
39
|
+
|
|
40
|
+
# Raises UsageError when a required flag value is missing.
|
|
41
|
+
def require!(value, flag_name:, usage:)
|
|
42
|
+
return if value && !value.empty?
|
|
43
|
+
|
|
44
|
+
raise UsageError, "missing required flag #{flag_name}\n#{usage}"
|
|
45
|
+
end
|
|
46
|
+
|
|
47
|
+
# Raises UsageError when an unknown option (any dash-prefixed token,
|
|
48
|
+
# including short options like `-x`) is present.
|
|
49
|
+
def check_known!(args, allowed)
|
|
50
|
+
unknown = args.select { |a| a.start_with?("-") && !allowed.include?(a) }
|
|
51
|
+
return if unknown.empty?
|
|
52
|
+
|
|
53
|
+
raise UsageError, "unknown flag(s): #{unknown.join(', ')}"
|
|
54
|
+
end
|
|
55
|
+
|
|
56
|
+
# A Kubernetes DNS label: lowercase alphanumerics and '-', 1-63 chars,
|
|
57
|
+
# starting and ending with an alphanumeric.
|
|
58
|
+
def dns_label?(name)
|
|
59
|
+
name.is_a?(String) && name.match?(/\A[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\z/)
|
|
60
|
+
end
|
|
61
|
+
|
|
62
|
+
# A Kubernetes DNS subdomain: DNS labels separated by '.' (e.g.
|
|
63
|
+
# "stable.example.com"), at most 253 characters total. A leading or
|
|
64
|
+
# trailing dot produces an empty label and is rejected.
|
|
65
|
+
def dns_subdomain?(value)
|
|
66
|
+
return false unless value.is_a?(String) && !value.empty?
|
|
67
|
+
return false if value.length > 253
|
|
68
|
+
|
|
69
|
+
# split(".", -1) keeps trailing empty fields so "example.com." is
|
|
70
|
+
# rejected instead of silently dropping the empty final label.
|
|
71
|
+
value.split(".", -1).all? { |label| dns_label?(label) }
|
|
72
|
+
end
|
|
73
|
+
|
|
74
|
+
# Strips a trailing `.git` and normalizes +name+ into a DNS label
|
|
75
|
+
# (lowercased, runs of invalid characters collapsed to '-', 1-63 chars).
|
|
76
|
+
# Returns nil when nothing valid remains.
|
|
77
|
+
def normalize_dns_label(name)
|
|
78
|
+
label = name.to_s.sub(/\.git\z/, "").downcase
|
|
79
|
+
label = label.gsub(/[^a-z0-9-]+/, "-").gsub(/-+/, "-").sub(/\A-+/, "").sub(/-\z/, "")
|
|
80
|
+
label = label[0, 63].sub(/-\z/, "")
|
|
81
|
+
dns_label?(label) ? label : nil
|
|
82
|
+
end
|
|
83
|
+
end
|
|
84
|
+
end
|
|
85
|
+
end
|