hamal 0.2 → 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.
Files changed (5) hide show
  1. checksums.yaml +4 -4
  2. data/README.md +113 -29
  3. data/exe/hamal +4 -1
  4. data/lib/hamal.rb +133 -223
  5. metadata +5 -4
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: f9ef115de2f093d85ef84dbc3fcc3018ced655c0a8a71311ba3cbbbabeb2195f
4
- data.tar.gz: 65a1477d5ff0827ea4c93bced1f08590b29d806e3497b71898437baa92e446a8
3
+ metadata.gz: cc1e6330868f217cb350bc8a3b9926f2dbc487209add8c7270d7980281b98e93
4
+ data.tar.gz: af43fe4e54d2d8fabc9665ae0d219adf1ed304594f5cc5bd23d8f607c0b9e7d0
5
5
  SHA512:
6
- metadata.gz: a1a7250bd24d6c87653f3ecb1e725e52a6e342fc9bd0fedf8621ef61c29d5b8b260ea5e0b687458a5f975b56a9680e6131c79cf34e7194f85829943d3effa69f
7
- data.tar.gz: 6c382bd0bf2e8e4d5817e1ba3f6b940a5fc83d8d999d389ee26e9568ddb76b35803b985dfc1cf1d6aec39e12f86882540c1e9f54f90bfa59b2d7341186514759
6
+ metadata.gz: 7aa4d7a2c6f666e5df0f1fce6d043a5f83e27b4c2758efb980b36ee71988a20f88f1b5b0e28a47f82d436477862170644b2c2a377f1a7a15b86d7c109e1e8b5c
7
+ data.tar.gz: 3b916c31ccd7e29fe333dfbb280f06e5e09ec351e5409e1c72b6dc25edf10a65dbb65fa7466a772e08f7e1aefa85dfa651d2cb6957beb490a002d2f15bb12361
data/README.md CHANGED
@@ -7,13 +7,14 @@ Not to be confused with Kamal. 😉
7
7
  configuration are app-specific, i.e. their exact contents will vary from app to
8
8
  app. In order to make this documentation generic, the `#{app_name}` and
9
9
  `#{app_domain}` placeholders are used in such places. Replace the placeholders
10
- with the respective values in `config/deploy.yml` before executing the commands
11
- / copying the configuration.
10
+ with the respective values of your app before executing the commands / copying
11
+ the configuration.
12
12
 
13
13
  # Overview
14
14
 
15
- `hamal` implements a simple deploy process for a self-hosted app on a server
16
- that you administer. It:
15
+ `hamal` gives each app a small Ruby DSL to define its own deploy commands for a
16
+ server that you administer. The app decides what a deploy is, `hamal` provides
17
+ the operations to build it from. A typical deploy:
17
18
 
18
19
  1. Connects to the server via SSH. All subsequent stages happen on the server.
19
20
  2. Fetches the code that will be deployed from GitHub.
@@ -21,6 +22,8 @@ that you administer. It:
21
22
  4. Uses that image to run the app in a container.
22
23
  5. Configures nginx to expose the app container to the Internet.
23
24
 
25
+ The rest of this document describes the server setup for that typical deploy.
26
+
24
27
  ## Prerequisites
25
28
 
26
29
  To deploy the app to a server, you will need:
@@ -233,7 +236,6 @@ nginx -s reload
233
236
  ```
234
237
  mkdir -p /var/lib/#{app_name}/db
235
238
  mkdir -p /var/lib/#{app_name}/storage
236
- mkdir -p /var/lib/#{app_name}/src
237
239
  chown rails:rails /var/lib/#{app_name}/db /var/lib/#{app_name}/storage
238
240
  ```
239
241
 
@@ -251,14 +253,15 @@ If this is an existing app, restore its database to `/var/lib/#{app_name}/db`.
251
253
  Make sure its owner user and group are `rails:rails`.
252
254
 
253
255
  If this is a new app, create its database by running `bin/rails db:create` in
