ruby-ship 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.md +21 -0
- data/README.md +175 -0
- data/docs/extensions.md +38 -0
- data/exe/ship +4 -0
- data/lib/ship/application.rb +123 -0
- data/lib/ship/cli.rb +429 -0
- data/lib/ship/compose.rb +288 -0
- data/lib/ship/config.rb +160 -0
- data/lib/ship/docker.rb +123 -0
- data/lib/ship/environment_files.rb +227 -0
- data/lib/ship/extensions.rb +70 -0
- data/lib/ship/project.rb +255 -0
- data/lib/ship/release.rb +332 -0
- data/lib/ship/services.rb +103 -0
- data/lib/ship/setup.rb +318 -0
- data/lib/ship/setup_options.rb +317 -0
- data/lib/ship/terminal.rb +205 -0
- data/lib/ship/version.rb +3 -0
- data/lib/ship.rb +6 -0
- data/schema/service-environment.json +23 -0
- data/schema/ship-release.schema.json +145 -0
- data/schema/ship.schema.json +507 -0
- data/templates/entrypoint.rb +19 -0
- data/templates/garage/Dockerfile +7 -0
- data/templates/garage/garage.toml +15 -0
- data/templates/mongodb/Dockerfile +7 -0
- data/templates/mongodb/app-user.js +4 -0
- data/templates/mongodb/bootstrap.js +28 -0
- data/templates/mongodb/bootstrap.sh +10 -0
- data/templates/mongodb/entrypoint.sh +20 -0
- data/templates/mongodb/health.js +18 -0
- data/templates/services.json +1783 -0
- metadata +70 -0
data/lib/ship/release.rb
ADDED
|
@@ -0,0 +1,332 @@
|
|
|
1
|
+
require "digest"
|
|
2
|
+
require "time"
|
|
3
|
+
require "tmpdir"
|
|
4
|
+
|
|
5
|
+
module Ship
|
|
6
|
+
class Release
|
|
7
|
+
TAG = /\A[A-Za-z0-9_][A-Za-z0-9_.-]{0,127}\z/
|
|
8
|
+
PLATFORM = /\A[a-z0-9]+\/[a-z0-9_]+(?:\/[A-Za-z0-9._-]+)?\z/
|
|
9
|
+
ID = /\Asha256:[0-9a-f]{64}\z/
|
|
10
|
+
ENV_NAMES = /^\s*(?:export\s+)?([A-Za-z_][A-Za-z0-9_]*)\s*=/
|
|
11
|
+
|
|
12
|
+
def initialize(project, terminal)
|
|
13
|
+
@project, @terminal = project, terminal
|
|
14
|
+
end
|
|
15
|
+
|
|
16
|
+
def run(command, args, verbose: false)
|
|
17
|
+
options = { verbose: verbose }
|
|
18
|
+
OptionParser.new do |cli|
|
|
19
|
+
cli.on("--tag TAG", String) { |tag| options[:tag] = tag }
|
|
20
|
+
cli.on("--platform PLATFORM", String) { |platform| options[:platform] = platform }
|
|
21
|
+
cli.on("--no-cache") { options[:no_cache] = true }
|
|
22
|
+
cli.on("-v", "--verbose") { options[:verbose] = true }
|
|
23
|
+
if command == "release"
|
|
24
|
+
cli.on("--no-env") { options[:no_env] = true }
|
|
25
|
+
cli.on("--force") { options[:force] = true }
|
|
26
|
+
end
|
|
27
|
+
end.parse!(args)
|
|
28
|
+
tag = options[:tag] || args.shift || (command == "build" ? "local" : nil)
|
|
29
|
+
raise Error, "Provide a valid Docker image tag using ship #{command} --tag TAG." unless args.empty? && tag && TAG.match?(tag)
|
|
30
|
+
if options[:platform] && !PLATFORM.match?(options[:platform])
|
|
31
|
+
raise Error, "Platform must use OS/ARCH or OS/ARCH/VARIANT."
|
|
32
|
+
end
|
|
33
|
+
|
|
34
|
+
source = source_metadata
|
|
35
|
+
@project.regenerate
|
|
36
|
+
config = @project.config
|
|
37
|
+
if command == "release" && !config.data.key?("name")
|
|
38
|
+
raise Error, "Set a stable application name with ship init --name NAME before releasing."
|
|
39
|
+
end
|
|
40
|
+
|
|
41
|
+
@terminal.title(command == "release" ? "Releasing #{config.name} · #{tag}" : "Building #{config.name} · #{tag}")
|
|
42
|
+
if command == "build"
|
|
43
|
+
with_build_stack(tag, options) do |docker, model|
|
|
44
|
+
build(docker, model, options)
|
|
45
|
+
@terminal.status("Production images built.")
|
|
46
|
+
@terminal.table(image_owners(model).map { |ref, name| [name, ref] })
|
|
47
|
+
end
|
|
48
|
+
else
|
|
49
|
+
export(tag, source, options)
|
|
50
|
+
end
|
|
51
|
+
0
|
|
52
|
+
end
|
|
53
|
+
|
|
54
|
+
private
|
|
55
|
+
|
|
56
|
+
def with_build_stack(tag, options)
|
|
57
|
+
editable = Marshal.load(Marshal.dump(@project.production.model))
|
|
58
|
+
image = "#{@project.config.name}-ruby-ship"
|
|
59
|
+
editable.fetch("services").each do |name, service|
|
|
60
|
+
if service["image"] == "#{image}:production"
|
|
61
|
+
service["image"] = "#{image}:#{tag}"
|
|
62
|
+
elsif service["build"]
|
|
63
|
+
service["image"] = "#{@project.config.name}-#{name}:#{tag}"
|
|
64
|
+
end
|
|
65
|
+
service["platform"] = options[:platform] if options[:platform]
|
|
66
|
+
end
|
|
67
|
+
Dir.mktmpdir("ruby-ship-build-") do |work|
|
|
68
|
+
file = File.join(work, "compose.yml")
|
|
69
|
+
Project.atomic_write(file, YAML.dump(editable), 0o600)
|
|
70
|
+
env = @project.path(@project.production.env_file)
|
|
71
|
+
files = [file, *@project.compose_files(true).drop(1)]
|
|
72
|
+
docker = Docker.new(@project, production: true, files: files, env_file: env)
|
|
73
|
+
model = editable
|
|
74
|
+
if files.length > 1
|
|
75
|
+
model = JSON.parse(docker.checked_compose("config", "--format", "json", "--no-interpolate", "--no-env-resolution", "--no-path-resolution"))
|
|
76
|
+
end
|
|
77
|
+
if options[:no_env]
|
|
78
|
+
defaults = required_settings(YAML.dump(model)).map { |name| "#{name}=ship_runtime_only" }.join("\n")
|
|
79
|
+
build_env = File.join(work, "build.env")
|
|
80
|
+
Project.atomic_write(build_env, "#{File.read(env)}\n#{defaults}\n", 0o600)
|
|
81
|
+
docker = Docker.new(@project, production: true, files: files, env_file: build_env)
|
|
82
|
+
end
|
|
83
|
+
|
|
84
|
+
yield docker, model
|
|
85
|
+
end
|
|
86
|
+
end
|
|
87
|
+
|
|
88
|
+
def build(docker, model, options)
|
|
89
|
+
secrets = model.fetch("secrets", {}).filter_map do |name, source|
|
|
90
|
+
file = source["file"]
|
|
91
|
+
name if file && !File.file?(File.expand_path(file, @project.root))
|
|
92
|
+
end
|
|
93
|
+
raise Error, "Add the missing build secret files for #{secrets.join(', ')} under .ship-secrets/." unless secrets.empty?
|
|
94
|
+
|
|
95
|
+
owners = image_owners(model).values
|
|
96
|
+
raise Error, "No project-owned images were found." if owners.empty?
|
|
97
|
+
|
|
98
|
+
flags = ["--pull"]
|
|
99
|
+
flags << "--no-cache" if options[:no_cache]
|
|
100
|
+
result = docker.build(*flags, *owners, terminal: @terminal,
|
|
101
|
+
message: "Building production images for #{@project.config.name}…", verbose: options[:verbose])
|
|
102
|
+
raise Error, "The Docker image build failed." unless result.zero?
|
|
103
|
+
end
|
|
104
|
+
|
|
105
|
+
def export(tag, source, options)
|
|
106
|
+
parent = @project.path("dist/ship")
|
|
107
|
+
FileUtils.mkdir_p(parent)
|
|
108
|
+
destination = File.join(parent, tag)
|
|
109
|
+
File.open(File.join(parent, ".#{tag}.lock"), File::RDWR | File::CREAT, 0o600) do |lock|
|
|
110
|
+
raise Error, "Release #{tag} is already building." unless lock.flock(File::LOCK_EX | File::LOCK_NB)
|
|
111
|
+
raise Error, "Release #{tag} already exists. Use a new tag or --force." if File.exist?(destination) && !options[:force]
|
|
112
|
+
|
|
113
|
+
with_build_stack(tag, options) do |docker, model|
|
|
114
|
+
validate_portability(model)
|
|
115
|
+
validate_environment(model) unless options[:no_env]
|
|
116
|
+
build(docker, model, options)
|
|
117
|
+
owners = image_owners(model)
|
|
118
|
+
groups = model.fetch("services").group_by { |_, service| service.fetch("image") }
|
|
119
|
+
pull = groups.reject { |ref, _| owners.key?(ref) }.values.map { |users| users.first.first }
|
|
120
|
+
if !pull.empty? && !docker.compose("pull", *pull).zero?
|
|
121
|
+
raise Error, "Pulling the release's infrastructure images failed."
|
|
122
|
+
end
|
|
123
|
+
stage = Dir.mktmpdir(".release-", parent)
|
|
124
|
+
begin
|
|
125
|
+
manifest = package(docker, stage, tag, model, groups, owners, source, options)
|
|
126
|
+
if File.exist?(destination)
|
|
127
|
+
replace(stage, destination, parent)
|
|
128
|
+
else
|
|
129
|
+
File.rename(stage, destination)
|
|
130
|
+
end
|
|
131
|
+
@terminal.status("Release created.")
|
|
132
|
+
@terminal.table([["Directory", destination], ["Platform", manifest.fetch("platform")],
|
|
133
|
+
["Built images", manifest.fetch("images").length.to_s],
|
|
134
|
+
["Registry images", manifest.fetch("pulledImages").length.to_s]])
|
|
135
|
+
@terminal.status("This release contains production settings in .env.", :warning) unless options[:no_env]
|
|
136
|
+
ensure
|
|
137
|
+
FileUtils.remove_entry(stage) if File.exist?(stage)
|
|
138
|
+
end
|
|
139
|
+
end
|
|
140
|
+
end
|
|
141
|
+
end
|
|
142
|
+
|
|
143
|
+
def replace(stage, destination, parent)
|
|
144
|
+
backup = Dir.mktmpdir(".previous-", parent)
|
|
145
|
+
old = File.join(backup, "release")
|
|
146
|
+
File.rename(destination, old)
|
|
147
|
+
begin
|
|
148
|
+
File.rename(stage, destination)
|
|
149
|
+
rescue SystemCallError
|
|
150
|
+
File.rename(old, destination)
|
|
151
|
+
raise
|
|
152
|
+
ensure
|
|
153
|
+
FileUtils.remove_entry(backup) if File.exist?(destination) && File.exist?(backup)
|
|
154
|
+
end
|
|
155
|
+
end
|
|
156
|
+
|
|
157
|
+
def validate_portability(model)
|
|
158
|
+
unless model["name"] == @project.config.name
|
|
159
|
+
raise Error, "The release's Compose project name must match ship.json."
|
|
160
|
+
end
|
|
161
|
+
model.fetch("services").each do |name, service|
|
|
162
|
+
unless service["image"].is_a?(String) && !service["image"].empty?
|
|
163
|
+
raise Error, "Service #{name} needs a release image name."
|
|
164
|
+
end
|
|
165
|
+
if service.fetch("volumes", []).any? { |entry| bind_mount?(entry) }
|
|
166
|
+
raise Error, "Service #{name} uses a host bind mount. Use a named volume or include the files in its image."
|
|
167
|
+
end
|
|
168
|
+
if service.key?("secrets") || service.key?("configs")
|
|
169
|
+
raise Error, "Service #{name} uses runtime configs or secrets. Supply runtime settings in .env."
|
|
170
|
+
end
|
|
171
|
+
if Array(service["env_file"]).any? { |entry| (entry.is_a?(Hash) ? entry["path"] : entry) != ".env.production" }
|
|
172
|
+
raise Error, "Service #{name} references a separate environment file. Move its settings into .env.production."
|
|
173
|
+
end
|
|
174
|
+
end
|
|
175
|
+
end
|
|
176
|
+
|
|
177
|
+
def validate_environment(model)
|
|
178
|
+
required = required_settings(YAML.dump(model))
|
|
179
|
+
values = File.readlines(@project.path(@project.production.env_file)).each_with_object({}) do |line, env|
|
|
180
|
+
if (match = ENV_NAMES.match(line))
|
|
181
|
+
value = match.post_match.strip
|
|
182
|
+
env[match[1]] = !value.empty? && !value.start_with?("#", %q(''), %q(""))
|
|
183
|
+
end
|
|
184
|
+
end
|
|
185
|
+
missing = required.reject { |name| values[name] }
|
|
186
|
+
return if missing.empty?
|
|
187
|
+
|
|
188
|
+
raise Error, "Set #{missing.join(', ')} in .env.production or export the release with --no-env."
|
|
189
|
+
end
|
|
190
|
+
|
|
191
|
+
def required_settings(yaml)
|
|
192
|
+
yaml.scan(Compose::ENV_VAR).filter_map { |name, operator, _, _| name if operator&.end_with?("?") }.uniq.sort
|
|
193
|
+
end
|
|
194
|
+
|
|
195
|
+
def bind_mount?(entry)
|
|
196
|
+
entry.is_a?(Hash) ? entry["type"] == "bind" : entry.include?(":") && !/\A[a-zA-Z0-9_-]+:/.match?(entry)
|
|
197
|
+
end
|
|
198
|
+
|
|
199
|
+
def image_owners(model)
|
|
200
|
+
model.fetch("services").each_with_object({}) do |(name, service), owners|
|
|
201
|
+
owners[service.fetch("image")] ||= name if service["build"]
|
|
202
|
+
end
|
|
203
|
+
end
|
|
204
|
+
|
|
205
|
+
def inspect_image(docker, ref)
|
|
206
|
+
image = JSON.parse(docker.checked("docker", "image", "inspect", ref)).first
|
|
207
|
+
if image && ID.match?(image["Id"].to_s) && image["Os"] && image["Architecture"]
|
|
208
|
+
return image
|
|
209
|
+
end
|
|
210
|
+
|
|
211
|
+
raise Error, "Docker did not report a valid ID and platform for #{ref}."
|
|
212
|
+
end
|
|
213
|
+
|
|
214
|
+
def registry_image(ref, image)
|
|
215
|
+
reference = ref.split("@", 2).first
|
|
216
|
+
repository = reference.sub(/:[^:\/]+\z/, "")
|
|
217
|
+
name = ->(value) { value.sub(/\A(?:docker\.io\/)?(?:library\/)?/, "") }
|
|
218
|
+
digest = Array(image["RepoDigests"]).filter_map do |entry|
|
|
219
|
+
repo, sha = entry.split("@", 2)
|
|
220
|
+
sha if name.call(repo) == name.call(repository) && ID.match?(sha.to_s)
|
|
221
|
+
end.first
|
|
222
|
+
raise Error, "No registry digest found for #{ref}." unless digest
|
|
223
|
+
|
|
224
|
+
"#{reference}@#{digest}"
|
|
225
|
+
end
|
|
226
|
+
|
|
227
|
+
def package(docker, stage, tag, model, groups, owners, source, options)
|
|
228
|
+
FileUtils.mkdir_p(File.join(stage, "images"))
|
|
229
|
+
services = model.fetch("services")
|
|
230
|
+
model.delete("secrets")
|
|
231
|
+
images, pulled, platforms = [], [], []
|
|
232
|
+
groups.each do |ref, users|
|
|
233
|
+
info = inspect_image(docker, ref)
|
|
234
|
+
names = users.map(&:first).sort
|
|
235
|
+
if (owner = owners[ref])
|
|
236
|
+
platforms << [info["Os"], info["Architecture"], info["Variant"]].reject { |part| part.to_s.empty? }.join("/")
|
|
237
|
+
archive = "images/#{owner}.tar"
|
|
238
|
+
target = File.join(stage, archive)
|
|
239
|
+
unless docker.run("docker", "save", "-o", target, ref).zero?
|
|
240
|
+
raise Error, "Docker could not archive #{ref}."
|
|
241
|
+
end
|
|
242
|
+
images << { "ref" => ref, "id" => info.fetch("Id"), "file" => archive,
|
|
243
|
+
"sha256" => Digest::SHA256.file(target).hexdigest, "services" => names }
|
|
244
|
+
else
|
|
245
|
+
pinned = registry_image(ref, info)
|
|
246
|
+
names.each { |name| services.fetch(name)["image"] = pinned }
|
|
247
|
+
pulled << { "ref" => pinned, "services" => names }
|
|
248
|
+
end
|
|
249
|
+
end
|
|
250
|
+
raise Error, "Release images must use a single platform." unless platforms.uniq.length == 1
|
|
251
|
+
|
|
252
|
+
services.each_value do |entry|
|
|
253
|
+
entry.delete("build")
|
|
254
|
+
entry["env_file"] = [{ "path" => ".env", "required" => false }] if entry.key?("env_file")
|
|
255
|
+
end
|
|
256
|
+
yaml = YAML.dump(model)
|
|
257
|
+
manifest = manifest_for(stage, tag, model, yaml, images, pulled, platforms.first, source, options)
|
|
258
|
+
Project.atomic_write(File.join(stage, "docker-compose.yml"), yaml)
|
|
259
|
+
write_deploy(stage, manifest["deploy"]) if manifest["deploy"]
|
|
260
|
+
write_readme(stage, manifest)
|
|
261
|
+
Project.atomic_write(File.join(stage, "release.json"), JSON.pretty_generate(manifest) + "\n")
|
|
262
|
+
manifest
|
|
263
|
+
end
|
|
264
|
+
|
|
265
|
+
def manifest_for(stage, tag, model, yaml, images, pulled, platform, source, options)
|
|
266
|
+
env = File.read(@project.path(@project.production.env_file))
|
|
267
|
+
referenced = yaml.scan(Compose::ENV_VAR)
|
|
268
|
+
required = required_settings(yaml)
|
|
269
|
+
keys = (env.scan(ENV_NAMES).flatten + required).uniq.sort
|
|
270
|
+
Project.atomic_write(File.join(stage, ".env"), env, 0o600) unless options[:no_env]
|
|
271
|
+
roles = @project.production.roles
|
|
272
|
+
services = model.fetch("services").to_h do |name, entry|
|
|
273
|
+
volumes = entry.fetch("volumes", []).filter_map do |volume|
|
|
274
|
+
volume_name = volume.is_a?(Hash) ? volume["source"] : volume.split(":", 2).first
|
|
275
|
+
volume_name if model.fetch("volumes", {}).key?(volume_name)
|
|
276
|
+
end.uniq.sort
|
|
277
|
+
health = entry["healthcheck"]
|
|
278
|
+
[name, { "role" => roles.fetch(name, "infrastructure"), "image" => entry["image"],
|
|
279
|
+
"healthcheck" => !health.nil? && !health["disable"] && Array(health["test"]).first != "NONE", "volumes" => volumes }]
|
|
280
|
+
end
|
|
281
|
+
needs = services.filter_map { |name, entry| name if entry["role"] == "infrastructure" }.sort
|
|
282
|
+
app = @project.config.app
|
|
283
|
+
commands = @project.config.deploy
|
|
284
|
+
deploy = commands.empty? ? nil : { "service" => app, "needs" => needs, "commands" => commands }
|
|
285
|
+
networks = model.fetch("networks", {}).filter_map { |key, value| value.fetch("name", key) if value && value["external"] }.uniq.sort
|
|
286
|
+
{
|
|
287
|
+
"format" => "ship-release", "app" => model.fetch("name"), "tag" => tag, "createdAt" => Time.now.utc.iso8601,
|
|
288
|
+
"builder" => { "package" => "ruby-ship", "version" => Ship::VERSION },
|
|
289
|
+
"source" => source, "platform" => platform, "compose" => "docker-compose.yml",
|
|
290
|
+
"images" => images, "pulledImages" => pulled, "http" => @project.production.http, "services" => services,
|
|
291
|
+
"framework" => @project.app.framework, "runtime" => @project.config.server,
|
|
292
|
+
"env" => { "file" => options[:no_env] ? nil : ".env", "keys" => keys,
|
|
293
|
+
"required" => required, "referenced" => referenced.map { |name, _, _, shorthand| name || shorthand }.uniq.sort },
|
|
294
|
+
"deploy" => deploy, "requires" => { "networks" => networks },
|
|
295
|
+
"console" => { "service" => app, "user" => "ship", "shell" => ["sh"], "commands" => @project.app.console }
|
|
296
|
+
}.tap { |manifest| manifest["extensions"] = @project.services.extensions.metadata if @project.services.extensions.metadata }
|
|
297
|
+
end
|
|
298
|
+
|
|
299
|
+
def write_deploy(stage, deploy)
|
|
300
|
+
lines = ["#!/bin/sh", "set -eu", 'cd "$(dirname "$0")"']
|
|
301
|
+
needs = deploy.fetch("needs")
|
|
302
|
+
lines << Shellwords.join(["docker", "compose", "up", "-d", "--wait", *needs]) unless needs.empty?
|
|
303
|
+
deploy.fetch("commands").each do |command|
|
|
304
|
+
lines << Shellwords.join(["docker", "compose", "run", "--rm", "--no-deps", "-T", deploy.fetch("service"), *command])
|
|
305
|
+
end
|
|
306
|
+
Project.atomic_write(File.join(stage, "deploy-commands.sh"), lines.join("\n") + "\n", 0o755)
|
|
307
|
+
end
|
|
308
|
+
|
|
309
|
+
def write_readme(stage, manifest)
|
|
310
|
+
instructions = manifest.fetch("images").map { |image| "docker load -i #{image.fetch('file')}" }
|
|
311
|
+
pulled = manifest.fetch("pulledImages").flat_map { |image| image.fetch("services") }
|
|
312
|
+
instructions << Shellwords.join(["docker", "compose", "pull", *pulled]) unless pulled.empty?
|
|
313
|
+
instructions << "./deploy-commands.sh" if manifest["deploy"]
|
|
314
|
+
instructions << "docker compose up -d --wait"
|
|
315
|
+
env = manifest.dig("env", "file") ? "Keep the bundled .env private." : "Provide production settings in .env."
|
|
316
|
+
text = "# Release #{manifest.fetch('tag')}\n\n#{manifest.fetch('app')} · #{manifest.fetch('platform')}\n\n#{env}\n\n" \
|
|
317
|
+
"Create any external networks in release.json before deployment. Run these commands from this directory.\n\n" \
|
|
318
|
+
"```sh\n#{instructions.join("\n")}\n```\n"
|
|
319
|
+
Project.atomic_write(File.join(stage, "README.md"), text)
|
|
320
|
+
end
|
|
321
|
+
|
|
322
|
+
def source_metadata
|
|
323
|
+
docker = Docker.new(@project)
|
|
324
|
+
commit, _, valid = docker.capture("git", "rev-parse", "HEAD")
|
|
325
|
+
return { "gitCommit" => nil, "dirty" => nil } unless valid && /\A[0-9a-f]{40,64}\z/.match?(commit.strip)
|
|
326
|
+
|
|
327
|
+
exclude = %w[dist/ship docker-compose.generated.yml docker-compose.production.generated.yml docker/ship]
|
|
328
|
+
status, _, ok = docker.capture("git", "status", "--porcelain", "--", ".", *exclude.map { |file| ":(exclude)#{file}" })
|
|
329
|
+
{ "gitCommit" => commit.strip, "dirty" => ok ? !status.strip.empty? : nil }
|
|
330
|
+
end
|
|
331
|
+
end
|
|
332
|
+
end
|
|
@@ -0,0 +1,103 @@
|
|
|
1
|
+
require_relative "config"
|
|
2
|
+
|
|
3
|
+
module Ship
|
|
4
|
+
class Services
|
|
5
|
+
GROUPS = {
|
|
6
|
+
"database" => "Database", "cache" => "Cache",
|
|
7
|
+
"broker" => "Message broker", "mail" => "Local mail", "storage" => "Object storage",
|
|
8
|
+
"search" => "Search", "broadcasting" => "Real-time messaging", "testing" => "Browser testing",
|
|
9
|
+
"frontend" => "Frontend tooling"
|
|
10
|
+
}.freeze
|
|
11
|
+
CATALOG = JSON.parse(File.read(File.join(Config::ROOT, "templates/services.json"))).merge(
|
|
12
|
+
"sqlite" => { "group" => "database", "label" => "SQLite (in-process)", "named" => false },
|
|
13
|
+
"node" => { "group" => "frontend", "label" => "Node.js (Vite HMR)", "named" => false }
|
|
14
|
+
).freeze
|
|
15
|
+
|
|
16
|
+
Instance = Struct.new(:key, :name, :host, :definition, keyword_init: true) do
|
|
17
|
+
def resource = name ? "#{key}-#{name}" : key
|
|
18
|
+
def prefix = name ? "#{name.upcase}_" : ""
|
|
19
|
+
def group = definition.fetch("group")
|
|
20
|
+
def label = definition.fetch("label")
|
|
21
|
+
|
|
22
|
+
def model(production, config)
|
|
23
|
+
raw = definition[production ? "production" : "development"]
|
|
24
|
+
return {} unless raw
|
|
25
|
+
|
|
26
|
+
model = substitute(raw, config)
|
|
27
|
+
if key == "silo" && config.data["siloImage"] == "distroless"
|
|
28
|
+
model["compose"]["image"] += "-distroless"
|
|
29
|
+
end
|
|
30
|
+
if key == "mongodb"
|
|
31
|
+
service = model.fetch("compose")
|
|
32
|
+
settings = service.fetch("environment")
|
|
33
|
+
mode = config.data.fetch("mongodbMode", "replica-set")
|
|
34
|
+
settings["SHIP_MONGO_MODE"] = mode
|
|
35
|
+
model["environment"]["#{prefix}MONGODB_REPLICA_SET"] = mode == "replica-set" ? "rs0" : ""
|
|
36
|
+
end
|
|
37
|
+
if key == "centrifugo" && %w[redis valkey].include?(config.services["cache"])
|
|
38
|
+
cache = config.services.fetch("cache")
|
|
39
|
+
address = config.renames.fetch(cache, cache)
|
|
40
|
+
model["compose"]["environment"]["CENTRIFUGO_ENGINE_REDIS_ADDRESS"] =
|
|
41
|
+
"${#{prefix}CENTRIFUGO_REDIS_ADDRESS:-redis://#{address}:6379}"
|
|
42
|
+
end
|
|
43
|
+
model
|
|
44
|
+
end
|
|
45
|
+
|
|
46
|
+
private
|
|
47
|
+
|
|
48
|
+
def substitute(value, config)
|
|
49
|
+
case value
|
|
50
|
+
when String
|
|
51
|
+
substitutions = { "SHIPSEED_" => prefix, "shiphostname" => host, "#{key}-shipseed" => resource,
|
|
52
|
+
"ship-app.test:8000" => "ship-app.test:#{config.port}", "SHIP_APP_HOST" => config.app,
|
|
53
|
+
"SHIP_APP_PORT" => config.port.to_s }
|
|
54
|
+
value.gsub(Regexp.union(substitutions.keys)) { |token| substitutions.fetch(token) }
|
|
55
|
+
when Hash
|
|
56
|
+
value.to_h { |key, entry| [substitute(key, config), substitute(entry, config)] }
|
|
57
|
+
when Array
|
|
58
|
+
value.map { |entry| substitute(entry, config) }
|
|
59
|
+
else
|
|
60
|
+
value
|
|
61
|
+
end
|
|
62
|
+
end
|
|
63
|
+
end
|
|
64
|
+
|
|
65
|
+
attr_reader :instances, :catalog, :extensions
|
|
66
|
+
|
|
67
|
+
def initialize(config)
|
|
68
|
+
@extensions = Extensions.new(config)
|
|
69
|
+
@catalog = CATALOG.merge(extensions.services)
|
|
70
|
+
@primary_database = config.services["database"]
|
|
71
|
+
@instances = config.services.map { |group, key| instance(config, group, key) }
|
|
72
|
+
@instances += config.instances.map do |entry|
|
|
73
|
+
instance(config, entry.fetch("group"), entry.fetch("service"), entry.fetch("name"))
|
|
74
|
+
end
|
|
75
|
+
names = instances.filter_map(&:name)
|
|
76
|
+
raise Error, "Named service instances must have unique names and environment prefixes." if names.uniq != names
|
|
77
|
+
|
|
78
|
+
defaults = instances.map(&:resource) + config.processes.keys + ["app"]
|
|
79
|
+
unknown = config.renames.keys - defaults
|
|
80
|
+
raise Error, "serviceNames refers to unknown services #{unknown.join(', ')}." unless unknown.empty?
|
|
81
|
+
|
|
82
|
+
hosts = instances.map(&:host) + config.processes.keys.map { |key| config.renames.fetch(key, key) } + [config.app]
|
|
83
|
+
raise Error, "Choose unique Compose names for the app, services, and processes." unless hosts.uniq == hosts && defaults.uniq == defaults
|
|
84
|
+
end
|
|
85
|
+
|
|
86
|
+
def database(name = nil)
|
|
87
|
+
candidates = instances.select { |entry| entry.group == "database" && entry.name == name }
|
|
88
|
+
candidates.find { |entry| entry.resource == @primary_database } || candidates.first
|
|
89
|
+
end
|
|
90
|
+
|
|
91
|
+
private
|
|
92
|
+
|
|
93
|
+
def instance(config, group, key, name = nil)
|
|
94
|
+
definition = catalog[key]
|
|
95
|
+
legacy_clickhouse = group == "analytics" && key == "clickhouse"
|
|
96
|
+
raise Error, "Unknown provider #{key.inspect} for #{group}." unless definition && (definition["group"] == group || legacy_clickhouse)
|
|
97
|
+
raise Error, "#{definition['label']} does not support named instances." if name && !definition["named"]
|
|
98
|
+
|
|
99
|
+
resource = name ? "#{key}-#{name}" : key
|
|
100
|
+
Instance.new(key: key, name: name, host: config.renames.fetch(resource, resource), definition: definition)
|
|
101
|
+
end
|
|
102
|
+
end
|
|
103
|
+
end
|