Sha256: 55f7a9e08fceb73829bc6f04e460c9e9916ecbb8aba65014c4de7d4c0354ac6e

Contents?: true

Size: 1.86 KB

Versions: 2

Compression:

Stored size: 1.86 KB

Contents

require 'fileutils'
module Deploy
  def self.deploy(file)
    Deployer.new(file).deploy
  end
  class Deployer
    include FileUtils
    DEPLOYED_DIR = File.expand_path("~/.vendingmachine/control")
    PIDFILE = File.expand_path("~/.vendingmachine/pid")

    attr_reader :executable, :current_pid

    def initialize(executable)
      @executable = executable
      @log = ""
      $: << DEPLOYED_DIR unless $:.include?(DEPLOYED_DIR)
    end

    def run_log
      @log
    end

    def deploy(file_path)
      create_deployment_environment
      read_current_pid
      kill_running_process
      install_deployed_code(file_path)
      start_deployed_code
    end

    def kill
      read_current_pid
      kill_running_process
      clear_current_pid
    end

    def wait_for
      Process.wait(read_current_pid)
      clear_current_pid
      self
    end

    private
    def start_deployed_code
      save_current_pid(fork { system(executable) })
    end

    def install_deployed_code(file_path)
      rm_r Dir.glob(File.join(DEPLOYED_DIR, '*'))
      file_path = File.expand_path(file_path)
      cd(DEPLOYED_DIR) do
        sh "unzip #{file_path}"
      end
    end

    def kill_running_process
      begin
        if current_pid
          system "kill -9 #{current_pid}"
          Process.wait(current_pid)
        end
      rescue 
        # thats fine
      end
    end

    def save_current_pid(pid)
      @current_pid = pid
      File.open(PIDFILE, 'w+') { |f| f.write(@current_pid.to_s) }
    end

    def read_current_pid
      @current_pid = File.read(PIDFILE).to_i if File.exists?(PIDFILE)
    end

    def clear_current_pid
      @current_pid = nil
      rm PIDFILE if File.exists?(PIDFILE)
    end

    def create_deployment_environment
      mkdir_p DEPLOYED_DIR unless File.exists?(DEPLOYED_DIR)
    end

    def sh(command)
      system "#{command} >> /dev/null"
    end

  end
end

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
vmsim-1.0.1 lib/deploy/deployer.rb
vmsim-1.0.0 lib/deploy/deployer.rb