trellis-pg 0.2.0 → 0.3.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 +4 -4
- data/README.md +327 -25
- data/ext/trellis_ruby/Cargo.lock +5 -5
- data/ext/trellis_ruby/Cargo.toml +3 -3
- data/ext/trellis_ruby/src/lib.rs +98 -11
- data/lib/trellis/instance.rb +4 -0
- data/lib/trellis/log_bridge.rb +201 -0
- data/lib/trellis/metrics.rb +129 -11
- data/lib/trellis/migration.rb +34 -0
- data/lib/trellis/pg.rb +37 -0
- data/lib/trellis/railtie.rb +119 -3
- data/lib/trellis/release_check.rb +165 -0
- data/lib/trellis/schema_dump.rb +26 -2
- data/lib/trellis/target.rb +141 -0
- data/lib/trellis/test_support.rb +176 -2
- data/lib/trellis/version.rb +1 -1
- metadata +4 -1
|
@@ -0,0 +1,201 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
module Trellis
|
|
4
|
+
# Forwards the engine's log lines to a Logger: Trellis.logger= installs
|
|
5
|
+
# trellis-embed's pull-based tracing subscriber in this extension's native
|
|
6
|
+
# library, and a Ruby thread drains its bounded queue into the Logger every
|
|
7
|
+
# 100 ms. Engine threads only append to the queue; nothing calls into the
|
|
8
|
+
# VM from them. Levels, drops, fork and exit behaviour: "Logs" in the
|
|
9
|
+
# README.
|
|
10
|
+
class LogBridge
|
|
11
|
+
# Seconds between drains.
|
|
12
|
+
INTERVAL = 0.1
|
|
13
|
+
# Records per call into the extension: one call holds the GVL for no
|
|
14
|
+
# longer than this many lines take to copy.
|
|
15
|
+
BATCH = 500
|
|
16
|
+
# Batches per drain_once: enough to empty a full queue (10,000 lines).
|
|
17
|
+
MAX_BATCHES = 21
|
|
18
|
+
|
|
19
|
+
# The engine's level words, as Logger's severity integers (written out,
|
|
20
|
+
# so the gem needs no `require "logger"`, a bundled gem since Ruby 4.0).
|
|
21
|
+
# Its trace has no Logger equivalent.
|
|
22
|
+
SEVERITIES = { error: 3, warn: 2, info: 1, debug: 0, trace: 0 }.freeze
|
|
23
|
+
|
|
24
|
+
# A Logger level, as the most verbose engine level worth forwarding. The
|
|
25
|
+
# engine has no level above error.
|
|
26
|
+
FILTERS = { debug: "debug", info: "info", warn: "warn", error: "error", fatal: "off", unknown: "off" }.freeze
|
|
27
|
+
|
|
28
|
+
@lock = Mutex.new
|
|
29
|
+
@current = nil
|
|
30
|
+
|
|
31
|
+
class << self
|
|
32
|
+
# The bridge Trellis.logger= installed, or nil.
|
|
33
|
+
attr_reader :current
|
|
34
|
+
|
|
35
|
+
# Replaces the process's bridge with one for `logger` (stopping the
|
|
36
|
+
# previous one), or with none if `logger` is nil: the engine's lines then
|
|
37
|
+
# go nowhere. `level` is the most verbose level forwarded, a Logger
|
|
38
|
+
# level (:info, "warn", 0); the default is logger.level.
|
|
39
|
+
# Returns the new bridge.
|
|
40
|
+
def install(logger, level: nil)
|
|
41
|
+
@lock.synchronize do
|
|
42
|
+
previous = @current
|
|
43
|
+
previous&.stop
|
|
44
|
+
@current = nil
|
|
45
|
+
if logger.nil?
|
|
46
|
+
Native.set_log_level("off") if previous
|
|
47
|
+
return nil
|
|
48
|
+
end
|
|
49
|
+
@current = new(logger, level: level).start
|
|
50
|
+
end
|
|
51
|
+
end
|
|
52
|
+
|
|
53
|
+
# Starts the bridge's thread again in a process forked since it started.
|
|
54
|
+
# What Instance.connect calls before it connects.
|
|
55
|
+
def ensure_running
|
|
56
|
+
@lock.synchronize { @current }&.ensure_running
|
|
57
|
+
end
|
|
58
|
+
|
|
59
|
+
# Stops the current bridge, draining what is left. Instance's at_exit
|
|
60
|
+
# hook calls it once every instance is down.
|
|
61
|
+
def stop_current
|
|
62
|
+
@lock.synchronize { @current }&.stop
|
|
63
|
+
end
|
|
64
|
+
|
|
65
|
+
# A Logger level (Integer or word) as the engine's level filter word.
|
|
66
|
+
# Raises ValidationError for anything else.
|
|
67
|
+
def filter(level)
|
|
68
|
+
case level
|
|
69
|
+
when Integer then FILTERS.values.fetch(level.clamp(0, FILTERS.size - 1))
|
|
70
|
+
when Symbol, String
|
|
71
|
+
FILTERS.fetch(level.to_s.downcase.to_sym) { invalid_level!(level) }
|
|
72
|
+
else invalid_level!(level)
|
|
73
|
+
end
|
|
74
|
+
end
|
|
75
|
+
|
|
76
|
+
private
|
|
77
|
+
|
|
78
|
+
def invalid_level!(level)
|
|
79
|
+
raise ValidationError,
|
|
80
|
+
"a log level is one of #{FILTERS.keys.map(&:inspect).join(', ')} or a Logger severity " \
|
|
81
|
+
"integer, got: #{level.inspect}"
|
|
82
|
+
end
|
|
83
|
+
end
|
|
84
|
+
|
|
85
|
+
attr_reader :logger
|
|
86
|
+
|
|
87
|
+
def initialize(logger, level: nil)
|
|
88
|
+
unless logger.respond_to?(:add)
|
|
89
|
+
raise ValidationError, "the logger must respond to add (a Logger), got: #{logger.inspect}"
|
|
90
|
+
end
|
|
91
|
+
|
|
92
|
+
@logger = logger
|
|
93
|
+
@filter = self.class.filter(level || logger.level)
|
|
94
|
+
@drain_lock = Mutex.new
|
|
95
|
+
@state = Mutex.new
|
|
96
|
+
@pid = nil
|
|
97
|
+
@thread = nil
|
|
98
|
+
@stopped = false
|
|
99
|
+
@last_error = nil
|
|
100
|
+
end
|
|
101
|
+
|
|
102
|
+
# Installs the subscriber in the native library (once per process, however
|
|
103
|
+
# many bridges) and starts the thread. Raises ConflictError if another
|
|
104
|
+
# subscriber in that library was installed first.
|
|
105
|
+
def start
|
|
106
|
+
Native.install_log_bridge(@filter)
|
|
107
|
+
ensure_running
|
|
108
|
+
self
|
|
109
|
+
end
|
|
110
|
+
|
|
111
|
+
# Starts the thread if this process hasn't (it was forked since). A
|
|
112
|
+
# process forked from the one that started the bridge begins with an empty
|
|
113
|
+
# queue: the lines the parent hadn't drained yet are the parent's to log.
|
|
114
|
+
def ensure_running
|
|
115
|
+
@state.synchronize do
|
|
116
|
+
return self if @stopped || (@pid == Process.pid && @thread&.alive?)
|
|
117
|
+
|
|
118
|
+
discard_queue if @pid && @pid != Process.pid
|
|
119
|
+
@pid = Process.pid
|
|
120
|
+
@thread = Thread.new { run }
|
|
121
|
+
@thread.name = "trellis-log-bridge"
|
|
122
|
+
@thread.report_on_exception = false
|
|
123
|
+
end
|
|
124
|
+
self
|
|
125
|
+
end
|
|
126
|
+
|
|
127
|
+
# Whether this process's thread is running.
|
|
128
|
+
def running?
|
|
129
|
+
@state.synchronize { @pid == Process.pid && !!@thread&.alive? }
|
|
130
|
+
end
|
|
131
|
+
|
|
132
|
+
# Changes the most verbose level forwarded: a Logger level, as for
|
|
133
|
+
# install.
|
|
134
|
+
def level=(level)
|
|
135
|
+
@filter = self.class.filter(level)
|
|
136
|
+
Native.set_log_level(@filter)
|
|
137
|
+
end
|
|
138
|
+
|
|
139
|
+
# Forwards every line queued so far to the Logger before returning,
|
|
140
|
+
# rather than on the next tick. The thread calls it; tests and a host
|
|
141
|
+
# that wants the engine's last lines logged now can too. Returns true if
|
|
142
|
+
# lines may remain, because the queue held more than one call forwards.
|
|
143
|
+
def drain_once
|
|
144
|
+
@drain_lock.synchronize do
|
|
145
|
+
MAX_BATCHES.times do
|
|
146
|
+
records, dropped = Native.take_log_records(BATCH)
|
|
147
|
+
if dropped.positive?
|
|
148
|
+
logger.add(SEVERITIES.fetch(:warn), "Trellis dropped #{dropped} log lines: the Logger bridge fell behind", "trellis")
|
|
149
|
+
end
|
|
150
|
+
records.each { |level, target, message| logger.add(SEVERITIES.fetch(level), message, target) }
|
|
151
|
+
return false if records.size < BATCH
|
|
152
|
+
end
|
|
153
|
+
true
|
|
154
|
+
end
|
|
155
|
+
end
|
|
156
|
+
|
|
157
|
+
# Stops the thread and forwards what is left. Does nothing in a process
|
|
158
|
+
# forked since the bridge started and not started again: the queue it
|
|
159
|
+
# inherited isn't its own to log. A stopped bridge stays stopped.
|
|
160
|
+
def stop
|
|
161
|
+
thread = @state.synchronize do
|
|
162
|
+
@stopped = true
|
|
163
|
+
@thread if @pid == Process.pid
|
|
164
|
+
end
|
|
165
|
+
return unless thread
|
|
166
|
+
|
|
167
|
+
begin
|
|
168
|
+
thread.wakeup
|
|
169
|
+
rescue ThreadError
|
|
170
|
+
# Already finished.
|
|
171
|
+
end
|
|
172
|
+
thread.join
|
|
173
|
+
drain_safely
|
|
174
|
+
end
|
|
175
|
+
|
|
176
|
+
private
|
|
177
|
+
|
|
178
|
+
def run
|
|
179
|
+
until @stopped
|
|
180
|
+
sleep INTERVAL
|
|
181
|
+
drain_safely
|
|
182
|
+
end
|
|
183
|
+
end
|
|
184
|
+
|
|
185
|
+
# A Logger that raises (a closed stream) mustn't end the thread, or make
|
|
186
|
+
# the next drain's lines vanish: warn once per distinct failure, drop
|
|
187
|
+
# nothing it hasn't already taken, and carry on.
|
|
188
|
+
def drain_safely
|
|
189
|
+
nil while drain_once
|
|
190
|
+
@last_error = nil
|
|
191
|
+
rescue StandardError => e
|
|
192
|
+
failure = "#{e.class}: #{e.message}"
|
|
193
|
+
warn "trellis: forwarding the engine's log lines failed: #{failure}" unless failure == @last_error
|
|
194
|
+
@last_error = failure
|
|
195
|
+
end
|
|
196
|
+
|
|
197
|
+
def discard_queue
|
|
198
|
+
nil while Native.take_log_records(BATCH).first.size == BATCH
|
|
199
|
+
end
|
|
200
|
+
end
|
|
201
|
+
end
|
data/lib/trellis/metrics.rb
CHANGED
|
@@ -13,17 +13,11 @@ module Trellis
|
|
|
13
13
|
# running handle and 0 after its last one shuts down; the other gauges of a
|
|
14
14
|
# stopped instance disappear after 60 seconds. See docs/observability.md.
|
|
15
15
|
#
|
|
16
|
-
# The binding opens no port.
|
|
17
|
-
#
|
|
18
|
-
#
|
|
19
|
-
#
|
|
20
|
-
#
|
|
21
|
-
# [200, { "content-type" => "text/plain; version=0.0.4" }, [Trellis::Metrics.render_prometheus]]
|
|
22
|
-
# }
|
|
23
|
-
#
|
|
24
|
-
# In a forking server each worker process has its own registry, holding
|
|
25
|
-
# only its own handles' series, so scrape every worker (or run the worker
|
|
26
|
-
# handle, staging: true, in a process of its own and scrape that).
|
|
16
|
+
# The binding opens no port. Trellis::Metrics::RackApp serves the text from
|
|
17
|
+
# a route of its own; Trellis::Metrics::Middleware appends it to the body of
|
|
18
|
+
# an exporter's route the app already has. Most series are set only in the
|
|
19
|
+
# process running the staging or drain work, so scrape that one (README,
|
|
20
|
+
# Metrics).
|
|
27
21
|
#
|
|
28
22
|
# A process forked while its parent had an engine running may have
|
|
29
23
|
# inherited the registry's lock held, so rendering there raises
|
|
@@ -34,5 +28,129 @@ module Trellis
|
|
|
34
28
|
def self.render_prometheus
|
|
35
29
|
Native.render_prometheus
|
|
36
30
|
end
|
|
31
|
+
|
|
32
|
+
# A Rack app answering GET and HEAD with render_prometheus, in the
|
|
33
|
+
# content type Prometheus expects, at whatever path it is mounted; every
|
|
34
|
+
# other method is a 405. It needs no Rack gem. Unauthenticated, as a
|
|
35
|
+
# Prometheus target is: guard it if the port is public.
|
|
36
|
+
#
|
|
37
|
+
# mount Trellis::Metrics::RackApp, at: "/metrics/trellis" # Rails
|
|
38
|
+
# map("/metrics/trellis") { run Trellis::Metrics::RackApp } # config.ru
|
|
39
|
+
class RackApp
|
|
40
|
+
CONTENT_TYPE = "text/plain; version=0.0.4; charset=utf-8"
|
|
41
|
+
|
|
42
|
+
def self.call(env)
|
|
43
|
+
new.call(env)
|
|
44
|
+
end
|
|
45
|
+
|
|
46
|
+
def call(env)
|
|
47
|
+
case env["REQUEST_METHOD"]
|
|
48
|
+
when "GET"
|
|
49
|
+
body = Metrics.render_prometheus
|
|
50
|
+
[200, headers(body), [body]]
|
|
51
|
+
when "HEAD"
|
|
52
|
+
[200, headers(Metrics.render_prometheus), []]
|
|
53
|
+
else
|
|
54
|
+
[405, { "allow" => "GET, HEAD", "content-length" => "0" }, []]
|
|
55
|
+
end
|
|
56
|
+
end
|
|
57
|
+
|
|
58
|
+
private
|
|
59
|
+
|
|
60
|
+
def headers(body)
|
|
61
|
+
{ "content-type" => CONTENT_TYPE, "content-length" => body.bytesize.to_s }
|
|
62
|
+
end
|
|
63
|
+
end
|
|
64
|
+
|
|
65
|
+
# Rack middleware that appends render_prometheus to the Prometheus text
|
|
66
|
+
# another exporter (prometheus-client's Prometheus::Middleware::Exporter,
|
|
67
|
+
# Yabeda's exporter) serves at `path`, so one scrape returns both. It
|
|
68
|
+
# needs no exporter gem and no Rack gem: it wraps any Rack app, and must
|
|
69
|
+
# sit outside the exporter it appends to.
|
|
70
|
+
#
|
|
71
|
+
# config.middleware.insert_before Prometheus::Middleware::Exporter,
|
|
72
|
+
# Trellis::Metrics::Middleware, path: "/metrics"
|
|
73
|
+
#
|
|
74
|
+
# A GET or HEAD of `path` (PATH_INFO, as the exporters match it) is
|
|
75
|
+
# answered by the wrapped app. Only a 200 with a text/plain body that is
|
|
76
|
+
# neither compressed nor chunk-framed (no Content-Encoding or
|
|
77
|
+
# Transfer-Encoding other than identity) is changed: it is buffered, a
|
|
78
|
+
# newline is added if it lacks one, the Trellis text follows, and
|
|
79
|
+
# Content-Length is the new size. Everything else passes through as
|
|
80
|
+
# the wrapped app returned it: other paths and methods, other statuses,
|
|
81
|
+
# compressed bodies (put Rack::Deflater outside this middleware), bodies
|
|
82
|
+
# with no each (Rack 3 streaming), an empty registry, and a process
|
|
83
|
+
# forked while its parent had an engine running (render_prometheus
|
|
84
|
+
# raises Trellis::ForkedHandleError there; the exporter's own series are
|
|
85
|
+
# still served). HEAD is answered as the GET would be, without the body.
|
|
86
|
+
#
|
|
87
|
+
# It does not dedupe, and the text format allows each metric name once,
|
|
88
|
+
# so don't name an app metric like one of the engine's trellis_* series.
|
|
89
|
+
class Middleware
|
|
90
|
+
def initialize(app, path: "/metrics")
|
|
91
|
+
@app = app
|
|
92
|
+
@path = path
|
|
93
|
+
end
|
|
94
|
+
|
|
95
|
+
def call(env)
|
|
96
|
+
method = env["REQUEST_METHOD"]
|
|
97
|
+
return @app.call(env) unless (method == "GET" || method == "HEAD") && env["PATH_INFO"] == @path
|
|
98
|
+
|
|
99
|
+
# A HEAD is forwarded as the GET it stands for, so the wrapped app's
|
|
100
|
+
# Content-Length is the body's real size; the body is dropped below.
|
|
101
|
+
status, headers, body = @app.call(method == "HEAD" ? env.merge("REQUEST_METHOD" => "GET") : env)
|
|
102
|
+
status, headers, body = append(status, headers, body)
|
|
103
|
+
if method == "HEAD"
|
|
104
|
+
body.close if body.respond_to?(:close)
|
|
105
|
+
body = []
|
|
106
|
+
end
|
|
107
|
+
[status, headers, body]
|
|
108
|
+
end
|
|
109
|
+
|
|
110
|
+
private
|
|
111
|
+
|
|
112
|
+
def append(status, headers, body)
|
|
113
|
+
return [status, headers, body] unless appendable?(status, headers, body)
|
|
114
|
+
|
|
115
|
+
trellis = begin
|
|
116
|
+
Metrics.render_prometheus
|
|
117
|
+
rescue ForkedHandleError
|
|
118
|
+
return [status, headers, body]
|
|
119
|
+
rescue Exception
|
|
120
|
+
# The response is dropped, so close its body as the server would.
|
|
121
|
+
body.close if body.respond_to?(:close)
|
|
122
|
+
raise
|
|
123
|
+
end
|
|
124
|
+
return [status, headers, body] if trellis.empty?
|
|
125
|
+
|
|
126
|
+
text = read(body)
|
|
127
|
+
text << "\n" unless text.empty? || text.end_with?("\n")
|
|
128
|
+
text << trellis.b
|
|
129
|
+
headers = headers.reject { |name, _| name.casecmp?("content-length") }
|
|
130
|
+
headers["content-length"] = text.bytesize.to_s
|
|
131
|
+
[status, headers, [text]]
|
|
132
|
+
end
|
|
133
|
+
|
|
134
|
+
def appendable?(status, headers, body)
|
|
135
|
+
status == 200 && body.respond_to?(:each) &&
|
|
136
|
+
header(headers, "content-type").to_s.start_with?("text/plain") &&
|
|
137
|
+
%w[content-encoding transfer-encoding].all? { |name| [nil, "identity"].include?(header(headers, name)) }
|
|
138
|
+
end
|
|
139
|
+
|
|
140
|
+
def header(headers, name)
|
|
141
|
+
headers.each { |key, value| return value.to_s.downcase if key.casecmp?(name) }
|
|
142
|
+
nil
|
|
143
|
+
end
|
|
144
|
+
|
|
145
|
+
# The whole body as bytes; the wrapped body is closed, as the server
|
|
146
|
+
# would have.
|
|
147
|
+
def read(body)
|
|
148
|
+
text = String.new(encoding: Encoding::BINARY)
|
|
149
|
+
body.each { |chunk| text << chunk.b }
|
|
150
|
+
text
|
|
151
|
+
ensure
|
|
152
|
+
body.close if body.respond_to?(:close)
|
|
153
|
+
end
|
|
154
|
+
end
|
|
37
155
|
end
|
|
38
156
|
end
|
data/lib/trellis/migration.rb
CHANGED
|
@@ -64,6 +64,16 @@ module Trellis
|
|
|
64
64
|
# ran before the failure in place, on both sides. Give a migration that
|
|
65
65
|
# defines transforms little else to do.
|
|
66
66
|
#
|
|
67
|
+
# == Environments Trellis is off in
|
|
68
|
+
#
|
|
69
|
+
# A database of an environment named in config.trellis.off_in (`%w[test]`)
|
|
70
|
+
# is built by loading the schema, which carries the targets as plain
|
|
71
|
+
# tables, not by a migration that defines one. Run in that environment, the
|
|
72
|
+
# three helpers raise ActiveRecord::MigrationError before running anything.
|
|
73
|
+
# Run from an environment Trellis is on in (`db:prepare` in development
|
|
74
|
+
# migrates the test database too), they do nothing and return nil: that
|
|
75
|
+
# database is reloaded from the new dump the next time it is prepared.
|
|
76
|
+
#
|
|
67
77
|
# == up and down, not change
|
|
68
78
|
#
|
|
69
79
|
# ActiveRecord can reverse `create_table` on its own, but not a Trellis
|
|
@@ -145,6 +155,8 @@ module Trellis
|
|
|
145
155
|
# does: Trellis.status. A read, so it runs whether or not a transaction
|
|
146
156
|
# is open.
|
|
147
157
|
def status(target_table)
|
|
158
|
+
return if off_database?("this status wasn't read: #{target_table}")
|
|
159
|
+
|
|
148
160
|
Migration.with_handle { Trellis.status(target_table) }
|
|
149
161
|
end
|
|
150
162
|
|
|
@@ -169,11 +181,33 @@ module Trellis
|
|
|
169
181
|
"cannot reverse a Trellis statement: #{statement}. Undo a define in down with " \
|
|
170
182
|
"PAUSE TRANSFORM and DROP TRANSFORM statements."
|
|
171
183
|
end
|
|
184
|
+
return if off_database?("this statement wasn't applied: #{statement}")
|
|
185
|
+
|
|
172
186
|
refuse_open_transaction!("this statement wasn't applied: #{statement}")
|
|
173
187
|
|
|
174
188
|
say_with_time("#{helper}(#{statement.inspect})") { Migration.with_handle { yield } }
|
|
175
189
|
end
|
|
176
190
|
|
|
191
|
+
# Whether the migrating database belongs to an environment Trellis is off
|
|
192
|
+
# in, so `what` is skipped: raises when that is also the environment
|
|
193
|
+
# running the migration.
|
|
194
|
+
def off_database?(what)
|
|
195
|
+
return false unless defined?(Trellis::Railtie)
|
|
196
|
+
|
|
197
|
+
environment = connection.pool.db_config.env_name
|
|
198
|
+
return false unless Trellis::Railtie.off_in?(environment)
|
|
199
|
+
|
|
200
|
+
if Trellis::Railtie.off_in?(ActiveRecord::Tasks::DatabaseTasks.env)
|
|
201
|
+
raise ActiveRecord::MigrationError,
|
|
202
|
+
Trellis::Railtie.off_message("#{what}. Build this database by loading the schema " \
|
|
203
|
+
"(`bin/rails db:schema:load`, or `db:test:prepare`) rather than " \
|
|
204
|
+
"migrating it", environment)
|
|
205
|
+
end
|
|
206
|
+
|
|
207
|
+
say Trellis::Railtie.off_message("#{what}; the next schema load of this database brings it in", environment)
|
|
208
|
+
true
|
|
209
|
+
end
|
|
210
|
+
|
|
177
211
|
def refuse_open_transaction!(what)
|
|
178
212
|
return unless connection.transaction_open?
|
|
179
213
|
|
data/lib/trellis/pg.rb
CHANGED
|
@@ -23,6 +23,7 @@ else
|
|
|
23
23
|
require_relative "trellis_ruby"
|
|
24
24
|
end
|
|
25
25
|
|
|
26
|
+
require_relative "log_bridge"
|
|
26
27
|
require_relative "instance"
|
|
27
28
|
require_relative "metrics"
|
|
28
29
|
|
|
@@ -51,6 +52,8 @@ require_relative "metrics"
|
|
|
51
52
|
# has_live_staging_worker?, watermark_token, await_converged, self_check,
|
|
52
53
|
# self_check_job.
|
|
53
54
|
# - Metrics: Trellis::Metrics.render_prometheus, which needs no handle.
|
|
55
|
+
# - Logs: Trellis.logger=, which sends the engine's log lines to a Logger
|
|
56
|
+
# (Trellis::LogBridge); needs no handle either.
|
|
54
57
|
#
|
|
55
58
|
# # A deploy's migration step: the defaults run nothing in the background.
|
|
56
59
|
# Trellis.connect(url: "host=localhost dbname=app")
|
|
@@ -97,6 +100,14 @@ module Trellis
|
|
|
97
100
|
nil
|
|
98
101
|
end
|
|
99
102
|
|
|
103
|
+
# Whether Trellis is on in this process's Rails environment: false when
|
|
104
|
+
# the app's config.trellis.off_in names it (`%w[test]`, so a test suite
|
|
105
|
+
# runs without Trellis). Always true without Rails. Code that builds on
|
|
106
|
+
# Trellis, such as a test helper that fills a target, branches on it.
|
|
107
|
+
def enabled?
|
|
108
|
+
!defined?(Trellis::Railtie) || Trellis::Railtie.enabled?
|
|
109
|
+
end
|
|
110
|
+
|
|
100
111
|
# Whether this process's default instance is connected. False before
|
|
101
112
|
# connect, after shutdown, and in a forked child that hasn't connected
|
|
102
113
|
# its own.
|
|
@@ -105,6 +116,32 @@ module Trellis
|
|
|
105
116
|
!default.nil? && default.connected?
|
|
106
117
|
end
|
|
107
118
|
|
|
119
|
+
# The Logger the engine's log lines go to, or nil (the default: they are
|
|
120
|
+
# dropped). See Trellis::LogBridge.
|
|
121
|
+
def logger
|
|
122
|
+
LogBridge.current&.logger
|
|
123
|
+
end
|
|
124
|
+
|
|
125
|
+
# Sends the engine's log lines to `logger`, from a Ruby thread
|
|
126
|
+
# (Trellis::LogBridge), or to nowhere if it is nil. The most verbose
|
|
127
|
+
# level forwarded is the logger's own level now. Set it before connecting,
|
|
128
|
+
# to catch connect's own lines. The Rails integration sets it to
|
|
129
|
+
# Rails.logger. Raises ConflictError if another tracing subscriber was
|
|
130
|
+
# installed in this extension's native library first.
|
|
131
|
+
#
|
|
132
|
+
# Trellis.logger = Logger.new($stderr)
|
|
133
|
+
def logger=(logger)
|
|
134
|
+
LogBridge.install(logger)
|
|
135
|
+
end
|
|
136
|
+
|
|
137
|
+
# Changes the most verbose level forwarded to Trellis.logger: a Logger level
|
|
138
|
+
# (:debug, :info, :warn, :error, or a Logger severity). Raises
|
|
139
|
+
# ValidationError if there is no logger.
|
|
140
|
+
def log_level=(level)
|
|
141
|
+
bridge = LogBridge.current or raise ValidationError, "Trellis.logger is not set: set it first"
|
|
142
|
+
bridge.level = level
|
|
143
|
+
end
|
|
144
|
+
|
|
108
145
|
# The default instance Trellis.connect opened, for code that takes an
|
|
109
146
|
# Instance. Raises ValidationError if there is none.
|
|
110
147
|
def default_instance
|
data/lib/trellis/railtie.rb
CHANGED
|
@@ -34,8 +34,19 @@ module Trellis
|
|
|
34
34
|
# the definitions in `structure.sql` (Trellis::SchemaDump). The database
|
|
35
35
|
# they dump into is config.trellis.dump_database, "primary" by default.
|
|
36
36
|
#
|
|
37
|
+
# `config.trellis.off_in` names the environments Trellis is off in. The
|
|
38
|
+
# default is `%w[test]`: a test suite's transactions never commit, so it
|
|
39
|
+
# can't see a target change. `off_in = []` turns Trellis on in tests. It
|
|
40
|
+
# is read from any environment, so a `db:prepare` or `db:test:prepare` run
|
|
41
|
+
# from development leaves Trellis out of the test database too. There,
|
|
42
|
+
# nothing connects at boot, Railtie.connect and `trellis:migrate` do
|
|
43
|
+
# nothing, the schema load and dump hooks leave the target tables as plain
|
|
44
|
+
# ones, and the migration helpers refuse (or skip, migrating that database
|
|
45
|
+
# from an environment Trellis is on in).
|
|
46
|
+
# Trellis.enabled? is the predicate; "Testing" in the README has the rest.
|
|
47
|
+
#
|
|
37
48
|
# When either is set, the app's handles connect in an after_initialize hook,
|
|
38
|
-
# except in these
|
|
49
|
+
# except in these cases:
|
|
39
50
|
#
|
|
40
51
|
# - An app booted by a rake task (`rails db:migrate`, `rails db:create`,
|
|
41
52
|
# ...): like Ecto, which migrates without starting the app, those get no
|
|
@@ -46,9 +57,16 @@ module Trellis
|
|
|
46
57
|
# `rails test` loads the tasks to run test:prepare, then boots the app
|
|
47
58
|
# outside any task, so it gets its handle (but `bin/rails db:test:prepare
|
|
48
59
|
# test` boots it inside the first task, so it doesn't).
|
|
60
|
+
# - Trellis is off in this environment (config.trellis.off_in).
|
|
49
61
|
# - config.trellis.connect_on_boot = false, for a server that forks with
|
|
50
62
|
# no hook to shut the handle down first (see below).
|
|
51
63
|
#
|
|
64
|
+
# The engine's log lines go to Rails.logger (Trellis::LogBridge), at
|
|
65
|
+
# Rails.logger's level or config.trellis.log_level (:debug, :info, :warn,
|
|
66
|
+
# :error), unless config.trellis.log_bridge = false or Trellis is off in
|
|
67
|
+
# this environment (nothing connects, so there are none). Trellis.logger =
|
|
68
|
+
# in a config/initializers file sends them elsewhere.
|
|
69
|
+
#
|
|
52
70
|
# A handle doesn't survive fork. A preforking server that
|
|
53
71
|
# loads the app before forking (Puma's preload_app!, on by default with
|
|
54
72
|
# more than one worker) must shut the boot handle down before it forks,
|
|
@@ -67,6 +85,9 @@ module Trellis
|
|
|
67
85
|
config.trellis.instances = {}
|
|
68
86
|
config.trellis.connect_on_boot = true
|
|
69
87
|
config.trellis.dump_database = "primary"
|
|
88
|
+
config.trellis.off_in = %w[test]
|
|
89
|
+
config.trellis.log_bridge = true
|
|
90
|
+
config.trellis.log_level = nil
|
|
70
91
|
|
|
71
92
|
rake_tasks do
|
|
72
93
|
namespace :trellis do
|
|
@@ -74,13 +95,28 @@ module Trellis
|
|
|
74
95
|
task migrate: :environment do
|
|
75
96
|
Trellis::Railtie.migrate_all
|
|
76
97
|
end
|
|
98
|
+
|
|
99
|
+
# No :environment: the check reads git and files, so it runs in a CI
|
|
100
|
+
# job with no database and none of the app's initializers.
|
|
101
|
+
desc "Fail if this release changes trellis-pg's version and adds a Trellis migration (BASE=<git ref>)"
|
|
102
|
+
task :release_check do
|
|
103
|
+
Trellis::Railtie.release_check(ENV.fetch("BASE", nil))
|
|
104
|
+
end
|
|
77
105
|
end
|
|
78
106
|
end
|
|
79
107
|
|
|
108
|
+
initializer "trellis.logger" do |app|
|
|
109
|
+
settings = app.config.trellis
|
|
110
|
+
next unless settings.log_bridge && ::Rails.logger && Trellis::Railtie.enabled?
|
|
111
|
+
|
|
112
|
+
Trellis::LogBridge.install(::Rails.logger, level: settings.log_level)
|
|
113
|
+
end
|
|
114
|
+
|
|
80
115
|
initializer "trellis.migration" do
|
|
81
116
|
ActiveSupport.on_load(:active_record) do
|
|
82
117
|
require "trellis/migration"
|
|
83
118
|
require "trellis/schema_dump"
|
|
119
|
+
require "trellis/target"
|
|
84
120
|
end
|
|
85
121
|
end
|
|
86
122
|
|
|
@@ -95,13 +131,16 @@ module Trellis
|
|
|
95
131
|
# instance from config.trellis.connect (when set), and each of
|
|
96
132
|
# config.trellis.instances. In a forked worker (Puma's
|
|
97
133
|
# before_worker_boot, Unicorn's after_fork, Passenger's
|
|
98
|
-
# starting_worker_process), or a rake task of your own.
|
|
134
|
+
# starting_worker_process), or a rake task of your own. Warns and
|
|
135
|
+
# connects nothing in an environment Trellis is off in. Raises
|
|
99
136
|
# ValidationError if neither is set, or if a named instance is already
|
|
100
137
|
# connected (as Trellis.connect does for the default one), and whatever
|
|
101
138
|
# Trellis.connect and Trellis::Instance.connect raise; the instances
|
|
102
139
|
# this call had connected are shut down first, so a failure leaves
|
|
103
140
|
# nothing half connected.
|
|
104
141
|
def connect
|
|
142
|
+
return skipped("Trellis::Railtie.connect connects nothing") unless enabled?
|
|
143
|
+
|
|
105
144
|
default = connect_options
|
|
106
145
|
named = instance_options
|
|
107
146
|
if default.nil? && named.empty?
|
|
@@ -187,6 +226,8 @@ module Trellis
|
|
|
187
226
|
# config.trellis.instances, each as with_handle does. Raises
|
|
188
227
|
# ValidationError if neither is set.
|
|
189
228
|
def migrate_all
|
|
229
|
+
return skipped("trellis:migrate migrates nothing") unless enabled?
|
|
230
|
+
|
|
190
231
|
default = connect_options
|
|
191
232
|
named = instance_options
|
|
192
233
|
if default.nil? && named.empty?
|
|
@@ -199,6 +240,40 @@ module Trellis
|
|
|
199
240
|
nil
|
|
200
241
|
end
|
|
201
242
|
|
|
243
|
+
# Runs Trellis::ReleaseCheck for this app against the git ref `base`,
|
|
244
|
+
# over every migrations path the app has (db/migrate, and each
|
|
245
|
+
# database's migrations_paths): prints its verdict, and exits 1 when
|
|
246
|
+
# the release both changes trellis-pg's version and adds a Trellis
|
|
247
|
+
# migration, or when the check can't run. What `rails
|
|
248
|
+
# trellis:release_check BASE=<ref>` runs.
|
|
249
|
+
def release_check(base)
|
|
250
|
+
require "trellis/release_check"
|
|
251
|
+
result = ReleaseCheck.call(root: ::Rails.root, base: base,
|
|
252
|
+
migrations_paths: migrations_paths, lockfile: lockfile)
|
|
253
|
+
abort result.message unless result.ok?
|
|
254
|
+
puts result.message
|
|
255
|
+
rescue ReleaseCheck::Error => e
|
|
256
|
+
abort "trellis:release_check: #{e.message}"
|
|
257
|
+
end
|
|
258
|
+
|
|
259
|
+
# Whether Trellis is off in `environment`, however it is spelled.
|
|
260
|
+
def off_in?(environment)
|
|
261
|
+
off_in.include?(environment.to_s)
|
|
262
|
+
end
|
|
263
|
+
|
|
264
|
+
# Whether Trellis is on in `environment` (this process's, by default):
|
|
265
|
+
# false when config.trellis.off_in names it. Trellis.enabled? is the
|
|
266
|
+
# shortcut for code that doesn't need the Railtie.
|
|
267
|
+
def enabled?(environment = ::Rails.env)
|
|
268
|
+
!off_in?(environment)
|
|
269
|
+
end
|
|
270
|
+
|
|
271
|
+
# A sentence saying Trellis is off in `environment`, and `what` that
|
|
272
|
+
# means was not done.
|
|
273
|
+
def off_message(what, environment = ::Rails.env)
|
|
274
|
+
"Trellis is off in the #{environment} environment (config.trellis.off_in): #{what}"
|
|
275
|
+
end
|
|
276
|
+
|
|
202
277
|
# config.trellis.connect, as Trellis.connect's keyword options, or nil
|
|
203
278
|
# when it isn't set (or there's no Rails app).
|
|
204
279
|
def connect_options
|
|
@@ -228,6 +303,42 @@ module Trellis
|
|
|
228
303
|
|
|
229
304
|
private
|
|
230
305
|
|
|
306
|
+
# The environments config.trellis.off_in names, as strings; empty when
|
|
307
|
+
# it isn't set (or there's no Rails app).
|
|
308
|
+
def off_in
|
|
309
|
+
app = ::Rails.respond_to?(:application) && ::Rails.application or return []
|
|
310
|
+
|
|
311
|
+
Array(app.config.trellis.off_in).map(&:to_s)
|
|
312
|
+
end
|
|
313
|
+
|
|
314
|
+
# Where the app keeps migrations: db/migrate, and the migrations_paths
|
|
315
|
+
# of every database in config/database.yml, read without connecting.
|
|
316
|
+
# An app whose database config can't be read here (no database.yml, a
|
|
317
|
+
# missing environment variable) is checked on db/migrate alone.
|
|
318
|
+
def migrations_paths
|
|
319
|
+
app = ::Rails.application
|
|
320
|
+
collect = lambda do |node|
|
|
321
|
+
next [] unless node.is_a?(Hash)
|
|
322
|
+
|
|
323
|
+
node.flat_map { |key, value| key.to_s == "migrations_paths" ? Array(value) : collect.call(value) }
|
|
324
|
+
end
|
|
325
|
+
configured = begin
|
|
326
|
+
collect.call(app.config.database_configuration)
|
|
327
|
+
rescue StandardError
|
|
328
|
+
[]
|
|
329
|
+
end
|
|
330
|
+
(app.paths["db/migrate"].to_a + configured).map(&:to_s).uniq
|
|
331
|
+
end
|
|
332
|
+
|
|
333
|
+
# The lockfile Bundler resolved the app with (it follows BUNDLE_GEMFILE,
|
|
334
|
+
# and a gems.rb has a gems.locked), or Gemfile.lock in an app that
|
|
335
|
+
# isn't running under Bundler.
|
|
336
|
+
def lockfile
|
|
337
|
+
defined?(::Bundler) ? ::Bundler.default_lockfile : "Gemfile.lock"
|
|
338
|
+
rescue StandardError
|
|
339
|
+
"Gemfile.lock"
|
|
340
|
+
end
|
|
341
|
+
|
|
231
342
|
def keyword_options(what, options)
|
|
232
343
|
unless options.respond_to?(:to_h)
|
|
233
344
|
raise ValidationError,
|
|
@@ -253,6 +364,11 @@ module Trellis
|
|
|
253
364
|
Trellis.default_instance
|
|
254
365
|
end
|
|
255
366
|
|
|
367
|
+
def skipped(what)
|
|
368
|
+
warn "trellis: #{off_message(what)}"
|
|
369
|
+
nil
|
|
370
|
+
end
|
|
371
|
+
|
|
256
372
|
def ignoring_errors
|
|
257
373
|
yield
|
|
258
374
|
rescue StandardError => e
|
|
@@ -274,7 +390,7 @@ module Trellis
|
|
|
274
390
|
private
|
|
275
391
|
|
|
276
392
|
def boot
|
|
277
|
-
return if rake_running?
|
|
393
|
+
return if rake_running? || !self.class.enabled?
|
|
278
394
|
|
|
279
395
|
settings = ::Rails.application.config.trellis
|
|
280
396
|
return unless settings.connect_on_boot && (settings.connect || !self.class.instance_options.empty?)
|