dalben-cli 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.
@@ -0,0 +1,1075 @@
1
+ module DalbenCli
2
+ class Main
3
+ DEFAULT_URL = "https://dalben.cloud"
4
+
5
+ HELP = <<~TXT
6
+ Usage: dalben COMMAND [options]
7
+
8
+ Session
9
+ login [--url URL] [--email EMAIL] log in and store a token
10
+ logout revoke the stored token and forget it
11
+ tokens list API tokens
12
+ keys list your SSH keys for git push
13
+ keys:add [PATH] [--name N] add a public key (default ~/.ssh/id_ed25519.pub, then id_rsa.pub)
14
+ keys:remove NAME|FINGERPRINT|ID remove a key
15
+
16
+ Environments (production, staging, dev)
17
+ env show the default environment
18
+ env:use ENV set the default environment
19
+ env:clear forget the default environment
20
+
21
+ Servers
22
+ servers list servers
23
+ servers:add NAME HOST --env ENV [--port 22] [--fingerprint SHA256:...]
24
+ servers:check NAME test the SSH connection
25
+ servers:import NAME [--apply] adopt existing apps and services (dry run without --apply)
26
+ servers:remove NAME --confirm NAME
27
+
28
+ Projects (group the apps of one product, across environments)
29
+ projects list projects
30
+ projects:info PROJECT show a project and its apps
31
+ projects:create PROJECT
32
+ projects:rename PROJECT NEW_NAME
33
+ projects:destroy PROJECT --confirm PROJECT only an empty project
34
+ projects:members PROJECT list who can reach a project, with their roles
35
+ projects:members:add PROJECT EMAIL [--role ROLE] the person needs an account; developer by default
36
+ projects:members:role PROJECT EMAIL ROLE viewer (read only), developer or owner (members, billing, tiers)
37
+ projects:members:remove PROJECT EMAIL
38
+
39
+ Apps
40
+ apps list apps
41
+ apps:create NAME --server SERVER --project PROJECT [--tier TIER]
42
+ apps:tier TIER -a APP move an app to another tier (see `tiers`); says what it adds a month
43
+ apps:info -a APP
44
+ apps:rename NEW_NAME -a APP rename an app; its git remote changes
45
+ apps:move -a APP --project PROJECT move an app to another project
46
+ apps:destroy -a APP --confirm APP destroy the app with its add-ons and their data
47
+ deploy IMAGE -a APP deploy a Docker image (private registries: see registry:login)
48
+ deploy:source [PATH] -a APP upload a folder (default .) without .git and .gitignore'd files, build it
49
+ git:remote -a APP print the `git push` remote
50
+ github:connect OWNER/REPO -a APP [--branch B] [--auto] deploy from a GitHub branch
51
+ github:disconnect -a APP
52
+ github:deploy -a APP [--commit SHA] deploy the connected branch head (or a commit)
53
+ github:deploy OWNER/REPO (--server S --project P [--name N] | -a APP) [--branch B] [--auto]
54
+ deploy a repository to a new or existing app
55
+ releases -a APP list releases, newest first
56
+ releases:info RELEASE -a APP show one release, such as v12
57
+ rollback RELEASE -a APP deploy an earlier release's image again as a new release
58
+ ps -a APP show the process formation
59
+ ps:scale web=2 worker=1 -a APP
60
+ ps:restart -a APP
61
+ logs -a APP [-n 200]
62
+ maintenance -a APP show whether the app serves the maintenance page
63
+ maintenance:on -a APP serve a 503 maintenance page instead of the app
64
+ maintenance:off -a APP serve the app again
65
+
66
+ Review apps (one app per GitHub pull request, removed when it closes or after 5 days without a push)
67
+ reviewapps -a APP whether they are on, and the open review apps
68
+ reviewapps:enable -a APP the app must deploy from GitHub; pull requests from forks get none
69
+ reviewapps:disable -a APP open review apps stay until their pull requests close
70
+ reviewapps:limit N --project P how many may be open at once (owners; 3 by default)
71
+
72
+ One-off runs (a one-off container of the app, stopped after the tier's scheduler runtime)
73
+ run -a APP -- COMMAND open a console over SSH with your key, such as bin/rails console
74
+ run --detach -a APP -- COMMAND run it as an operation and follow its output, such as bin/rails db:migrate
75
+ runs -a APP recent runs: command, who, start, duration and exit status
76
+
77
+ Private registries (logins per project, used when deploying an image from that host)
78
+ registry --project P list registry logins (host and user, never the token)
79
+ registry:login HOST -u USER --project P [--password-stdin] save a login, such as ghcr.io or docker.io
80
+ registry:logout HOST --project P forget a login
81
+
82
+ Alerts (failed backups and deploys, apps that keep restarting; mailed to developers and owners, who can mute a project in account settings)
83
+ webhooks --project P the project's webhook, its signing secret and last deliveries (owners)
84
+ webhooks:set URL --project P post the project's alerts to a public https:// URL, signed per standardwebhooks.com
85
+ webhooks:remove --project P stop posting them; a new webhook gets a new secret
86
+ webhooks:test --project P post a webhook.test event and show how it went with `dalben webhooks`
87
+
88
+ Billing (per minute, capped at each tier's monthly price)
89
+ tiers list tiers with memory, CPU and monthly price
90
+ billing PROJECT the project's customer: payment status, trial, cap, this month, past charges
91
+ billing:checkout PROJECT print the Paddle link to add the customer's payment method
92
+ billing:cap PROJECT EUROS|--off the most the customer may spend a month; paid apps stop at it
93
+ billing:cancel PROJECT --confirm PROJECT stop paid apps, charge usage so far, cancel
94
+
95
+ Config (values are encrypted at rest)
96
+ config -a APP [--reveal] values masked unless --reveal, also with --json
97
+ config:set KEY=VALUE ... -a APP [--no-restart]
98
+ config:unset KEY ... -a APP [--no-restart]
99
+
100
+ Dokku settings
101
+ settings -a APP
102
+ settings:set KEY=VALUE ... -a APP keys: ports, tls, checks, builder, buildpacks, deploy_branch,
103
+ nginx.client-max-body-size, nginx.proxy-read-timeout,
104
+ limits.TYPE.memory, limits.TYPE.cpu (lists comma-separated)
105
+
106
+ Domains
107
+ domains -a APP
108
+ domains:add HOST -a APP [--no-tls]
109
+ domains:remove HOST -a APP
110
+ certs:retry -a APP ask Let's Encrypt again for domains still waiting
111
+
112
+ Log drains (one per app; logs also stay on the server for 14 days)
113
+ drains -a APP the app's drain, shown without its token
114
+ drains:add URL -a APP syslog+tls://HOST:PORT, syslog://HOST:PORT (TCP), syslog+udp://HOST:PORT
115
+ or an https:// URL with its token, such as Datadog's intake URL
116
+ drains:remove ID -a APP
117
+
118
+ Volumes (directories on the server, kept when unmounted)
119
+ volumes -a APP
120
+ volumes:add NAME PATH -a APP [--limit GB] mount at PATH in the app, restarts it
121
+ volumes:limit NAME GB -a APP own disk of GB; the first limit stops the app, later ones only grow
122
+ volumes:remove NAME -a APP --confirm NAME
123
+ volumes:push NAME DIR -a APP copy DIR into the volume with rsync over your SSH key; sends what changed
124
+ volumes:pull NAME DIR -a APP copy the volume into DIR
125
+ volumes:sync NAME DIR -a APP --confirm NAME make the volume match DIR, deleting files DIR does not have
126
+
127
+ Scheduler (commands on a schedule in a one-off container, times in UTC)
128
+ scheduler -a APP
129
+ scheduler:add "COMMAND" -a APP --every 10m|1h|1d [--at :MM|HH:MM] or --schedule CRON; --at defaults to :00 or 00:00
130
+ scheduler:update ID -a APP ["COMMAND"] [--every F] [--at T] [--schedule CRON] [--enable|--disable]
131
+ scheduler:run ID -a APP run it now and follow its output
132
+ scheduler:remove ID -a APP --confirm ID
133
+
134
+ Add-ons (postgres, redis, mysql, objectstorage: an S3 bucket that sets S3_*)
135
+ addons [--all] list add-ons; --all adds deleted ones, whose backups stay
136
+ addons:create KIND -a APP [--name N] [--backups DEST] [--schedule "15 3 * * *"] [--retention 14] [--limit GB] [--version 17]
137
+ addons:limit NAME GB own disk of GB; the first limit stops the service, later ones only grow
138
+ addons:destroy NAME --confirm NAME
139
+
140
+ Backups
141
+ backups:destinations list backup destinations
142
+ backups:destinations:add NAME --bucket B [--endpoint URL] [--region R] [--prefix P]
143
+ backups ADDON list backups; a deleted add-on by its ID from `addons --all`
144
+ backups:capture ADDON
145
+ backups:restore BACKUP_ID --confirm ADDON
146
+ backups:verify BACKUP_ID
147
+ backups:schedule ADDON --destination DEST --schedule CRON [--retention N]
148
+
149
+ Point-in-time recovery (Postgres; 7 days on Standard, 14 on Pro; needs a backup destination)
150
+ pg:pitr ADDON whether it is on, and the window a restore may name
151
+ pg:pitr:enable ADDON archive every change with WAL-G; restarts the database once
152
+ pg:pitr:disable ADDON stop archiving; the archive stays in the bucket
153
+ pg:restore ADDON --to "2026-12-01 14:30" [--as NAME] restore that minute (UTC unless an offset is given)
154
+ into a new add-on; the app gets NAME_URL, DATABASE_URL stays
155
+
156
+ Postgres access and versions (developers; over SSH with your key, no public database port)
157
+ pg:psql ADDON open psql on the add-on, for at most four hours
158
+ pg:tunnel ADDON [--port 5432] a local port for GUI tools for eight hours; prints the URL to connect to
159
+ pg:credentials:rotate ADDON --confirm ADDON new passwords; apps using them restart once
160
+ pg:fork BACKUP_ID [--as NAME] [-a APP] restore a backup into a new add-on; the app gets NAME_URL
161
+ pg:upgrade ADDON --version 17 [--as NAME] copy into a new add-on on that version, while the apps using it stop writing
162
+ pg:upgrade:switch ADDON --confirm ADDON make a copy (upgrade, fork, restore) the app's DATABASE_URL;
163
+ the old add-on stays as NAME_OLD_URL until you destroy it
164
+
165
+ Imports (copy an app from Heroku; nothing changes on Heroku)
166
+ import heroku HEROKU_APP --server SERVER --project PROJECT [-a NAME] [--token-stdin]
167
+ create the app with its tier, add-ons, config vars, domains and
168
+ database; asks for a Heroku API token (or reads HEROKU_API_KEY),
169
+ which Dalben uses for this import only and never stores
170
+ imports list imports
171
+ import:db IMPORT_ID [--token-stdin] copy the Heroku database again, for the final cut-over
172
+
173
+ Other
174
+ operations [ID] list operations, or show one
175
+ audit recent audit events
176
+
177
+ An app or add-on name that exists in more than one environment needs
178
+ -e ENV, a default from `env:use`, or the NAME@ENV form.
179
+ Long-running commands wait for their operation; pass --no-wait to return at once.
180
+ TXT
181
+
182
+ def initialize(argv)
183
+ @argv = argv.dup
184
+ @opts = { wait: true, restart: true, tls: true }
185
+ @config = Config.new
186
+ end
187
+
188
+ def run
189
+ command = @argv.shift
190
+ parser.parse!(@argv)
191
+ return (puts HELP; 0) if command.nil? || %w[help -h --help].include?(command)
192
+ method = "cmd_#{command.tr(':', '_')}"
193
+ raise Error, "unknown command `#{command}`, see `dalben help`" unless respond_to?(method, true)
194
+ send(method)
195
+ 0
196
+ rescue Error, OptionParser::ParseError => e
197
+ warn "error: #{e.message}"
198
+ 1
199
+ rescue Interrupt
200
+ warn "\ninterrupted"
201
+ 130
202
+ end
203
+
204
+ private
205
+
206
+ def parser
207
+ OptionParser.new do |o|
208
+ o.on("-a", "--app APP") { @opts[:app] = _1 }
209
+ o.on("--server SERVER") { @opts[:server] = _1 }
210
+ o.on("-p", "--project PROJECT") { @opts[:project] = _1 }
211
+ o.on("-e", "--env ENV") { @opts[:env] = _1 }
212
+ o.on("--confirm NAME") { @opts[:confirm] = _1 }
213
+ o.on("--url URL") { @opts[:url] = _1 }
214
+ o.on("--email EMAIL") { @opts[:email] = _1 }
215
+ o.on("--port PORT", Integer) { @opts[:port] = _1 }
216
+ o.on("--fingerprint FP") { @opts[:fingerprint] = _1 }
217
+ o.on("-n", "--num N", Integer) { @opts[:num] = _1 }
218
+ o.on("--name NAME") { @opts[:name] = _1 }
219
+ o.on("--backups DEST") { @opts[:destination] = _1 }
220
+ o.on("--destination DEST") { @opts[:destination] = _1 }
221
+ o.on("--schedule CRON") { @opts[:schedule] = _1 }
222
+ o.on("--retention N", Integer) { @opts[:retention] = _1 }
223
+ o.on("--limit GB", Integer) { @opts[:limit] = _1 }
224
+ o.on("--bucket B") { @opts[:bucket] = _1 }
225
+ o.on("--endpoint URL") { @opts[:endpoint] = _1 }
226
+ o.on("--region R") { @opts[:region] = _1 }
227
+ o.on("--prefix P") { @opts[:prefix] = _1 }
228
+ o.on("--[no-]wait") { @opts[:wait] = _1 }
229
+ o.on("--[no-]restart") { @opts[:restart] = _1 }
230
+ o.on("--[no-]tls") { @opts[:tls] = _1 }
231
+ o.on("--reveal") { @opts[:reveal] = true }
232
+ o.on("--json") { @opts[:json] = true }
233
+ o.on("--all") { @opts[:all] = true }
234
+ o.on("--apply") { @opts[:apply] = true }
235
+ o.on("--branch B") { @opts[:branch] = _1 }
236
+ o.on("--commit SHA") { @opts[:commit] = _1 }
237
+ o.on("--auto") { @opts[:auto] = true }
238
+ o.on("--tier TIER") { @opts[:tier] = _1 }
239
+ o.on("--role ROLE") { @opts[:role] = _1 }
240
+ o.on("--every FREQ") { @opts[:every] = _1 }
241
+ o.on("--at TIME") { @opts[:at] = _1 }
242
+ o.on("-u", "--username USER") { @opts[:username] = _1 }
243
+ o.on("--password-stdin") { @opts[:password_stdin] = true }
244
+ o.on("--token-stdin") { @opts[:token_stdin] = true }
245
+ o.on("--enable") { @opts[:enabled] = true }
246
+ o.on("--disable") { @opts[:enabled] = false }
247
+ o.on("--detach") { @opts[:detach] = true }
248
+ o.on("--to TIME") { @opts[:to] = _1 }
249
+ o.on("--as NAME") { @opts[:as] = _1 }
250
+ o.on("--off") { @opts[:off] = true }
251
+ o.on("--version V") { @opts[:version] = _1 }
252
+ end
253
+ end
254
+
255
+ def api = @api ||= Api.new(@config.url, @config.token)
256
+ def app! = scoped(@opts[:app] || raise(Error, "missing -a APP"))
257
+ def environment = @opts[:env] || @config.environment
258
+
259
+ # "shop" becomes "shop@staging" when an environment is chosen; ids and
260
+ # names that already carry one are left alone.
261
+ def scoped(name)
262
+ return name if environment.nil? || name.include?("@") || name.match?(/\A\d+\z/)
263
+ "#{name}@#{environment}"
264
+ end
265
+ def arg!(what) = @argv.shift || raise(Error, "missing #{what}")
266
+
267
+ def ask(prompt, secret: false)
268
+ $stderr.print prompt
269
+ value = if secret && $stdin.tty?
270
+ require "io/console"
271
+ $stdin.noecho(&:gets).tap { $stderr.puts }
272
+ else
273
+ $stdin.gets
274
+ end
275
+ value.to_s.chomp
276
+ end
277
+
278
+ def output(data, &table)
279
+ return puts(JSON.pretty_generate(data)) if @opts[:json] || table.nil?
280
+ table.call(data)
281
+ end
282
+
283
+ def rows(list, *cols)
284
+ return puts("(none)") if list.empty?
285
+ widths = cols.map { |c| [ c.to_s.size, *list.map { _1[c.to_s].to_s.size } ].max }
286
+ puts cols.each_with_index.map { |c, i| c.to_s.upcase.ljust(widths[i]) }.join(" ")
287
+ list.each { |r| puts cols.each_with_index.map { |c, i| r[c.to_s].to_s.ljust(widths[i]) }.join(" ") }
288
+ end
289
+
290
+ # Follows an operation's log until it finishes.
291
+ def follow(result)
292
+ op = result["operation"] or return
293
+ return puts("queued operation #{op['id']} (#{op['kind']})") unless @opts[:wait]
294
+ printed = 0
295
+ loop do
296
+ log = op["log"].to_s
297
+ print log[printed..] if log.size > printed
298
+ printed = log.size
299
+ break if %w[succeeded failed].include?(op["status"])
300
+ sleep 1
301
+ op = api.get("operations/#{op['id']}")
302
+ end
303
+ raise Error, "operation #{op['id']} failed: #{op['error']}" if op["status"] == "failed"
304
+ puts "done (operation #{op['id']})"
305
+ end
306
+
307
+ # --- session --------------------------------------------------------
308
+ def cmd_login
309
+ url = @opts[:url] || @config.url || ask("Dalben URL [#{DEFAULT_URL}]: ").then { _1.empty? ? DEFAULT_URL : _1 }
310
+ email = @opts[:email] || ask("Email: ")
311
+ password = ask("Password: ", secret: true)
312
+ host = `hostname`.strip rescue "cli"
313
+ credentials = { email: email, password: password, name: "cli@#{host}" }
314
+ res = begin
315
+ Api.new(url).post("tokens", credentials)
316
+ rescue ApiError => e
317
+ raise unless e.reason == "otp_required"
318
+ Api.new(url).post("tokens", credentials.merge(otp: ask("Code from your authenticator app: ")))
319
+ end
320
+ @config.save(url: url, token: res.fetch("token"))
321
+ puts "Logged in to #{url} (token #{res['prefix']}…, expires #{res['expires_at']})"
322
+ end
323
+
324
+ # Revokes the token `dalben login` stored and forgets it; the URL and the
325
+ # default environment stay. A token from DALBEN_TOKEN is left alone.
326
+ def cmd_logout
327
+ return puts("Not logged in.") unless @config.saved_token
328
+ revoked = begin
329
+ Api.new(@config.saved_url, @config.saved_token).delete("tokens/current")
330
+ true
331
+ rescue StandardError => e
332
+ warn "could not revoke the token on the server (#{e.message}); revoke it under Profile, API tokens in the web UI"
333
+ false
334
+ end
335
+ @config.forget_token
336
+ puts revoked ? "Logged out; the token is revoked." : "Logged out locally."
337
+ end
338
+ def cmd_tokens = output(api.get("tokens")) { rows(_1, :id, :name, :prefix, :last_used_at, :expires_at) }
339
+
340
+ # --- SSH keys for git push --------------------------------------------
341
+ DEFAULT_KEYS = %w[id_ed25519.pub id_ecdsa.pub id_rsa.pub].freeze
342
+
343
+ def cmd_keys = output(api.get("ssh_keys")) { rows(_1, :id, :name, :fingerprint, :created_at) }
344
+
345
+ def cmd_keys_add
346
+ path = @argv.shift || DEFAULT_KEYS.map { File.join(Dir.home, ".ssh", _1) }.find { File.exist?(_1) } ||
347
+ raise(Error, "no public key in ~/.ssh; create one with ssh-keygen -t ed25519")
348
+ key = File.read(path).strip
349
+ raise Error, "#{path} is a private key; pass the .pub file" if key.include?("PRIVATE KEY")
350
+ res = api.post("ssh_keys", { public_key: key, name: @opts[:name] }.compact)
351
+ output(res) { puts "Added #{_1['name']} (#{_1['fingerprint']}). git push works on every server within a minute." }
352
+ end
353
+
354
+ def cmd_keys_remove
355
+ wanted = arg!("NAME, FINGERPRINT or ID")
356
+ matches = api.get("ssh_keys").select { [ _1["id"].to_s, _1["name"], _1["fingerprint"] ].include?(wanted) }
357
+ raise Error, "no SSH key matches #{wanted}" if matches.empty?
358
+ raise Error, "#{matches.size} keys are named #{wanted}; use the fingerprint or ID" if matches.size > 1
359
+ api.delete("ssh_keys/#{matches.first['id']}")
360
+ puts "Removed #{matches.first['name']}."
361
+ end
362
+
363
+ # --- environments ---------------------------------------------------
364
+ def cmd_env = puts(environment || "(none)")
365
+
366
+ def cmd_env_use
367
+ env = arg!("ENV")
368
+ @config.use_environment(env)
369
+ puts "Default environment: #{env}"
370
+ end
371
+
372
+ def cmd_env_clear = (@config.use_environment(nil); puts("No default environment"))
373
+
374
+ # --- servers --------------------------------------------------------
375
+ def cmd_servers = output(api.get("servers")) { rows(_1, :name, :environment, :host, :status, :dokku_version, :host_key_trusted) }
376
+
377
+ def cmd_servers_add
378
+ name, host = arg!("NAME"), arg!("HOST")
379
+ env = @opts[:env] || raise(Error, "missing --env (production, staging or dev)")
380
+ body = { name: name, environment: env, host: host, ssh_port: @opts[:port] || 22, host_key_fingerprint: @opts[:fingerprint] }.compact
381
+ res = api.post("servers", body)
382
+ server = res["server"]
383
+ unless server["host_key_trusted"]
384
+ puts "Host key fingerprint offered by #{host}:"
385
+ puts " #{server['host_key_fingerprint']}"
386
+ puts "Compare it with `ssh-keygen -lf /etc/ssh/ssh_host_ed25519_key.pub` on the server."
387
+ answer = ask("Trust this key? [y/N] ")
388
+ raise Error, "not trusted; remove it with `dalben servers:remove #{name} --confirm #{name}`" unless answer.downcase.start_with?("y")
389
+ res = api.post("servers/#{name}/trust", fingerprint: server["host_key_fingerprint"])
390
+ end
391
+ follow(res)
392
+ end
393
+
394
+ def cmd_servers_check = follow(api.post("servers/#{arg!('NAME')}/check"))
395
+
396
+ # Dokku is only read; --apply records what the dry run lists.
397
+ def cmd_servers_import
398
+ name = arg!("NAME")
399
+ plan = @opts[:apply] ? api.post("servers/#{name}/import") : api.get("servers/#{name}/import")
400
+ output(plan) do |p|
401
+ puts "#{p['applied'] ? 'Imported' : 'Would import'} into #{p['environment']}:"
402
+ p["apps"].each do |a|
403
+ parts = [ "app", a["name"], "(#{a['status']})", *a["formation"].map { "#{_1}=#{_2}" },
404
+ "domains:#{a['domains'].size}", "config:#{a['config_keys'].size}", "volumes:#{a['volumes'].size}" ]
405
+ puts " #{parts.join(' ')}"
406
+ end
407
+ p["addons"].each { puts " #{_1['kind']} #{_1['name']}#{" -> #{_1['app']}" if _1['app']}" }
408
+ p["skipped"].each { puts " skipped #{_1['type']} #{_1['name']}: #{_1['reason']}" }
409
+ puts "Run again with --apply to record this." unless p["applied"]
410
+ end
411
+ end
412
+
413
+ def cmd_servers_remove
414
+ name = arg!("NAME")
415
+ api.delete("servers/#{name}", confirm: @opts[:confirm].to_s)
416
+ puts "Removed #{name}"
417
+ end
418
+
419
+ # --- projects -------------------------------------------------------
420
+ def cmd_projects
421
+ output(api.get("projects")) { |list| rows(list.map { { "name" => _1["name"], "apps" => _1["apps"].size } }, :name, :apps) }
422
+ end
423
+
424
+ def cmd_projects_info = output(api.get("projects/#{arg!('PROJECT')}")) { rows(_1["apps"], :name, :environment, :status, :url) }
425
+ def cmd_projects_create = puts("Created #{api.post('projects', name: arg!('PROJECT'))['name']}")
426
+
427
+ def cmd_projects_rename
428
+ name, new_name = arg!("PROJECT"), arg!("NEW_NAME")
429
+ puts "Renamed #{name} to #{api.patch("projects/#{name}", new_name: new_name)['name']}"
430
+ end
431
+
432
+ def cmd_projects_destroy
433
+ name = arg!("PROJECT")
434
+ api.delete("projects/#{name}", confirm: @opts[:confirm].to_s)
435
+ puts "Deleted #{name}"
436
+ end
437
+
438
+ def cmd_projects_members = output(api.get("projects/#{arg!('PROJECT')}/members")) { rows(_1, :email, :role) }
439
+
440
+ def cmd_projects_members_add
441
+ name, email = arg!("PROJECT"), arg!("EMAIL")
442
+ member = api.post("projects/#{name}/members", email: email, **{ role: @opts[:role] }.compact)
443
+ puts "Added #{member['email']} to #{name} as #{member['role']}"
444
+ end
445
+
446
+ def cmd_projects_members_role
447
+ name, email, role = arg!("PROJECT"), arg!("EMAIL"), arg!("ROLE")
448
+ member = api.patch("projects/#{name}/members/#{URI.encode_www_form_component(email)}", role: role)
449
+ puts "#{member['email']} is now #{member['role']} in #{name}"
450
+ end
451
+
452
+ def cmd_projects_members_remove
453
+ name, email = arg!("PROJECT"), arg!("EMAIL")
454
+ api.delete("projects/#{name}/members/#{URI.encode_www_form_component(email)}")
455
+ puts "Removed #{email} from #{name}"
456
+ end
457
+
458
+ def project! = @opts[:project] || raise(Error, "missing --project")
459
+
460
+ # --- apps -----------------------------------------------------------
461
+ def cmd_apps = output(api.get("apps")) { rows(_1, :name, :project, :environment, :server, :status, :image) }
462
+
463
+ def cmd_apps_create
464
+ name = arg!("NAME")
465
+ res = api.post("apps", name: name, server: @opts[:server] || raise(Error, "missing --server"), project: project!, **{ tier: @opts[:tier] }.compact)
466
+ follow(res)
467
+ puts "git remote: #{res.dig('app', 'git_remote')}" if res.dig("app", "git_remote")
468
+ end
469
+
470
+ def cmd_apps_info = output(api.get("apps/#{app!}"))
471
+
472
+ def cmd_apps_tier
473
+ tier = arg!("TIER")
474
+ print_estimate(app!, tier: tier)
475
+ res = api.patch("apps/#{app!}/tier", tier: tier)
476
+ output(res) { puts "#{_1['name']} now runs on #{_1['tier']}." }
477
+ end
478
+
479
+ # --- billing ----------------------------------------------------------
480
+ def euros(cents) = format("€%.2f", cents / 100.0)
481
+
482
+ # Says what a change adds to the monthly bill on a manager that bills.
483
+ # A failed estimate stops nothing: the change itself reports a bad
484
+ # tier or kind, and an older manager has no estimates.
485
+ def print_estimate(app, query)
486
+ return if @opts[:json]
487
+ estimate = api.get("apps/#{app}/estimate", query)
488
+ return unless estimate["billing"]
489
+ added = estimate["added_cents"]
490
+ return puts("This adds nothing to the monthly bill.") if added.zero?
491
+ puts(added.positive? ? "This adds about #{euros(added)} a month." : "This saves about #{euros(-added)} a month.")
492
+ rescue ApiError
493
+ nil
494
+ end
495
+
496
+ # Normal tiers price an app per process; premium tiers are dedicated
497
+ # servers. A manager without categories only has normal tiers.
498
+ def cmd_tiers
499
+ output(api.get("tiers")) do |tiers|
500
+ premium, normal = tiers.map { _1.merge("price" => _1["monthly_cents"].zero? ? "free" : "#{euros(_1['monthly_cents'])}/month") }
501
+ .partition { _1["category"] == "premium" }
502
+ puts "Normal (per process, on a shared server):"
503
+ rows(normal.map do
504
+ _1.merge("cpu" => _1["cpu"] ? "#{_1['cpu']} vCPU" : "–", "postgres" => "#{_1['postgres_gb']} GB",
505
+ "storage" => _1["object_storage_gb"] ? "#{_1['object_storage_gb']} GB" : "–")
506
+ end, :key, :name, :memory, :cpu, :postgres, :storage, :price)
507
+ next if premium.empty?
508
+
509
+ puts "Premium (a dedicated server; ask support):"
510
+ rows(premium.map { _1.merge("server" => "#{_1['vcpus']} vCPU, #{_1['memory_mb'] / 1024} GB, #{_1['disk_gb']} GB disk") }, :key, :name, :server, :price)
511
+ end
512
+ end
513
+
514
+ def cmd_billing
515
+ output(api.get("projects/#{arg!('PROJECT')}/billing")) do |billing|
516
+ usage = billing["usage_this_month"]
517
+ puts "Status: #{billing['status'].tr('_', ' ')}"
518
+ puts "Trial: Basic is free for #{billing['trial_days_left']} more days, until #{billing['trial_ends_at']}" if billing["trial_days_left"]
519
+ puts "Spending cap: #{billing['spending_cap_cents'] ? "#{euros(billing['spending_cap_cents'])} a month" : 'none'}"
520
+ puts "This month so far: #{euros(usage['total_cents'])}, about #{euros(usage['projected_cents'])} by the end of the month"
521
+ rows(usage["lines"].map { _1.merge("cost" => euros(_1["cents"])) }, :label, :minutes, :cost)
522
+ puts "Charges:"
523
+ rows(billing["charges"].map { _1.merge("amount" => euros(_1["amount_cents"])) }, :month, :status, :amount)
524
+ end
525
+ end
526
+
527
+ def cmd_billing_checkout
528
+ url = api.post("projects/#{arg!('PROJECT')}/billing", {})["checkout_url"]
529
+ puts "Add a payment method at: #{url}"
530
+ end
531
+
532
+ def cmd_billing_cap
533
+ project = arg!("PROJECT")
534
+ euros = @opts[:off] ? nil : arg!("EUROS or --off")
535
+ res = api.patch("projects/#{project}/billing", spending_cap: euros)
536
+ cap = res["spending_cap_cents"]
537
+ puts(cap ? "#{res['customer']} may now spend up to #{euros(cap)} a month." : "#{res['customer']} has no spending cap now.")
538
+ end
539
+
540
+ def cmd_billing_cancel
541
+ res = api.delete("projects/#{arg!('PROJECT')}/billing", confirm: @opts[:confirm].to_s)
542
+ stopped = res["stopped_apps"].empty? ? "no paid apps were running" : "stopped #{res['stopped_apps'].join(', ')}"
543
+ puts "Canceled #{res['customer']}'s subscription. Charged #{euros(res['charged_cents'])} for usage so far; #{stopped}."
544
+ end
545
+
546
+ def cmd_apps_rename
547
+ new_name = arg!("NEW_NAME")
548
+ follow(api.patch("apps/#{app!}", new_name: new_name))
549
+ puts "Point your git remote at the new name: dalben git:remote -a #{new_name}"
550
+ end
551
+
552
+ def cmd_apps_move
553
+ app = app!
554
+ puts "Moved #{app} to #{api.patch("apps/#{app}", project: project!)['project']}"
555
+ end
556
+
557
+ def cmd_apps_destroy = follow(api.delete("apps/#{app!}", confirm: @opts[:confirm].to_s))
558
+ def cmd_deploy = follow(api.post("apps/#{app!}/deploys", image: arg!("IMAGE")))
559
+ def cmd_deploy_source
560
+ path = @argv.shift || "."
561
+ app = app!
562
+ archive = SourceArchive.new(path)
563
+ archive.pack do |file|
564
+ puts "Uploading #{archive.files} files (#{(file.size / 1024.0 / 1024).round(1)} MB)"
565
+ follow(api.upload("apps/#{app}/source_deploys", file, content_type: "application/gzip"))
566
+ end
567
+ end
568
+
569
+ def cmd_git_remote = puts(api.get("apps/#{app!}")["git_remote"])
570
+ def cmd_ps
571
+ output(api.get("apps/#{app!}")["formation"]) do |formation|
572
+ puts formation.empty? ? "(not scaled yet; Dokku runs web=1)" : formation.map { "#{_1}=#{_2}" }.join(" ")
573
+ end
574
+ end
575
+
576
+ def cmd_github_connect
577
+ body = { repo: arg!("OWNER/REPO"), branch: @opts[:branch], auto_deploy: @opts[:auto] || false }.compact
578
+ github = api.put("apps/#{app!}/github", body)["github"]
579
+ puts "#{github['repo']}@#{github['branch']}, #{github['auto_deploy'] ? 'deploys new commits automatically' : 'deploy with github:deploy'}"
580
+ end
581
+
582
+ def cmd_github_disconnect = (api.delete("apps/#{app!}/github"); puts("Disconnected from GitHub"))
583
+ def cmd_github_deploy
584
+ repo = @argv.shift
585
+ return follow(api.post("apps/#{app!}/github/deploy", { commit: @opts[:commit] }.compact)) unless repo
586
+ raise Error, "pass --server and --project for a new app or -a APP for an existing one" unless @opts[:server] || @opts[:app]
587
+
588
+ body = { repo: repo, branch: @opts[:branch], auto_deploy: @opts[:auto] || false }
589
+ body.merge!(@opts[:app] ? { app: app! } : { server: @opts[:server], project: project!, name: @opts[:name] })
590
+ res = api.post("repository_deploys", body.compact)
591
+ puts "#{res.dig('app', 'name')}@#{res.dig('app', 'environment')} deploys from #{repo}"
592
+ follow(res)
593
+ end
594
+
595
+ def cmd_ps_restart = follow(api.post("apps/#{app!}/restart"))
596
+
597
+ # --- releases -----------------------------------------------------------
598
+ def cmd_releases
599
+ output(api.get("apps/#{app!}/releases")) do |releases|
600
+ rows(releases.map { _1.merge("version" => _1["name"], "commit" => _1["commit"].to_s[0, 7], "author" => _1["author"] || "-",
601
+ "created" => _1["created_at"]) }, :version, :source, :status, :commit, :author, :created)
602
+ end
603
+ end
604
+
605
+ def cmd_releases_info
606
+ output(api.get("apps/#{app!}/releases/#{arg!('RELEASE')}")) do |release|
607
+ puts "#{release['name']}: #{release['description']}"
608
+ %w[status source commit author image rollback_of created_at].each { puts " #{_1.tr('_', ' ')}: #{release[_1] || '-'}" }
609
+ puts " rollback: #{release['rollbackable'] ? 'possible' : 'not possible, the image is not kept'}"
610
+ end
611
+ end
612
+
613
+ def cmd_rollback = follow(api.post("apps/#{app!}/releases/#{arg!('RELEASE')}/rollback"))
614
+
615
+ # --- one-off runs -------------------------------------------------------
616
+ CONSOLE = /\Adalben:console \h{32}\z/
617
+
618
+ # A console goes over SSH with the user's own key, straight to the
619
+ # node, so its input and output never pass the manager. ssh replaces
620
+ # this process; its exit status is the command's.
621
+ def cmd_run
622
+ command = @argv.join(" ")
623
+ raise Error, "usage: dalben run -a APP [--detach] -- COMMAND" if command.empty?
624
+ app = app!
625
+ return follow(api.post("apps/#{app}/runs", command: command, detach: true)) if @opts[:detach]
626
+
627
+ ssh = api.post("apps/#{app}/runs", command: command).fetch("ssh")
628
+ raise Error, "unexpected console command from the manager" unless ssh["command"].to_s.match?(CONSOLE)
629
+ exec_ssh("ssh", "-t", "-p", ssh["port"].to_s, "#{ssh['user']}@#{ssh['host']}", *ssh["command"].split)
630
+ end
631
+
632
+ def exec_ssh(*args)
633
+ Kernel.exec(*args)
634
+ rescue SystemCallError => e
635
+ raise Error, "cannot start ssh: #{e.message}"
636
+ end
637
+
638
+ def cmd_runs
639
+ output(api.get("apps/#{app!}/runs")) do |runs|
640
+ rows(runs.map { _1.merge("kind" => _1["interactive"] ? "console" : "detached", "user" => _1["user"] || "-",
641
+ "duration" => _1["duration"] ? "#{_1['duration']}s" : "-", "exit" => _1["exit_status"] || "-") },
642
+ :id, :command, :kind, :user, :started_at, :duration, :exit, :status)
643
+ end
644
+ end
645
+
646
+ # --- private registries -------------------------------------------------
647
+ def cmd_registry = output(api.get("projects/#{project!}/registry_credentials")) { rows(_1, :host, :username, :updated_at) }
648
+
649
+ def cmd_registry_login
650
+ host = arg!("HOST")
651
+ username = @opts[:username] || raise(Error, "missing -u USER")
652
+ project = project!
653
+ password = @opts[:password_stdin] ? $stdin.read.to_s.chomp : ask("Password or token for #{username}@#{host}: ", secret: true)
654
+ raise Error, "empty password" if password.empty?
655
+ login = api.post("projects/#{project}/registry_credentials", host: host, username: username, password: password)
656
+ puts "Saved the login for #{login['host']} as #{login['username']} in #{project}."
657
+ end
658
+
659
+ def cmd_registry_logout
660
+ host = arg!("HOST")
661
+ api.delete("projects/#{project!}/registry_credentials/#{URI.encode_www_form_component(host)}")
662
+ puts "Removed the login for #{host}."
663
+ end
664
+
665
+ # --- webhooks --------------------------------------------------------
666
+ def cmd_webhooks
667
+ output(api.get("projects/#{project!}/webhook")) do |webhook|
668
+ puts "URL: #{webhook['url']}", "Secret: #{webhook['secret']}", "Deliveries:"
669
+ rows(webhook["deliveries"], :id, :event, :status, :attempts, :response_code, :error, :created_at)
670
+ end
671
+ end
672
+
673
+ def cmd_webhooks_set
674
+ url = arg!("URL")
675
+ project = project!
676
+ webhook = api.patch("projects/#{project}/webhook", url: url)
677
+ puts "Alerts of #{project} are posted to #{webhook['url']}.", "Verify them with the secret #{webhook['secret']}"
678
+ end
679
+
680
+ def cmd_webhooks_remove
681
+ project = project!
682
+ api.delete("projects/#{project}/webhook")
683
+ puts "Alerts of #{project} are no longer posted."
684
+ end
685
+
686
+ def cmd_webhooks_test
687
+ delivery = api.post("projects/#{project!}/webhook/test")
688
+ puts "Queued #{delivery['event']} as #{delivery['id']}. See how it went with: dalben webhooks --project #{@opts[:project]}"
689
+ end
690
+
691
+ # --- review apps -----------------------------------------------------
692
+ def cmd_reviewapps
693
+ data = api.get("apps/#{app!}/review_apps")
694
+ output(data) do
695
+ puts "review apps are #{data['enabled'] ? 'on' : 'off'}, at most #{data['limit']} open in the project"
696
+ rows(data["apps"].map { _1.merge("pull_request" => "##{_1.dig('review', 'pull_request')}") }, :name, :pull_request, :status, :url)
697
+ end
698
+ end
699
+
700
+ def cmd_reviewapps_enable = switch_review_apps(true)
701
+ def cmd_reviewapps_disable = switch_review_apps(false)
702
+
703
+ def switch_review_apps(enabled)
704
+ app = app!
705
+ api.patch("apps/#{app}/review_apps", enabled: enabled)
706
+ puts "review apps are #{enabled ? 'on' : 'off'} for #{app}"
707
+ end
708
+
709
+ def cmd_reviewapps_limit
710
+ project = project!
711
+ limit = api.patch("projects/#{project}/review_apps", limit: arg!("N"))["review_apps_limit"]
712
+ puts "at most #{limit} review apps open in #{project}"
713
+ end
714
+
715
+ def cmd_maintenance = puts("maintenance is #{api.get("apps/#{app!}")['maintenance'] ? 'on' : 'off'}")
716
+ def cmd_maintenance_on = follow(api.patch("apps/#{app!}/maintenance", enabled: true))
717
+ def cmd_maintenance_off = follow(api.patch("apps/#{app!}/maintenance", enabled: false))
718
+
719
+ def cmd_ps_scale
720
+ formation = @argv.to_h { _1.split("=", 2).then { |k, v| [ k, Integer(v) ] } }
721
+ raise Error, "usage: ps:scale web=2 -a APP" if formation.empty?
722
+ follow(api.post("apps/#{app!}/scale", formation: formation))
723
+ rescue ArgumentError
724
+ raise Error, "usage: ps:scale web=2 -a APP"
725
+ end
726
+
727
+ def cmd_logs = output(api.get("apps/#{app!}/logs", lines: @opts[:num] || 200)) { print _1["logs"] }
728
+
729
+ # --- config ---------------------------------------------------------
730
+ def cmd_config
731
+ vars = api.get("apps/#{app!}/config")
732
+ vars = vars.transform_values { mask(_1) } unless @opts[:reveal]
733
+ output(vars) do
734
+ width = vars.keys.map(&:size).max.to_i
735
+ vars.each { |k, v| puts "#{k.ljust(width)} #{v}" }
736
+ end
737
+ end
738
+
739
+ def mask(value) = value.size <= 4 ? "****" : "#{value[0, 2]}****#{value[-2..]}"
740
+
741
+ def cmd_config_set
742
+ vars = @argv.to_h do |pair|
743
+ key, value = pair.split("=", 2)
744
+ raise Error, "expected KEY=VALUE, got #{pair}" if value.nil?
745
+ [ key, value ]
746
+ end
747
+ raise Error, "usage: config:set KEY=VALUE -a APP" if vars.empty?
748
+ follow(api.patch("apps/#{app!}/config", vars: vars, restart: @opts[:restart]))
749
+ end
750
+
751
+ def cmd_config_unset
752
+ raise Error, "usage: config:unset KEY -a APP" if @argv.empty?
753
+ follow(api.patch("apps/#{app!}/config", vars: @argv.to_h { [ _1, nil ] }, restart: @opts[:restart]))
754
+ end
755
+
756
+ # --- domains --------------------------------------------------------
757
+ def cmd_settings = output(api.get("apps/#{app!}/settings"))
758
+
759
+ # Dotted keys change one nested value; the rest of limits and nginx is kept.
760
+ def cmd_settings_set
761
+ raise Error, "missing KEY=VALUE" if @argv.empty?
762
+ changes = {}
763
+ @argv.each do |pair|
764
+ key, value = pair.split("=", 2)
765
+ raise Error, "expected KEY=VALUE, got #{pair}" if value.nil?
766
+ top, *parents, last = key.split(".")
767
+ top = top.tr("-", "_")
768
+ next changes[top] = value if last.nil?
769
+
770
+ changes[top] ||= api.get("apps/#{app!}/settings").fetch(top, {})
771
+ parents.reduce(changes[top]) { |hash, part| hash[part] ||= {} }[last] = value
772
+ end
773
+ follow(api.patch("apps/#{app!}/settings", settings: changes))
774
+ end
775
+
776
+ # A failed certificate gets Let's Encrypt's reason on its own line.
777
+ def cmd_domains
778
+ output(api.get("apps/#{app!}/domains")) do |domains|
779
+ # The CNAME target column only once a domain has one.
780
+ rows(domains, :hostname, *(:dns_target if domains.any? { _1["dns_target"] }), :certificate_status)
781
+ domains.select { _1["certificate_status"] == "failed" }.each { puts "#{_1['hostname']}: #{_1['certificate_error']}" }
782
+ end
783
+ end
784
+
785
+ def cmd_domains_add = follow(api.post("apps/#{app!}/domains", hostname: arg!("HOST"), tls: @opts[:tls]))
786
+ def cmd_domains_remove = follow(api.delete("apps/#{app!}/domains/#{arg!('HOST')}"))
787
+ def cmd_certs_retry = follow(api.post("apps/#{app!}/certificate"))
788
+
789
+ # --- log drains -----------------------------------------------------
790
+ def cmd_drains = output(api.get("apps/#{app!}/log_drains")) { rows(_1, :id, :kind, :url) }
791
+ def cmd_drains_add = follow(api.post("apps/#{app!}/log_drains", url: arg!("URL")))
792
+ def cmd_drains_remove = follow(api.delete("apps/#{app!}/log_drains/#{arg!('ID')}"))
793
+
794
+ # --- volumes --------------------------------------------------------
795
+ def cmd_volumes = output(api.get("apps/#{app!}/volumes")) { rows(_1, :name, :container_path, :host_path, :used_bytes, :limit_mb) }
796
+
797
+ def cmd_volumes_add
798
+ follow(api.post("apps/#{app!}/volumes", { name: arg!("NAME"), container_path: arg!("PATH"), limit_gb: @opts[:limit] }.compact))
799
+ end
800
+
801
+ def cmd_volumes_limit = follow(api.patch("apps/#{app!}/volumes/#{arg!('NAME')}/limit", limit_gb: arg!("GB")))
802
+ def cmd_volumes_remove = follow(api.delete("apps/#{app!}/volumes/#{arg!('NAME')}", confirm: @opts[:confirm].to_s))
803
+
804
+ VOLUME_RSYNC = /\Adalben:volume-rsync \h{32}\z/
805
+
806
+ # rsync over SSH with the user's own key, straight to the node, which
807
+ # runs the other side on the volume only. rsync replaces this process;
808
+ # its exit status is the copy's.
809
+ def cmd_volumes_push = copy_volume(:push)
810
+ def cmd_volumes_pull = copy_volume(:pull)
811
+ def cmd_volumes_sync = copy_volume(:sync)
812
+
813
+ def copy_volume(mode)
814
+ name = arg!("NAME")
815
+ dir = arg!("DIR")
816
+ raise Error, "sync deletes the volume's files that #{dir} does not have; add --confirm #{name}" if mode == :sync && @opts[:confirm] != name
817
+ raise Error, "#{dir} is not a directory" unless mode == :pull || File.directory?(dir)
818
+ grant = api.post("apps/#{app!}/volumes/#{name}/copy", direction: mode == :pull ? "pull" : "push")
819
+ ssh = grant.fetch("ssh")
820
+ raise Error, "unexpected copy command from the manager" unless ssh["command"].to_s.match?(VOLUME_RSYNC)
821
+ local = "#{dir.chomp('/')}/"
822
+ remote = "#{ssh['user']}@#{ssh['host']}:#{grant.fetch('path')}"
823
+ exec_rsync("rsync", "-az", *("--delete" if mode == :sync), "-e", "ssh -T -p #{Integer(ssh['port'])}", "--rsync-path", ssh["command"],
824
+ *(mode == :pull ? [ remote, local ] : [ local, remote ]))
825
+ end
826
+
827
+ # The node accepts rsync's arguments only on its command line, which
828
+ # RSYNC_PROTECT_ARGS would move into the connection.
829
+ def exec_rsync(*args)
830
+ Kernel.exec({ "RSYNC_PROTECT_ARGS" => nil }, *args)
831
+ rescue SystemCallError => e
832
+ raise Error, "cannot start rsync: #{e.message}; install rsync (on Windows, use WSL)"
833
+ end
834
+
835
+ # --- scheduler ------------------------------------------------------
836
+ def cmd_scheduler
837
+ output(api.get("apps/#{app!}/scheduled_jobs")) do |jobs|
838
+ rows(jobs.map { _1.merge("last_run" => _1.dig("last_run", "status"), "enabled" => _1["enabled"] ? "on" : "off") },
839
+ :id, :command, :schedule, :enabled, :next_run_at, :last_run)
840
+ end
841
+ end
842
+
843
+ def cmd_scheduler_add
844
+ command = @argv.join(" ").then { _1.empty? ? raise(Error, "missing COMMAND") : _1 }
845
+ job = api.post("apps/#{app!}/scheduled_jobs", { command:, **schedule_opts })
846
+ puts "Added job #{job['id']}: #{job['command']} (#{job['schedule']} UTC)"
847
+ end
848
+
849
+ def cmd_scheduler_update
850
+ id = arg!("ID")
851
+ command = @argv.join(" ").then { _1.empty? ? nil : _1 }
852
+ job = api.patch("apps/#{app!}/scheduled_jobs/#{id}", { command:, **schedule_opts, enabled: @opts[:enabled] }.compact)
853
+ puts "Job #{job['id']}: #{job['command']} (#{job['schedule']} UTC, #{job['enabled'] ? 'on' : 'off'})"
854
+ end
855
+
856
+ def cmd_scheduler_run = follow(api.post("apps/#{app!}/scheduled_jobs/#{arg!('ID')}/run"))
857
+
858
+ def cmd_scheduler_remove
859
+ id = arg!("ID")
860
+ api.delete("apps/#{app!}/scheduled_jobs/#{id}", confirm: @opts[:confirm].to_s)
861
+ puts "Removed job #{id}"
862
+ end
863
+
864
+ def schedule_opts = { schedule: @opts[:schedule], every: @opts[:every], at: @opts[:at] }.compact
865
+
866
+ # --- addons ---------------------------------------------------------
867
+ def cmd_addons
868
+ list = @opts[:all] ? api.get("addons", all: 1) : api.get("addons")
869
+ output(list) { rows(_1, :id, :kind, :version, :name, :environment, :app, :status, :used_bytes, :limit_mb, :backup_schedule, :last_backup_at) }
870
+ end
871
+
872
+ def cmd_addons_create
873
+ body = { kind: arg!("KIND"), app: (app! if @opts[:app]), server: @opts[:server], name: @opts[:name],
874
+ backup_destination: @opts[:destination], backup_schedule: @opts[:schedule],
875
+ backup_retention: @opts[:retention], limit_gb: @opts[:limit], version: @opts[:version] }.compact
876
+ print_estimate(body[:app], { addon: body[:kind], limit_gb: body[:limit_gb] }.compact) if body[:app]
877
+ follow(api.post("addons", body))
878
+ end
879
+
880
+ def cmd_addons_limit = follow(api.patch("addons/#{scoped(arg!('NAME'))}/limit", limit_gb: arg!("GB")))
881
+ def cmd_addons_destroy = follow(api.delete("addons/#{scoped(arg!('NAME'))}", confirm: @opts[:confirm].to_s))
882
+
883
+ # --- backups --------------------------------------------------------
884
+ def cmd_backups_destinations = output(api.get("backup_destinations")) { rows(_1, :name, :endpoint, :bucket, :prefix) }
885
+
886
+ def cmd_backups_destinations_add
887
+ name = arg!("NAME")
888
+ body = { name: name, bucket: @opts[:bucket] || raise(Error, "missing --bucket"), endpoint: @opts[:endpoint],
889
+ region: @opts[:region], prefix: @opts[:prefix] }.compact
890
+ body[:access_key_id] = ask("Access key id: ")
891
+ body[:secret_access_key] = ask("Secret access key: ", secret: true)
892
+ body[:encryption_passphrase] = ask("Encryption passphrase (min 20 chars, store it somewhere safe!): ", secret: true)
893
+ raise Error, "passphrases do not match" unless ask("Repeat passphrase: ", secret: true) == body[:encryption_passphrase]
894
+ api.post("backup_destinations", body)
895
+ puts "Added backup destination #{name}"
896
+ end
897
+
898
+ def cmd_backups
899
+ addon = scoped(arg!("ADDON"))
900
+ output(api.get("addons/#{addon}/backups")) { rows(_1, :id, :status, :size_bytes, :finished_at, :verification_status) }
901
+ end
902
+
903
+ def cmd_backups_capture = follow(api.post("addons/#{scoped(arg!('ADDON'))}/backups"))
904
+ def cmd_backups_restore = follow(api.post("backups/#{arg!('BACKUP_ID')}/restore", {}, confirm: @opts[:confirm].to_s))
905
+ def cmd_backups_verify = follow(api.post("backups/#{arg!('BACKUP_ID')}/verify"))
906
+
907
+ def cmd_backups_schedule
908
+ body = { backup_destination: @opts[:destination], backup_schedule: @opts[:schedule], backup_retention: @opts[:retention] }.compact
909
+ res = api.patch("addons/#{scoped(arg!('ADDON'))}", body)
910
+ puts "#{res['name']}: #{res['backup_schedule']} -> #{res['backup_destination']} (keep #{res['backup_retention']})"
911
+ end
912
+
913
+ # --- point-in-time recovery -----------------------------------------
914
+ def cmd_pg_pitr
915
+ output(api.get("addons/#{scoped(arg!('ADDON'))}/pitr")) do |pitr|
916
+ next puts("#{pitr['name']}: point-in-time recovery is off (#{pitr['pitr_days']} days on its tier)") unless pitr["pitr_enabled_at"]
917
+ puts "#{pitr['name']}: point-in-time recovery is on, #{pitr['pitr_days']} days"
918
+ puts " restorable from #{pitr['pitr_restorable_from'] || 'after the first base backup'}"
919
+ puts " last archived #{pitr['pitr_latest_at'] || '-'}"
920
+ end
921
+ end
922
+
923
+ def cmd_pg_pitr_enable = follow(api.post("addons/#{scoped(arg!('ADDON'))}/pitr"))
924
+ def cmd_pg_pitr_disable = follow(api.delete("addons/#{scoped(arg!('ADDON'))}/pitr"))
925
+
926
+ def cmd_pg_restore
927
+ addon = scoped(arg!("ADDON"))
928
+ to = @opts[:to] || raise(Error, 'missing --to "YYYY-MM-DD HH:MM" (UTC unless an offset is given)')
929
+ res = api.post("addons/#{addon}/pitr/restore", { to: to, name: @opts[:as] }.compact)
930
+ puts "Restoring into #{res['addon']['name']}"
931
+ follow(res)
932
+ end
933
+
934
+ # --- Postgres access and versions -------------------------------------
935
+ DB_CONNECT = /\Adalben:db-connect \h{32}\z/
936
+ DB_TUNNEL = /\Adalben:db-tunnel \h{32}\z/
937
+
938
+ # psql goes over SSH with the user's own key, straight to the node, like
939
+ # a console; ssh replaces this process.
940
+ def cmd_pg_psql
941
+ ssh = api.post("addons/#{scoped(arg!('ADDON'))}/psql").fetch("ssh")
942
+ raise Error, "unexpected psql command from the manager" unless ssh["command"].to_s.match?(DB_CONNECT)
943
+ exec_ssh("ssh", "-t", "-p", ssh["port"].to_s, "#{ssh['user']}@#{ssh['host']}", *ssh["command"].split)
944
+ end
945
+
946
+ # A local port for GUI tools. Dokku refuses SSH port forwarding for user
947
+ # keys, so every connection to the port gets its own SSH session, which
948
+ # the node joins to the database. Runs until Ctrl-C.
949
+ def cmd_pg_tunnel
950
+ port = @opts[:port] || 5432
951
+ grant = api.post("addons/#{scoped(arg!('ADDON'))}/tunnel")
952
+ ssh = grant.fetch("ssh")
953
+ raise Error, "unexpected tunnel command from the manager" unless ssh["command"].to_s.match?(DB_TUNNEL)
954
+ server = listen(port)
955
+ db = grant.fetch("connection")
956
+ puts "Tunnel open until #{grant['expires_at']}. Connect to:",
957
+ " postgres://#{db['user']}:#{db['password']}@127.0.0.1:#{port}/#{db['database']}",
958
+ "Press Ctrl-C to close it."
959
+ session = [ "ssh", "-T", "-p", ssh["port"].to_s, "#{ssh['user']}@#{ssh['host']}", *ssh["command"].split ]
960
+ loop { relay(server.accept, session) }
961
+ ensure
962
+ server&.close
963
+ end
964
+
965
+ def listen(port)
966
+ TCPServer.new("127.0.0.1", port)
967
+ rescue SystemCallError => e
968
+ raise Error, "cannot listen on 127.0.0.1:#{port} (#{e.message}); pick another with --port"
969
+ end
970
+
971
+ # One SSH session per connection, with the socket as its stdin and stdout.
972
+ def relay(socket, session)
973
+ Process.detach(Process.spawn(*session, in: socket, out: socket))
974
+ rescue SystemCallError => e
975
+ warn "cannot start ssh: #{e.message}"
976
+ ensure
977
+ socket.close
978
+ end
979
+
980
+ def cmd_pg_credentials_rotate = follow(api.post("addons/#{scoped(arg!('ADDON'))}/rotate", {}, confirm: @opts[:confirm].to_s))
981
+
982
+ def cmd_pg_fork
983
+ res = api.post("backups/#{arg!('BACKUP_ID')}/fork", { name: @opts[:as], app: (app! if @opts[:app]) }.compact)
984
+ puts "Forking into #{res['addon']['name']}"
985
+ follow(res)
986
+ end
987
+
988
+ def cmd_pg_upgrade
989
+ addon = scoped(arg!("ADDON"))
990
+ version = @opts[:version] || raise(Error, "missing --version, such as --version 17")
991
+ res = api.post("addons/#{addon}/upgrade", { version: version, name: @opts[:as] }.compact)
992
+ puts "Copying into #{res['addon']['name']} (Postgres #{res['addon']['version']})"
993
+ follow(res)
994
+ end
995
+
996
+ def cmd_pg_upgrade_switch = follow(api.post("addons/#{scoped(arg!('ADDON'))}/switch", {}, confirm: @opts[:confirm].to_s))
997
+
998
+ # --- imports --------------------------------------------------------
999
+ def cmd_import
1000
+ source = arg!("SOURCE, such as heroku")
1001
+ raise Error, "unknown source #{source}; only `dalben import heroku` exists" unless source == "heroku"
1002
+ heroku_app = arg!("HEROKU_APP")
1003
+ server = @opts[:server] || raise(Error, "missing --server")
1004
+ body = { heroku_app: heroku_app, project: project!, server: server, name: @opts[:app], token: heroku_token }
1005
+ res = api.post("imports", body.compact)
1006
+ import = res.fetch("import")
1007
+ print_import_plan(import)
1008
+ follow(res)
1009
+ print_next_steps(import)
1010
+ end
1011
+
1012
+ def cmd_imports
1013
+ output(api.get("imports")) { rows(_1, :id, :source_app, :app, :project, :status, :database_copied_at, :created_at) }
1014
+ end
1015
+
1016
+ def cmd_import_db
1017
+ id = arg!("IMPORT_ID")
1018
+ res = api.post("imports/#{id}/database", token: heroku_token)
1019
+ puts "Copying #{res.dig('import', 'source_app')}'s database from Heroku into #{res.dig('import', 'app')} again; this replaces its data."
1020
+ follow(res)
1021
+ end
1022
+
1023
+ # From --token-stdin, HEROKU_API_KEY or a prompt. Dalben only reads the
1024
+ # Heroku app with it, during the request, and never stores it.
1025
+ def heroku_token
1026
+ token = if @opts[:token_stdin] then $stdin.read
1027
+ elsif ENV["HEROKU_API_KEY"].to_s.strip != "" then ENV["HEROKU_API_KEY"]
1028
+ else ask("Heroku API token (`heroku auth:token`; used for this import only, never stored): ", secret: true)
1029
+ end
1030
+ token.to_s.strip.then { _1.empty? ? raise(Error, "empty Heroku API token") : _1 }
1031
+ end
1032
+
1033
+ def print_import_plan(import)
1034
+ plan = import["plan"]
1035
+ puts "Importing #{import['source_app']} from Heroku into #{import['app']} (import #{import['id']}, tier #{plan['tier']})"
1036
+ plan["addons"].each { puts " add-on #{_1['heroku']} -> #{_1['name']} (#{_1['kind']})" }
1037
+ plan["skipped_addons"].each { puts " skipped #{_1['heroku']}: #{_1['reason']}; not copied: #{_1['config_vars'].join(', ')}" }
1038
+ puts " config #{plan['config_vars'].size} vars; not copied: #{plan['skipped_config_vars'].join(', ')}"
1039
+ plan["skipped_domains"].each { puts " skipped domain #{_1}" }
1040
+ plan["warnings"].each { puts " warning #{_1}" }
1041
+ end
1042
+
1043
+ def print_next_steps(import)
1044
+ plan = import["plan"]
1045
+ app = import["app"]
1046
+ puts "", "Next steps (code is not imported):"
1047
+ puts " - Push your code: git remote add dalben #{import['git_remote']} && git push dalben main,"
1048
+ puts " or deploy from GitHub: dalben github:connect OWNER/REPO -a #{app} --auto"
1049
+ scale = plan["formation"].map { "#{_1}=#{_2}" }.join(" ")
1050
+ puts " - Scale as on Heroku after the first deploy: dalben ps:scale #{scale} -a #{app}" unless scale.empty?
1051
+ kept = plan["addons"].reject { _1["kind"] == "postgres" }.map { _1["heroku"] }
1052
+ puts " - The data of #{kept.join(', ')} is not copied." if kept.any?
1053
+ if plan["addons"].any? { _1["kind"] == "postgres" }
1054
+ puts " - Final cut-over: heroku maintenance:on -a #{import['source_app']}, then dalben import:db #{import['id']}"
1055
+ end
1056
+ import["dns"].each do |domain|
1057
+ target = domain["cname"] ? "a CNAME at #{domain['cname']}" : "an A record at #{domain['address']}"
1058
+ puts " - Point #{domain['hostname']} at #{target}; its certificate follows once DNS points here"
1059
+ end
1060
+ end
1061
+
1062
+ # --- other ----------------------------------------------------------
1063
+ def cmd_operations
1064
+ if (id = @argv.shift)
1065
+ op = api.get("operations/#{id}")
1066
+ puts "#{op['kind']} #{op['status']}", op["log"]
1067
+ puts "error: #{op['error']}" if op["error"]
1068
+ else
1069
+ output(api.get("operations")) { rows(_1, :id, :kind, :status, :target_type, :target_id, :created_at) }
1070
+ end
1071
+ end
1072
+
1073
+ def cmd_audit = output(api.get("audit_events")) { rows(_1, :created_at, :user, :action, :target_type, :target_id, :ip) }
1074
+ end
1075
+ end