You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

408 lines
13 KiB

  1. # frozen_string_literal: true
  2. require 'tty-command'
  3. require 'tty-prompt'
  4. namespace :mastodon do
  5. desc 'Configure the instance for production use'
  6. task :setup do
  7. prompt = TTY::Prompt.new
  8. env = {}
  9. begin
  10. prompt.say('Your instance is identified by its domain name. Changing it afterward will break things.')
  11. env['LOCAL_DOMAIN'] = prompt.ask('Domain name:') do |q|
  12. q.required true
  13. q.modify :strip
  14. q.validate(/\A[a-z0-9\.\-]+\z/i)
  15. q.messages[:valid?] = 'Invalid domain. If you intend to use unicode characters, enter punycode here'
  16. end
  17. prompt.say "\n"
  18. prompt.say('Single user mode disables registrations and redirects the landing page to your public profile.')
  19. env['SINGLE_USER_MODE'] = prompt.yes?('Do you want to enable single user mode?', default: false)
  20. %w(SECRET_KEY_BASE OTP_SECRET).each do |key|
  21. env[key] = SecureRandom.hex(64)
  22. end
  23. vapid_key = Webpush.generate_key
  24. env['VAPID_PRIVATE_KEY'] = vapid_key.private_key
  25. env['VAPID_PUBLIC_KEY'] = vapid_key.public_key
  26. prompt.say "\n"
  27. using_docker = prompt.yes?('Are you using Docker to run Mastodon?')
  28. db_connection_works = false
  29. prompt.say "\n"
  30. loop do
  31. env['DB_HOST'] = prompt.ask('PostgreSQL host:') do |q|
  32. q.required true
  33. q.default using_docker ? 'db' : '/var/run/postgresql'
  34. q.modify :strip
  35. end
  36. env['DB_PORT'] = prompt.ask('PostgreSQL port:') do |q|
  37. q.required true
  38. q.default 5432
  39. q.convert :int
  40. end
  41. env['DB_NAME'] = prompt.ask('Name of PostgreSQL database:') do |q|
  42. q.required true
  43. q.default using_docker ? 'postgres' : 'mastodon_production'
  44. q.modify :strip
  45. end
  46. env['DB_USER'] = prompt.ask('Name of PostgreSQL user:') do |q|
  47. q.required true
  48. q.default using_docker ? 'postgres' : 'mastodon'
  49. q.modify :strip
  50. end
  51. env['DB_PASS'] = prompt.ask('Password of PostgreSQL user:') do |q|
  52. q.echo false
  53. end
  54. # The chosen database may not exist yet. Connect to default database
  55. # to avoid "database does not exist" error.
  56. db_options = {
  57. adapter: :postgresql,
  58. database: 'postgres',
  59. host: env['DB_HOST'],
  60. port: env['DB_PORT'],
  61. user: env['DB_USER'],
  62. password: env['DB_PASS'],
  63. }
  64. begin
  65. ActiveRecord::Base.establish_connection(db_options)
  66. ActiveRecord::Base.connection
  67. prompt.ok 'Database configuration works! 🎆'
  68. db_connection_works = true
  69. break
  70. rescue StandardError => e
  71. prompt.error 'Database connection could not be established with this configuration, try again.'
  72. prompt.error e.message
  73. break unless prompt.yes?('Try again?')
  74. end
  75. end
  76. prompt.say "\n"
  77. loop do
  78. env['REDIS_HOST'] = prompt.ask('Redis host:') do |q|
  79. q.required true
  80. q.default using_docker ? 'redis' : 'localhost'
  81. q.modify :strip
  82. end
  83. env['REDIS_PORT'] = prompt.ask('Redis port:') do |q|
  84. q.required true
  85. q.default 6379
  86. q.convert :int
  87. end
  88. env['REDIS_PASSWORD'] = prompt.ask('Redis password:') do |q|
  89. q.required false
  90. q.default nil
  91. q.modify :strip
  92. end
  93. redis_options = {
  94. host: env['REDIS_HOST'],
  95. port: env['REDIS_PORT'],
  96. password: env['REDIS_PASSWORD'],
  97. driver: :hiredis,
  98. }
  99. begin
  100. redis = Redis.new(redis_options)
  101. redis.ping
  102. prompt.ok 'Redis configuration works! 🎆'
  103. break
  104. rescue StandardError => e
  105. prompt.error 'Redis connection could not be established with this configuration, try again.'
  106. prompt.error e.message
  107. break unless prompt.yes?('Try again?')
  108. end
  109. end
  110. prompt.say "\n"
  111. if prompt.yes?('Do you want to store uploaded files on the cloud?', default: false)
  112. case prompt.select('Provider', ['Amazon S3', 'Wasabi', 'Minio'])
  113. when 'Amazon S3'
  114. env['S3_ENABLED'] = 'true'
  115. env['S3_PROTOCOL'] = 'https'
  116. env['S3_BUCKET'] = prompt.ask('S3 bucket name:') do |q|
  117. q.required true
  118. q.default "files.#{env['LOCAL_DOMAIN']}"
  119. q.modify :strip
  120. end
  121. env['S3_REGION'] = prompt.ask('S3 region:') do |q|
  122. q.required true
  123. q.default 'us-east-1'
  124. q.modify :strip
  125. end
  126. env['S3_HOSTNAME'] = prompt.ask('S3 hostname:') do |q|
  127. q.required true
  128. q.default 's3-us-east-1.amazonaws.com'
  129. q.modify :strip
  130. end
  131. env['AWS_ACCESS_KEY_ID'] = prompt.ask('S3 access key:') do |q|
  132. q.required true
  133. q.modify :strip
  134. end
  135. env['AWS_SECRET_ACCESS_KEY'] = prompt.ask('S3 secret key:') do |q|
  136. q.required true
  137. q.modify :strip
  138. end
  139. when 'Wasabi'
  140. env['S3_ENABLED'] = 'true'
  141. env['S3_PROTOCOL'] = 'https'
  142. env['S3_REGION'] = 'us-east-1'
  143. env['S3_HOSTNAME'] = 's3.wasabisys.com'
  144. env['S3_ENDPOINT'] = 'https://s3.wasabisys.com/'
  145. env['S3_BUCKET'] = prompt.ask('Wasabi bucket name:') do |q|
  146. q.required true
  147. q.default "files.#{env['LOCAL_DOMAIN']}"
  148. q.modify :strip
  149. end
  150. env['AWS_ACCESS_KEY_ID'] = prompt.ask('Wasabi access key:') do |q|
  151. q.required true
  152. q.modify :strip
  153. end
  154. env['AWS_SECRET_ACCESS_KEY'] = prompt.ask('Wasabi secret key:') do |q|
  155. q.required true
  156. q.modify :strip
  157. end
  158. when 'Minio'
  159. env['S3_ENABLED'] = 'true'
  160. env['S3_PROTOCOL'] = 'https'
  161. env['S3_REGION'] = 'us-east-1'
  162. env['S3_ENDPOINT'] = prompt.ask('Minio endpoint URL:') do |q|
  163. q.required true
  164. q.modify :strip
  165. end
  166. env['S3_PROTOCOL'] = env['S3_ENDPOINT'].start_with?('https') ? 'https' : 'http'
  167. env['S3_HOSTNAME'] = env['S3_ENDPOINT'].gsub(/\Ahttps?:\/\//, '')
  168. env['S3_BUCKET'] = prompt.ask('Minio bucket name:') do |q|
  169. q.required true
  170. q.default "files.#{env['LOCAL_DOMAIN']}"
  171. q.modify :strip
  172. end
  173. env['AWS_ACCESS_KEY_ID'] = prompt.ask('Minio access key:') do |q|
  174. q.required true
  175. q.modify :strip
  176. end
  177. env['AWS_SECRET_ACCESS_KEY'] = prompt.ask('Minio secret key:') do |q|
  178. q.required true
  179. q.modify :strip
  180. end
  181. end
  182. if prompt.yes?('Do you want to access the uploaded files from your own domain?')
  183. env['S3_ALIAS_HOST'] = prompt.ask('Domain for uploaded files:') do |q|
  184. q.required true
  185. q.default "files.#{env['LOCAL_DOMAIN']}"
  186. q.modify :strip
  187. end
  188. end
  189. end
  190. prompt.say "\n"
  191. loop do
  192. if prompt.yes?('Do you want to send e-mails from localhost?', default: false)
  193. env['SMTP_SERVER'] = 'localhost'
  194. env['SMTP_PORT'] = 25
  195. env['SMTP_AUTH_METHOD'] = 'none'
  196. env['SMTP_OPENSSL_VERIFY_MODE'] = 'none'
  197. else
  198. env['SMTP_SERVER'] = prompt.ask('SMTP server:') do |q|
  199. q.required true
  200. q.default 'smtp.mailgun.org'
  201. q.modify :strip
  202. end
  203. env['SMTP_PORT'] = prompt.ask('SMTP port:') do |q|
  204. q.required true
  205. q.default 587
  206. q.convert :int
  207. end
  208. env['SMTP_LOGIN'] = prompt.ask('SMTP username:') do |q|
  209. q.modify :strip
  210. end
  211. env['SMTP_PASSWORD'] = prompt.ask('SMTP password:') do |q|
  212. q.echo false
  213. end
  214. env['SMTP_AUTH_METHOD'] = prompt.ask('SMTP authentication:') do |q|
  215. q.required
  216. q.default 'plain'
  217. q.modify :strip
  218. end
  219. env['SMTP_OPENSSL_VERIFY_MODE'] = prompt.select('SMTP OpenSSL verify mode:', %w(none peer client_once fail_if_no_peer_cert))
  220. end
  221. env['SMTP_FROM_ADDRESS'] = prompt.ask('E-mail address to send e-mails "from":') do |q|
  222. q.required true
  223. q.default "Mastodon <notifications@#{env['LOCAL_DOMAIN']}>"
  224. q.modify :strip
  225. end
  226. break unless prompt.yes?('Send a test e-mail with this configuration right now?')
  227. send_to = prompt.ask('Send test e-mail to:', required: true)
  228. begin
  229. ActionMailer::Base.smtp_settings = {
  230. port: env['SMTP_PORT'],
  231. address: env['SMTP_SERVER'],
  232. user_name: env['SMTP_LOGIN'].presence,
  233. password: env['SMTP_PASSWORD'].presence,
  234. domain: env['LOCAL_DOMAIN'],
  235. authentication: env['SMTP_AUTH_METHOD'] == 'none' ? nil : env['SMTP_AUTH_METHOD'] || :plain,
  236. openssl_verify_mode: env['SMTP_OPENSSL_VERIFY_MODE'],
  237. enable_starttls_auto: true,
  238. }
  239. ActionMailer::Base.default_options = {
  240. from: env['SMTP_FROM_ADDRESS'],
  241. }
  242. mail = ActionMailer::Base.new.mail to: send_to, subject: 'Test', body: 'Mastodon SMTP configuration works!'
  243. mail.deliver
  244. break
  245. rescue StandardError => e
  246. prompt.error 'E-mail could not be sent with this configuration, try again.'
  247. prompt.error e.message
  248. break unless prompt.yes?('Try again?')
  249. end
  250. end
  251. prompt.say "\n"
  252. prompt.say 'This configuration will be written to .env.production'
  253. if prompt.yes?('Save configuration?')
  254. cmd = TTY::Command.new(printer: :quiet)
  255. File.write(Rails.root.join('.env.production'), "# Generated with mastodon:setup on #{Time.now.utc}\n\n" + env.each_pair.map { |key, value| "#{key}=#{value}" }.join("\n") + "\n")
  256. if using_docker
  257. prompt.ok 'Below is your configuration, save it to an .env.production file outside Docker:'
  258. prompt.say "\n"
  259. prompt.say File.read(Rails.root.join('.env.production'))
  260. prompt.say "\n"
  261. prompt.ok 'It is also saved within this container so you can proceed with this wizard.'
  262. end
  263. prompt.say "\n"
  264. prompt.say 'Now that configuration is saved, the database schema must be loaded.'
  265. prompt.warn 'If the database already exists, this will erase its contents.'
  266. if prompt.yes?('Prepare the database now?')
  267. prompt.say 'Running `RAILS_ENV=production rails db:setup` ...'
  268. prompt.say "\n\n"
  269. if cmd.run!({ RAILS_ENV: 'production', SAFETY_ASSURED: 1 }, :rails, 'db:setup').failure?
  270. prompt.error 'That failed! Perhaps your configuration is not right'
  271. else
  272. prompt.ok 'Done!'
  273. end
  274. end
  275. prompt.say "\n"
  276. prompt.say 'The final step is compiling CSS/JS assets.'
  277. prompt.say 'This may take a while and consume a lot of RAM.'
  278. if prompt.yes?('Compile the assets now?')
  279. prompt.say 'Running `RAILS_ENV=production rails assets:precompile` ...'
  280. prompt.say "\n\n"
  281. if cmd.run!({ RAILS_ENV: 'production' }, :rails, 'assets:precompile').failure?
  282. prompt.error 'That failed! Maybe you need swap space?'
  283. else
  284. prompt.say 'Done!'
  285. end
  286. end
  287. prompt.say "\n"
  288. prompt.ok 'All done! You can now power on the Mastodon server 🐘'
  289. prompt.say "\n"
  290. if db_connection_works && prompt.yes?('Do you want to create an admin user straight away?')
  291. env.each_pair do |key, value|
  292. ENV[key] = value.to_s
  293. end
  294. require_relative '../../config/environment'
  295. disable_log_stdout!
  296. username = prompt.ask('Username:') do |q|
  297. q.required true
  298. q.default 'admin'
  299. q.validate(/\A[a-z0-9_]+\z/i)
  300. q.modify :strip
  301. end
  302. email = prompt.ask('E-mail:') do |q|
  303. q.required true
  304. q.modify :strip
  305. end
  306. password = SecureRandom.hex(16)
  307. user = User.new(admin: true, email: email, password: password, confirmed_at: Time.now.utc, account_attributes: { username: username })
  308. user.save(validate: false)
  309. prompt.ok "You can login with the password: #{password}"
  310. prompt.warn 'You can change your password once you login.'
  311. end
  312. else
  313. prompt.warn 'Nothing saved. Bye!'
  314. end
  315. rescue TTY::Reader::InputInterrupt
  316. prompt.ok 'Aborting. Bye!'
  317. end
  318. end
  319. namespace :webpush do
  320. desc 'Generate VAPID key'
  321. task generate_vapid_key: :environment do
  322. vapid_key = Webpush.generate_key
  323. puts "VAPID_PRIVATE_KEY=#{vapid_key.private_key}"
  324. puts "VAPID_PUBLIC_KEY=#{vapid_key.public_key}"
  325. end
  326. end
  327. end
  328. def disable_log_stdout!
  329. dev_null = Logger.new('/dev/null')
  330. Rails.logger = dev_null
  331. ActiveRecord::Base.logger = dev_null
  332. HttpLog.configuration.logger = dev_null
  333. Paperclip.options[:log] = false
  334. end