254
- out of its images. You will likely have to do this at a later point, when you
255
- do have such an image. Examine `hamal` to determine what arguments to
256
- `docker run` are needed, e.g. to set ENV variables and mount host directories.
257
- The final commands you're looking for will look something like this:
256
+ one of its images. The simplest way is a temporary command in
257
+ `config/deploy.rb` (see [Configuration](#configuration)):
258
258
 
259
- ```
260
- docker run --rm <args inferred from hamal> --entrypoint '/rails/bin/rails' <app_image> -- db:create
261
- docker run --rm <args inferred from hamal> --entrypoint '/rails/bin/rails' <app_image> -- db:schema:load
259
+ ```ruby
260
+ command :setup, "Create the database" do
261
+ build
262
+ run "/rails/bin/rails db:create"
263
+ run "/rails/bin/rails db:schema:load"
264
+ end
262
265
  ```
263
266
 
264
267
  ## GitHub
@@ -293,19 +296,98 @@ In short:
293
296
 
294
297
  # Configuration
295
298
 
296
- The deploy script expects certain configuration in `config/deploy.yml`:
299
+ Define the deploy of the app in `config/deploy.rb`:
300
+
301
+ ```ruby
302
+ config = {
303
+ server: "203.0.113.7",
304
+ app: "myapp",
305
+ repo: "genadi/myapp",
306
+ env_file: "/var/lib/myapp/env_file",
307
+ volumes: { "/var/lib/myapp/db" => "/rails/db/production", "/var/lib/myapp/storage" => "/rails/storage" },
308
+ port: 3000,
309
+ host_ports: [3000, 3001],
310
+ health: "/healthz",
311
+ }
312
+
313
+ Hamal.deploy(config) do
314
+ command :deploy, "Deploy the app to the server" do
315
+ build
316
+ run "/rails/bin/rails db:migrate"
317
+
318
+ rollout do |port|
319
+ nginx.render "/etc/nginx/myapp.conf.template", ACTIVE_RAILS_PORT: port
320
+ nginx.reload
321
+ end
322
+ end
323
+
324
+ command :console, "Run Rails console in the deployed image" do
325
+ run "/rails/bin/rails console", tty: true
326
+ end
327
+
328
+ command :backup, "Download the SQLite database", aliases: [:dump] do
329
+ download "/var/lib/myapp/db/data.sqlite3", "data.sqlite3"
330
+ end
331
+ end
332
+ ```
333
+
334
+ ## Config
297
335
 
298
- - `github_repo`: The repo where the app's source is located, in the form
299
- `<username>/<repo_name>`.
300
- - `app_name`: Used as part of directory and Docker image names, so must be a
301
- valid identifier: only letters, numbers, and underscores.
302
- - `app_domain`: The hostname that this app will be accessible at.
303
336
  - `server`: The IP address of a provisioned server.
304
- - `local_ports`: An array of at least two ports that will be used by the run
305
- the app locally on the server. These ports will not be exposed to the
306
- Internet. If you're using the server to host multiple apps using this
307
- script, make sure that all apps are configured with unique ports so that
308
- they do not conflict with each other.
337
+ - `app`: Used as Docker image name and container label, so must be a valid
338
+ identifier: only letters, numbers, and underscores.
339
+ - `repo`: The GitHub repo where the app's source is located, in the form
340
+ `<username>/<repo_name>`.
341
+ - `env_file`: A file on the server with the ENV variables of the containers.
342
+ Optional.
343
+ - `volumes`: Server directories to mount in the containers, in the form
344
+ `server_dir => container_dir`. Optional.
345
+ - `port`: The port the app listens on inside the container.
346
+ - `host_ports`: An array of at least two ports that will be used to run the
347
+ app locally on the server. These ports will not be exposed to the Internet.
348
+ If you're using the server to host multiple apps, make sure that all apps
349
+ are configured with unique ports so that they do not conflict with each
350
+ other.
351
+ - `health`: A path that responds with success once the app is ready to serve
352
+ requests. Optional, without it traffic is switched right after the
353
+ container starts.
354
+
355
+ The config is a plain hash. Add your own keys and read them with `config` in
356
+ the commands.
357
+
358
+ ## Commands
359
+
360
+ `command name, description, aliases: []` defines a `hamal <name>` command. The
361
+ command line arguments are passed to the block.
362
+
363
+ The first argument of any command is the revision to work with, e.g.
364
+ `hamal deploy b04c0b567`. It defaults to the commit checked out locally and is
365
+ available as `revision`.
366
+
367
+ `hamal logs` and `hamal ssh` are built in. Define a command with the same name
368
+ to replace them.
369
+
370
+ ## Operations
371
+
372
+ - `build`: Clone the repo on the server and build the `<app>:<revision>`
373
+ image. Does nothing if the image exists.
374
+ - `run command, tty: false`: Run a one-off command in a new container. The
375
+ first word of the command replaces the image entrypoint.
376
+ - `rollout { |port| ... }`: Start a new container, wait for it to
377
+ become healthy, call the block to switch traffic to its port, stop the old
378
+ containers, and remove unused Docker objects.
379
+ - `logs`: Follow logs of the running container.
380
+ - `nginx.render template, **variables`: Write `<name>.conf` out of
381
+ `<name>.conf.template`, replacing only the given variables.
382
+ - `nginx.reload`: Reload the nginx config.
383
+ - `sh command`, `sh! command`, `sh? command`: Run a command on the server.
384
+ `sh` returns a result with `output`, `exit_code` and `success?`, `sh!`
385
+ aborts on failure, `sh?` returns whether the command succeeded.
386
+ - `download remote_path, local_path`: Copy a file from the server.
387
+ - `shell`: Open an SSH session on the server.
388
+ - `log message`: Print progress.
389
+
390
+ Containers always get the deployed revision in the `GIT_REVISION` ENV variable.
309
391
 
310
392
  # Usage
311
393
 
@@ -319,7 +401,8 @@ gem "hamal"
319
401
 
320
402
  ## Deploy
321
403
 
322
- Pass the commit you want deployed to `hamal deploy`:
404
+ With the configuration above, pass the commit you want deployed to
405
+ `hamal deploy`:
323
406
 
324
407
  ```
325
408
  hamal deploy b04c0b567
@@ -331,14 +414,15 @@ local commits.
331
414
 
332
415
  ## --help
333
416
 
334
- For more commands, run `hamal --help`:
417
+ For the list of commands, run `hamal --help`:
335
418
 
336
419
  ```
337
420
  Usage: hamal [command]
338
421
 
339
422
  Commands:
340
- deploy - Deploy the app to the server
341
- console - Run Rails console in the deployed container
342
- logs - Follow logs of the deployed container
343
- sudo - SSH into the server as administrator
423
+ logs - Follow logs of the deployed container
424
+ ssh - SSH into the server as administrator
425
+ deploy - Deploy the app to the server
426
+ console - Run Rails console in the deployed image
427
+ backup - Download the SQLite database, alias: dump
344
428
  ```
data/exe/hamal CHANGED
@@ -2,4 +2,7 @@
2
2
 
3
3
  require "hamal"
4
4
 
5
- Hamal::Commands.execute
5
+ deploy_file = "config/deploy.rb"
6
+ abort "Cannot find #{deploy_file}, define the deploy of this app in it" unless File.exist? deploy_file
7
+
8
+ load deploy_file
data/lib/hamal.rb CHANGED
@@ -1,291 +1,201 @@
1
- require "English"
2
1
  require "json"
3
- require "yaml"
4
2
 
5
3
  module Hamal
6
- VERSION = "0.2"
7
-
8
- module Config
9
- def config_file = "config/deploy.yml"
10
- def deployed_revision = ARGV.first.then { _1 unless _1.to_s.start_with? "-" } || `git rev-parse HEAD`.strip
11
- def deployed_image = "#{app_name}:#{deployed_revision}"
12
- def deploy_config = @deploy_config ||= YAML.safe_load_file(config_file)
13
- def deploy_env = "production"
14
- def app_name = deploy_config.fetch "app_name"
15
- def app_repo = deploy_config.fetch "github_repo"
16
- def app_local_ports = deploy_config.fetch("local_ports").map(&:to_s)
17
- def server = deploy_config.fetch "server"
18
- def project_root = "/var/lib/#{app_name}"
19
- end
4
+ VERSION = "1.0"
20
5
 
21
- module Helpers
22
- include Config
6
+ def self.deploy(config, &)
7
+ deploy = Deploy.new config
8
+ deploy.instance_exec(&)
9
+ deploy.execute ARGV.dup
10
+ end
23
11
 
24
- def on_server(user: :root, dir: nil, &) = RemoteExecutor.new(user, dir).instance_exec(&)
12
+ Command = Struct.new :name, :description, :aliases, :block
25
13
 
26
- def log(message)
27
- bold = "\e[1m"
28
- green = "\e[32m"
29
- clear = "\e[0m"
14
+ Result = Struct.new :output, :exit_code do
15
+ def success? = exit_code.zero?
16
+ end
30
17
 
31
- message = "#{bold}#{green}#{message}#{clear}" if $stdout.tty?
32
- puts message
18
+ class Nginx
19
+ def initialize(deploy)
20
+ @deploy = deploy
33
21
  end
34
- end
35
22
 
36
- class RemoteExecutor
37
- include Helpers
23
+ def render(template, **variables)
24
+ assignments = variables.map { |name, value| "#{name}=#{value}" }.join " "
25
+ names = variables.keys.map { "$#{it}" }.join " "
38
26
 
39
- ExecResult = Struct.new :output, :exit_code do
40
- def success? = exit_code.zero?
27
+ @deploy.sh! "#{assignments} envsubst '#{names}' < #{template} > #{template.delete_suffix '.template'}"
41
28
  end
42
29
 
43
- def initialize(remote_user, remote_dir)
44
- @remote_user = remote_user
45
- @remote_dir = remote_dir
30
+ def reload = @deploy.sh! "nginx -s reload"
31
+ end
32
+
33
+ class Deploy
34
+ attr_reader :config
35
+
36
+ def initialize(config)
37
+ @config = config
38
+ @commands = {}
46
39
 
47
- raise "Invalid remote user #{@remote_user}" unless [:root, :rails].include? @remote_user
40
+ command(:logs, "Follow logs of the deployed container") { logs }
41
+ command(:ssh, "SSH into the server as administrator") { shell }
48
42
  end
49
43
 
50
- def sh(command, interactive: false, abort_on_error: false)
51
- dir_override = "cd #{@remote_dir};" if @remote_dir
52
- user_override = "runuser -u rails" if @remote_user == :rails
53
- ssh "#{dir_override} #{user_override} #{command}", interactive:, abort_on_error:
44
+ def command(name, description = nil, aliases: [], &block)
45
+ @commands[name.to_s] = Command.new name.to_s, description, aliases.map(&:to_s), block
54
46
  end
55
47
 
56
- def sh!(command, interactive: false) = sh command, interactive:, abort_on_error: true
48
+ def execute(argv)
49
+ name = argv.shift
50
+ @revision = argv.first
51
+ command = @commands.values.find { it.name == name || it.aliases.include?(name) }
57
52
 
58
- def ssh(remote_command, abort_on_error:, interactive: false)
59
- remote_command = remote_command.gsub "'", %q('"'"')
53
+ if command
54
+ instance_exec(*argv, &command.block)
55
+ else
56
+ help
57
+ end
58
+ end
59
+
60
+ def nginx = Nginx.new self
61
+ def revision = @revision ||= `git rev-parse HEAD`.strip
60
62
 
63
+ def sh(command, tty: false, abort_on_error: false)
61
64
  output =
62
- if interactive
63
- spawn "ssh -tt root@#{server} '#{remote_command}'", out: $stdout, err: $stderr, in: $stdin
64
- Process.wait
65
+ if tty
66
+ system "ssh", "-tt", "root@#{server}", command
65
67
  nil
66
68
  else
67
- `ssh root@#{server} '#{remote_command}'`.strip
69
+ IO.popen(["ssh", "root@#{server}", command], &:read).strip
68
70
  end
69
71
 
70
- abort "Failed to execute `#{remote_command}` on `#{server}`" if abort_on_error && !$CHILD_STATUS.success?
72
+ abort "Failed to execute `#{command}` on `#{server}`" if abort_on_error && !Process.last_status.success?
71
73
 
72
- ExecResult.new output:, exit_code: $CHILD_STATUS.exitstatus
74
+ Result.new output, Process.last_status.exitstatus
73
75
  end
74
- end
75
76
 
76
- module Stages
77
- include Helpers
77
+ def sh!(command, tty: false) = sh command, tty:, abort_on_error: true
78
+ def sh?(command) = sh(command).success?
78
79
 
79
- def build_new_image
80
- image_exists = on_server { sh "docker image inspect #{deployed_image}" }.success?
81
- if image_exists
82
- log "Using existing image #{deployed_image} for deploy"
83
- return
84
- end
85
-
86
- log "Building new image #{deployed_image} for deploy"
87
-
88
- source_dir = "#{project_root}/src/#{deployed_revision}"
80
+ def download(remote_path, local_path)
81
+ system "scp", "-O", "root@#{server}:#{remote_path}", local_path, exception: true
82
+ end
89
83
 
90
- on_server do
91
- log " Checking out source at revision #{deployed_revision}..."
92
- sh! "rm -rf #{source_dir}"
93
- sh! "git clone git@github.com:#{app_repo}.git #{source_dir}"
94
- end
95
- on_server dir: source_dir do
96
- sh! "git checkout #{deployed_revision}"
84
+ def shell
85
+ system "ssh", "root@#{server}", exception: true
86
+ end
97
87
 
98
- log " Building image..."
99
- sh! "docker build -t #{deployed_image} ."
88
+ def log(message)
89
+ bold = "\e[1m"
90
+ green = "\e[32m"
91
+ clear = "\e[0m"
100
92
 
101
- log " Cleaning up source dir..."
102
- sh! "rm -rf #{source_dir}"
103
- end
93
+ message = "#{bold}#{green}#{message}#{clear}" if $stdout.tty?
94
+ puts message
104
95
  end
105
96
 
106
- def run_deploy_tasks
107
- log "Running migrations"
108
-
109
- on_server do
110
- sh! "docker run --rm " \
111
- "--label app=#{app_name} " \
112
- "--env-file #{project_root}/env_file " \
113
- "-e GIT_REVISION=#{deployed_revision} " \
114
- "-v #{project_root}/db:/rails/db/#{deploy_env} " \
115
- "-v #{project_root}/storage:/rails/storage " \
116
- "--entrypoint '/rails/bin/rails' " \
117
- "#{deployed_image} " \
118
- "-- db:migrate"
97
+ def build
98
+ if sh? "docker image inspect #{image}"
99
+ log "Using existing image #{image}"
100
+ return
119
101
  end
120
- end
121
102
 
122
- def start_new_container
123
- log "Starting container for new version"
103
+ log "Building image #{image}"
104
+ source_dir = sh!("mktemp -d").output
124
105
 
125
- # Determine which ports are currently bound and which are free for the new container
126
- running_containers = on_server { sh! "docker ps -q --filter label=app=#{app_name}" }.output.split
127
- bound_ports =
128
- running_containers.map do |container|
129
- port_settings = on_server { sh! "docker inspect --format '{{json .NetworkSettings.Ports}}' #{container}" }.output
130
- port_settings = JSON.parse port_settings
131
- (port_settings["3000/tcp"] || []).map { _1["HostPort"] }.compact
132
- end.flatten
133
-
134
- available_port = (app_local_ports - bound_ports).first
135
- abort "No TCP port available" unless available_port
136
-
137
- log " Using port #{available_port} for new container"
138
- on_server do
139
- sh! "docker run -d --rm " \
140
- "--label app=#{app_name} " \
141
- "--env-file #{project_root}/env_file " \
142
- "-e GIT_REVISION=#{deployed_revision} " \
143
- "-v #{project_root}/db:/rails/db/#{deploy_env} " \
144
- "-v #{project_root}/storage:/rails/storage " \
145
- "-p 127.0.0.1:#{available_port}:3000 " \
146
- "#{deployed_image}"
147
- end
106
+ log " Checking out source at revision #{revision}..."
107
+ sh! "git clone git@github.com:#{config.fetch :repo}.git #{source_dir}"
108
+ sh! "cd #{source_dir} && git checkout #{revision}"
148
109
 
149
- [available_port, running_containers]
110
+ log " Building image..."
111
+ sh! "cd #{source_dir} && docker build -t #{image} ."
112
+ ensure
113
+ sh "rm -rf #{source_dir}" if source_dir
150
114
  end
151
115
 
152
- def switch_traffic(new_container_port)
153
- log "Switching traffic to new version"
116
+ def run(command, tty: false)
117
+ executable, arguments = command.split " ", 2
154
118
 
155
- log " Waiting for new version to become ready"
156
- health_checks = 1
157
- loop do
158
- new_container_ready = on_server { sh "curl -fs http://localhost:#{new_container_port}/healthz" }.success?
159
- break if new_container_ready
119
+ log "Running `#{command}`"
120
+ sh! "docker run --rm #{'-it ' if tty}#{docker_flags} " \
121
+ "--entrypoint #{executable} #{image} #{arguments}", tty:
122
+ end
160
123
 
161
- abort "New container failed to start within 30 seconds, investigate!" if health_checks > 30
124
+ def rollout
125
+ log "Starting container for new version"
126
+ old_containers = running_containers
127
+ port = (config.fetch(:host_ports).map(&:to_s) - old_containers.flat_map { bound_ports it }).first
128
+ abort "No TCP port available" unless port
162
129
 
163
- health_checks += 1
164
- sleep 1
165
- end
130
+ log " Using port #{port} for new container"
131
+ sh! "docker run -d --rm --label app=#{app} #{docker_flags} " \
132
+ "-p 127.0.0.1:#{port}:#{config.fetch :port} #{image}"
166
133
 
167
- log " Redirecting nginx to new version"
168
- on_server do
169
- sh! "ACTIVE_RAILS_PORT=#{new_container_port} envsubst < /etc/nginx/#{app_name}.conf.template > /etc/nginx/#{app_name}.conf"
170
- sh! "nginx -s reload"
171
- end
172
- end
134
+ log " Waiting for new version to become ready"
135
+ wait_until_healthy port
173
136
 
174
- def stop_old_container(old_containers)
175
- log "Stopping old container"
137
+ log "Switching traffic to new version"
138
+ yield port if block_given?
176
139
 
177
- if old_containers.empty?
178
- log " (none found)"
179
- return
180
- end
140
+ log "Stopping old container"
141
+ sh! "docker kill -s SIGTERM #{old_containers.join ' '}" if old_containers.any?
181
142
 
182
- on_server do
183
- sh! "docker kill -s SIGTERM #{old_containers.join ' '}"
184
- end
143
+ log "Removing unused docker objects"
144
+ sh! 'docker system prune --all --force --filter "until=24h"'
185
145
  end
186
146
 
187
- def clean_up
188
- log "Cleaning up"
189
-
190
- log " Removing unused docker objects"
191
- on_server do
192
- sh! 'docker system prune --all --force --filter "until=24h"'
193
- end
194
- end
195
- end
147
+ def logs
148
+ container, *other_containers = running_containers
149
+ abort "No running container found, cannot follow logs" unless container
150
+ abort "Multiple containers found, cannot follow logs: #{other_containers.inspect}" unless other_containers.empty?
196
151
 
197
- module Commands
198
- extend self
199
-
200
- include Stages
201
-
202
- def execute
203
- abort "Configure server in deploy config file" unless server
204
-
205
- case ARGV.shift
206
- when "deploy"
207
- deploy_command
208
- when "console"
209
- console_command
210
- when "logs"
211
- logs_command
212
- when "dump"
213
- dump_command
214
- when "ssh", "sudo"
215
- sudo_command
216
- else
217
- help_command
218
- end
152
+ log "Following container #{container} logs"
153
+ sh "docker logs -f #{container}", tty: true
219
154
  end
220
155
 
221
156
  private
222
157
 
223
- def deploy_command
224
- build_new_image
225
- run_deploy_tasks
226
- new_container_port, old_containers = start_new_container
227
- switch_traffic new_container_port
228
- stop_old_container old_containers
229
- clean_up
158
+ def server = config.fetch :server
159
+ def app = config.fetch :app
160
+ def image = "#{app}:#{revision}"
161
+
162
+ def docker_flags
163
+ flags = []
164
+ flags << "--env-file #{config[:env_file]}" if config[:env_file]
165
+ flags << "-e GIT_REVISION=#{revision}"
166
+ flags += config.fetch(:volumes, {}).map { |host_dir, container_dir| "-v #{host_dir}:#{container_dir}" }
167
+ flags.join " "
230
168
  end
231
169
 
232
- def console_command
233
- image_exists = on_server { sh "docker image inspect #{deployed_image}" }.success?
234
- unless image_exists
235
- log "Cannot find #{deployed_image} for inspecting"
236
- return
237
- end
170
+ def running_containers = sh!("docker ps -q --filter label=app=#{app}").output.split
238
171
 
239
- log "Running Rails console"
240
-
241
- on_server do
242
- sh! "docker run --rm -it " \
243
- "--label app=#{app_name} " \
244
- "--env-file #{project_root}/env_file " \
245
- "-e GIT_REVISION=#{deployed_revision} " \
246
- "-v #{project_root}/db:/rails/db/#{deploy_env} " \
247
- "-v #{project_root}/storage:/rails/storage " \
248
- "--entrypoint '/rails/bin/rails' " \
249
- "#{deployed_image} " \
250
- "console", interactive: true
251
- end
172
+ def bound_ports(container)
173
+ ports = JSON.parse sh!("docker inspect --format '{{json .NetworkSettings.Ports}}' #{container}").output
174
+ (ports["#{config.fetch :port}/tcp"] || []).filter_map { it["HostPort"] }
252
175
  end
253
176
 
254
- def logs_command
255
- # Determine which ports are currently bound and which are free for the new container
256
- running_container, *other_containers = on_server { sh! "docker ps -q --filter label=app=#{app_name}" }.output.split
257
- abort "Multiple containers found, cannot follow logs: #{other_containers.inspect}" unless other_containers.empty?
177
+ def wait_until_healthy(port)
178
+ return unless config[:health]
258
179
 
259
- log "Following container #{running_container} logs"
180
+ health_checks = 1
181
+ until sh? "curl -fs http://localhost:#{port}#{config[:health]}"
182
+ abort "New container failed to start within 30 seconds, investigate!" if health_checks > 30
260
183
 
261
- on_server do
262
- sh "docker logs -f #{running_container}", interactive: true
184
+ health_checks += 1
185
+ sleep 1
263
186
  end
264
187
  end
265
188
 
266
- def dump_command
267
- log "Dumping database"
189
+ def help
190
+ width = @commands.keys.map(&:size).max
268
191
 
269
- on_server do
270
- system "scp -O root@#{server}:/var/lib/#{app_name}/db/data.sqlite3 data.sqlite3", exception: true
192
+ puts "Usage: hamal [command]"
193
+ puts
194
+ puts "Commands:"
195
+ @commands.each_value do |command|
196
+ aliases = ", alias: #{command.aliases.join ', '}" if command.aliases.any?
197
+ puts " #{command.name.ljust width} - #{command.description}#{aliases}"
271
198
  end
272
199
  end
273
-
274
- def sudo_command
275
- system "ssh root@#{server}", exception: true
276
- end
277
-
278
- def help_command
279
- puts <<~HELP
280
- Usage: hamal [command]
281
-
282
- Commands:
283
- deploy - Deploy the app to the server
284
- console - Run rails console in the deployed container
285
- backup - Backup the SQLite database from the server
286
- logs - Follow logs of the deployed container
287
- ssh - SSH into the server as administrator, alias: sudo
288
- HELP
289
- end
290
200
  end
291
201
  end
metadata CHANGED
@@ -1,7 +1,7 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: hamal
3
3
  version: !ruby/object:Gem::Version
4
- version: '0.2'
4
+ version: '1.0'
5
5
  platform: ruby
6
6
  authors:
7
7
  - Genadi Samokovarov
@@ -49,14 +49,15 @@ required_ruby_version: !ruby/object:Gem::Requirement
49
49
  requirements:
50
50
  - - ">="
51
51
  - !ruby/object:Gem::Version
52
- version: 3.1.0
52
+ version: 3.4.0
53
53
  required_rubygems_version: !ruby/object:Gem::Requirement
54
54
  requirements:
55
55
  - - ">="
56
56
  - !ruby/object:Gem::Version
57
57
  version: '0'
58
58
  requirements: []
59
- rubygems_version: 3.6.9
59
+ rubygems_version: 4.0.20
60
60
  specification_version: 4
61
- summary: Hamal is a simple deploy tool for self-hosted Rails applications
61
+ summary: Hamal is a simple deploy tool for self-hosted Rails applications, defined
62
+ by a DSL in each app
62
63
  test_files: []