Class: CrapServer::Application

Inherits:
Object
  • Object
show all
Defined in:
lib/crap_server/application.rb

Overview

Example:

Crap::Application.run! do |data|

if data =~ /^GET/i
  write SomeDatabase.get('column')
elsif data =~/SET/
  SomeDatabase.set('column', data.split(' ')[1])
else
  write 'Error. Invalid action.'
end

end

Class Method Summary collapse

Class Method Details

.configure(&block) ⇒ Object



20
21
22
23
# File 'lib/crap_server/application.rb', line 20

def configure(&block)
  @config ||= CrapServer::Configure.new
  block.yield @config
end

.per_process(&block) ⇒ Object



25
26
27
# File 'lib/crap_server/application.rb', line 25

def per_process(&block)
  @per_process_block = block
end

.run!(&block) ⇒ Object

Main method. This setup all the connections and make the logic of the app



30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
# File 'lib/crap_server/application.rb', line 30

def run!(&block)
  begin
    logger.info 'Initializing Crap Server'
    # Bup the maximum opened file to the maximum allowed by the system
    Process.setrlimit(:NOFILE, Process.getrlimit(:NOFILE)[1])

    # Start IPv4 and IPv6 connection for the current port
    open_connections


    # Some log info to the user :)
    logger.info "Listening 0.0.0.0:#{config.port}"
    logger.debug "Maximum allowed waiting connections: #{Socket::SOMAXCONN}"
    logger.debug "Maximum number of allowed connections: #{Process.getrlimit(:NOFILE)[1]}" # Same as maximum of opened files
    logger.debug "Number of threads per core: #{config.pool_size}"
    logger.info 'Everything is ready. Have fun!'
    logger.info ''

    # Prefork and handle the connections in each process.
    forker = CrapServer::Forker.new([socket_ipv4, socket_ipv6])
    # Run loop. (basically, waiting until Ctrl+C)
    forker.run &block

  # If any kind of error happens, we MUST close the sockets
  rescue => e
    logger.error "Error: #{e.message}"
    e.backtrace.each do |line|
      logger.error line
    end
  # We don't need to close the socket, because are closed automatically by ruby

  rescue Interrupt
    # We don't need to close the socket, because are closed automatically by ruby
    # Leaved in black only to prevent error backtrace.
    # The process are killed by CrapServer::Forker
  end
end