require 'net/ssh' require 'pathname' namespace :create_site do desc "Create Site Script" task :exec_commands,[:site_construct_id,:commands,:type] => :environment do |task,args| @site_construct = SiteConstruct.find(args.site_construct_id) site_server = SiteServer.where(:server_name=>@site_construct.server_type).first ip = site_server.ip user = site_server.account password = site_server.password @password = password #begin Net::SSH.start(ip , user , password: password) do |ssh| @site_construct.update!(:infos=>[]) if args.type == 'close_site' exec_ssh_command_by_sudo(ssh,"bash -l -c 'kill -s TERM `fuser #{@site_construct.path}/#{@site_construct.site_name}/tmp/unicorn.sock`'") update_infos("finish closing #{@site_construct.site_name}") @site_construct.update(:status =>"closed") elsif args.type == 'open_site' exec_ssh_command_by_sudo(ssh,"bash -l -c 'cd #{@site_construct.path}/#{@site_construct.site_name};kill -s TERM `fuser tmp/unicorn.sock`;bundle exec unicorn_rails -c config/unicorn.rb -D -E development'") update_infos("finish starting #{@site_construct.site_name}") @site_construct.update(:status =>"finish") else commands = YAML.load(args.commands) rescue args.commands if(!commands.blank? rescue true) if commands.class == Array commands.each do |command| update_infos("execing #{command}") exec_ssh_command_by_sudo(ssh,"bash -l -c '#{command}'") end else update_infos("execing #{commands}") exec_ssh_command_by_sudo(ssh,"bash -l -c '#{commands}'") end end end end #rescue =>e # @site_construct.update(:status =>"error",:infos=>@site_construct.infos.push("#{e}")) # end end def exec_ssh_command_by_sudo(session,command) output = session.exec!("echo '#{@password}' | sudo -S #{command}") # output = session.exec!("echo '#{@password}' | sudo -S -s #{command}") if output.include?("sudo:") && output.include?("command not found") output = session.exec!(command) end return output end def update_infos(info) puts info @site_construct.infos = @site_construct.infos.push(info) @site_construct.save! return @site_construct.infos end end