client_management/lib/tasks/change_site_server_name.rake

51 lines
2.1 KiB
Ruby
Raw Normal View History

2021-02-17 16:59:11 +00:00
require 'net/ssh'
require 'pathname'
2021-04-19 01:29:53 +00:00
require 'json'
2021-02-17 16:59:11 +00:00
namespace :create_site do
desc "Change Site Server Name"
2021-04-19 01:29:53 +00:00
task :change_site_server_name,[:id,:server_name,:port] => :environment do |task,args|
2021-02-17 16:59:11 +00:00
begin
2021-04-19 01:29:53 +00:00
@site_construct = SiteConstruct.find(args.id)
site_server = @site_construct.site_server
2021-02-17 16:59:11 +00:00
if !site_server.nil?
@password = site_server.password
2021-04-19 01:29:53 +00:00
update_infos("Starting change domain name and ports.")
2023-02-23 04:52:58 +00:00
Net::SSH.start(site_server.ip , site_server.account , { password: site_server.password, port: site_server.port}) do |ssh|
2021-04-19 01:29:53 +00:00
@site_construct.update(:domain_name=>args.server_name)
if args.port.present?
all_ports = args.port.split('////')
@site_construct.update(:port=> all_ports )
end
change_construct_nginx(ssh,@site_construct)
2021-04-19 01:29:53 +00:00
@site_construct.update(:status=>'finish')
2021-02-17 16:59:11 +00:00
end
end
rescue => e
2021-04-19 01:29:53 +00:00
update_infos(e.to_s)
@site_construct.update(:status=>'error')
2021-02-17 16:59:11 +00:00
puts [e,e.backtrace]
end
end
def change_construct_nginx(ssh,site_construct,update_multithread=false)
@is_multithread = update_multithread
auto_update_infos("Reading setting file...")
nginx_file_content = exec_command_by_user(ssh,"cat #{site_construct.nginx_file}")
nginx_file_content = site_construct.generate_nginx_text(nginx_file_content)
auto_update_infos("Writing...")
2022-09-08 06:48:32 +00:00
cmd = "x='#{nginx_file_content.gsub("\\$","$").gsub(/'{1,3}/,"\"\'\"")}'; echo '#{@password}' | sudo -S sh -c \"echo '$x' > #{site_construct.nginx_file}\""
exec_command_by_user(ssh,cmd)
exec_ssh_command_by_sudo(ssh,"service nginx restart")
auto_update_infos("Finish!")
end
2021-02-18 01:46:55 +00:00
def exec_command_by_user(session,command)
output = session.exec!(command)
2021-03-06 10:48:14 +00:00
return output[0...-1].gsub(/^\n[\n]+/,'')
2021-02-18 01:46:55 +00:00
end
2021-02-17 16:59:11 +00:00
def exec_ssh_command_by_sudo(session,command)
output = session.exec!("echo '#{@password}' | sudo -S #{command}")
if output.include?("sudo:") && output.include?("command not found")
output = session.exec!(command)
end
2022-07-21 16:10:04 +00:00
return output.encode!("UTF-8", :invalid => :replace, :undef => :replace, :replace => '')
2021-02-17 16:59:11 +00:00
end
end