Module: Waxx::Server

Extended by:
Server
Included in:
Server
Defined in:
waxx/server.rb

Overview

This is the core of waxx.

Process:
  start: A TCP server is setup listening on Waxx['server']['host'] on port Waxx['server']['port']
  setup_threads: The thread pool is created with dedicated database connection(s)
  loop: The requests are appended to the queue and the threads take one and:
  process_request: The request is parsed (query, string, multipart, etc). The "x" vairable is defined
  run_app: The proc/lambda is called with the x variable and any other optional variables
  finish: The response is sent to the client, background jobs are processed, the thread takes the next request

Instance Attribute Summary collapse

Instance Method Summary collapse

Instance Attribute Details

#last_load_timeObject (readonly)

Returns the value of attribute last_load_time



16
17
18
# File 'waxx/server.rb', line 16

def last_load_time
  @last_load_time
end

#queueObject (readonly)

Returns the value of attribute queue



17
18
19
# File 'waxx/server.rb', line 17

def queue
  @queue
end

Instance Method Details

#create_thread(id) ⇒ Object



254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
# File 'waxx/server.rb', line 254

def create_thread(id)
  Thread.new do
    Thread.current[:name]="waxx-#{Time.new.to_i}-#{id}"
    Thread.current[:status]="idle"
    Thread.current[:db] = Waxx['databases'].nil? ? {} : Waxx::Database.connections(Waxx['databases'])
    Thread.current[:last_used] = Time.new.to_i
    Waxx.debug "Create thread #{Thread.current[:name]}"
    loop do
      Waxx.debug "Thread loop start", 9
      begin
        Waxx::Server.process_request(@@queue.pop, Thread.current[:db])
      rescue => e
        Waxx.debug "Error: process_request loop: #{e} #{e.backtrace}", 1
      end
      Waxx.debug "Thread loop end", 9
    end
  end
end

#csrf?(x) ⇒ Boolean

Returns:

  • (Boolean)


41
42
43
44
45
46
47
48
49
50
# File 'waxx/server.rb', line 41

def csrf?(x)
  Waxx.debug "csrf?"
  if %w(PATCH POST PUT DELETE).include? x.req.meth
    if not Waxx::Csrf.ok?(x)
      true
    end
    puts "Cleared CSRF"
  end
  false
end

#default_cookiesObject



34
35
36
37
38
39
# File 'waxx/server.rb', line 34

def default_cookies
  {
    "#{Waxx['cookie']['user']['name']}" => {uk: Waxx.random_string(20), la: Time.now.to_i},
    "#{Waxx['cookie']['agent']['name']}" => {la: Time.now.to_i}
  }
end

#default_response_headers(req, ext) ⇒ Object



52
53
54
55
56
57
# File 'waxx/server.rb', line 52

def default_response_headers(req, ext)
  {
    "Content-Type" => (Waxx::Http.content_types()[ext.to_sym] || "text/html; charset=utf-8"),
    "App-Server" => "waxx/1.0"
  }
end

#fatal_error(x, e) ⇒ Object



181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
# File 'waxx/server.rb', line 181

def fatal_error(x, e)
  x.res.status = 503
  puts "FATAL ERROR: #{e}\n#{e.backtrace}"
  report = "APPLICATION ERROR\n=================\n\nUSR:\n\n#{x.usr.map{|n,v| "#{n}: #{v}"}.join("\n") rescue nil}\n\nERROR:\n\n#{e}\n#{e.backtrace.join("\n")}\n\nENV:\n\n#{x.req.env.map{|n,v| "#{n}: #{v}"}.join("\n") rescue nil}\n\nGET:\n\n#{x.req.get.map{|n,v| "#{n}: #{v}"}.join("\n") rescue nil}\n\nPOST:\n\n#{x.req.post.map{|n,v| "#{n}: #{v}"}.join("\n") rescue nil}\n\n"
  if Waxx['debug']['on_screen']
    x << "<pre>#{report.h}</pre>" 
  else
    App::Html.page(x, 
      title: "System Error", 
      content: "<h4><span class='glyphicon glyphicon-thumbs-down'></span> Sorry! Something went wrong on our end.</h4>
        <h4><span class='glyphicon glyphicon-thumbs-up'></span> The tech support team has been notified.</h4>
        <p>We will contact you if we need addition information. </p>
        <p>Sorry for the inconvenience.</p>"
    )
  end
  if Waxx['debug']['send_email'] and Waxx['debug']['email']
    begin
      to_email = Waxx['debug']['email']
      from_email = Waxx['site']['support_email']
      subject = "[Bug] #{Waxx['site']['name']} #{x.meth}:#{x.req.uri}"
      # Send email via DB
      App::Email.post(x,
        to_email: to_email,
        from_email: from_email,
        subject: subject,
        body_text: report
      )
    rescue => e2
      begin
        # Send email directly
        ::Mail.deliver do
          from     from_email
          to       to_email
          subject  subject
          body     report
        end
      rescue => e3
         puts "FATAL ERROR: Could not send bug report email: #{e2}\n#{e2.backtrace} AND #{e3}\n#{e3.backtrace}"
      end
    end
  end
end

#finish(x, io) ⇒ Object



166
167
168
169
170
171
172
173
174
175
176
177
178
179
# File 'waxx/server.rb', line 166

def finish(x, io)
  # Set last activity
  x.usr['la'] = Time.new.to_i
  set_cookies(x)
  Waxx.debug "Process time: #{(Time.new - x.req.start_time)*1000} ms."
  x.res.complete
  io.close
  x.jobs.each{|job| 
    job[0].call(*(job.slice(1, job.length)))
  }
  ::Thread.current[:status] = "idle"
  ::Thread.current[:last_used] = Time.new.to_i
  x # Return x for the console interfaces
end

#parse_uri(r) ⇒ Object



19
20
21
22
23
24
25
26
27
28
29
30
31
32
# File 'waxx/server.rb', line 19

def parse_uri(r)
  Waxx.debug "parse_uri: #{r}", 7
  meth, uri, ver = r.split(" ")
  path, params = uri.split("?", 2)
  parts = path.split('/')
  ext = parts.last.include?('.') ? parts.last.split('.').last : Waxx['default']['ext'] rescue Waxx['default']['ext']
  parts[parts.size - 1] = parts.last.to_s.sub(/.#{ext}$/,'') if parts.size > 0
  app = parts[1].to_s.empty? ? Waxx['default']['app'] : parts[1]
  act = parts[2].to_s.empty? ? (App[app.to_sym][:default] || Waxx['default']['act']) : parts[2] rescue Waxx['default']['act']
  args = parts.slice(3,99) || []
  oid = args.first.to_s.gsub(/[^0-9]/,"").to_i rescue 0
  get = Waxx::Http.query_string_to_hash(params).freeze
  [meth, uri, app, act, oid, args, ext, get]
end

#process_request(io, db) ⇒ Object



77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
# File 'waxx/server.rb', line 77

def process_request(io, db)
  begin
    Waxx.debug "process request", 4
    ::Thread.current[:status] = "working"
    start_time = Time.new
    r = io.gets
    #Waxx.debug r, 9
    meth, uri, app, act, oid, args, ext, get = parse_uri(r)
    #Waxx.debug([meth, uri, app, act, oid, args, ext, get].join(" "), 8)
    if meth == "GET" and Waxx['file'] and Waxx['file']['serve']
      #Waxx.debug "server_file"
      return if serve_file(io, uri)
    end
    #Waxx.debug "no-file"
    env, head = Waxx::Http.parse_head(io)
    Waxx.debug [Time.now.to_s, meth, uri].join(" "), 2
    #Waxx.debug head, 9
    cookie = Waxx::Http.parse_cookie(env['Cookie'])
    begin
      usr = cookie[Waxx['cookie']['user']['name']] ? JSON.parse(::App.decrypt(cookie[Waxx['cookie']['user']['name']][0])) : default_cookies[Waxx['cookie']['user']['name']] 
    rescue => e
      Waxx.debug e.to_s, 1
      usr = default_cookies[Waxx['cookie']['user']['name']]
    end
    begin
      ua = cookie[Waxx['cookie']['agent']['name']] ? JSON.parse(::App.decrypt(cookie[Waxx['cookie']['agent']['name']][0])) : {} 
    rescue => e
      Waxx.debug e.to_s, 1
      ua = {}
    end
    begin
      post, data = Waxx::Http.parse_data(env, meth, io, head)
    rescue => e
      post = nil
      req = Waxx::Req.new(env, data, meth, uri, get, post, cookie, start_time).freeze
      res = Waxx::Res.new(io, 400, default_response_headers(req, ext), [], [], [])
      jobs = []
      x = Waxx::X.new(req, res, usr, ua, db, meth.downcase.to_sym, app, act, oid, args, ext, jobs).freeze
      fatal_error(x, e)
      return finish(x, io)
    end
    req = Waxx::Req.new(env, data, meth, uri, get, post, cookie, start_time).freeze
    res = Waxx::Res.new(io, 200, default_response_headers(req, ext), [], [], [])
    jobs = []
    x = Waxx::X.new(req, res, usr, ua, db, meth.downcase.to_sym, app, act, oid, args, ext, jobs).freeze
    if csrf?(x)
      Waxx::App.csrf_failure(x)
      finish(x, io)
      return
    end
    run_app(x)
    finish(x, io)
  rescue => e
    fatal_error(x, e)
    finish(x, io)
  end
end

#reloadObject



236
237
238
# File 'waxx/server.rb', line 236

def reload
  reload_code
end

#reload_codeObject



240
241
242
243
244
245
246
247
248
249
250
251
252
# File 'waxx/server.rb', line 240

def reload_code
  require_apps
  $LOADED_FEATURES.each{|f| 
    if f =~ /^\// 
      if not f =~ /^\/usr\/local/
        if File.ctime(f) > @@last_load_time
          load(f)
        end
      end
    end
  }
  @@last_load_time = Time.new
end

#require_appsObject

Require first level apps in the Waxx::Root/app directory



225
226
227
228
229
230
231
232
233
234
# File 'waxx/server.rb', line 225

def require_apps
  Dir["#{Waxx["opts"][:base]}/app/*"].each{|f|
    next if f =~ /\/app\.rb$/ # Don't reinclude app.rb
    require f if f =~ /\.rb$/ # Load files in the app directory 
    if File.directory? f # Load top-level apps
      name = f.split("/").last
      require "#{f}/#{name}" if File.exist? "#{f}/#{name}.rb"
    end
  }
end

#restartObject



289
290
291
292
293
# File 'waxx/server.rb', line 289

def restart
  stop
  sleep(1)
  start
end

#run_app(x) ⇒ Object



135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
# File 'waxx/server.rb', line 135

def run_app(x)
  Waxx.debug "run_request"
  app = x.app.to_sym
  if App[app] 
    act = App[app][x.act.to_sym] ? x.act.to_sym : App[app][x.act] ? x.act : :not_found
    if App[app][act]
      if App.access?(x, acl:App[app][act][:acl])
        return App.run(x, app, act, x.meth.to_sym, x.args)
      else
        return App.(x)
      end
    end
  end
  App.not_found(x)
end

#serve_file(io, uri) ⇒ Object



59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
# File 'waxx/server.rb', line 59

def serve_file(io, uri)
  return false if Waxx['file'].nil?
  file = "#{Waxx/:opts/:base}/#{Waxx/:file/:path}#{uri.gsub("..","").split("?").first}"
  file = file + "/index.html" if File.directory?(file)
  return false unless File.exist? file
  ext = file.split(".").last
  io.print([
    "HTTP/1.1 200 OK",
    "Content-Type: #{(Waxx::Http.content_types/ext || 'octet-stream')}",
    "Content-Length: #{File.size(file)}",
    "",
    File.open(file,"rb") {|fh| fh.read}
  ].join("\r\n"))
  io.close
  ::Thread.current[:status] = "idle"
  true 
end

#set_cookies(x) ⇒ Object



151
152
153
154
155
156
157
158
159
160
161
162
163
164
# File 'waxx/server.rb', line 151

def set_cookies(x)
  return if x.usr/:no_cookies
  x.res.cookie( 
    name: Waxx['cookie']['user']['name'], 
    value: App.encrypt(x.usr.to_json), 
    secure: Waxx['cookie']['user']['secure']
  )
  x.res.cookie( 
    name: Waxx['cookie']['agent']['name'], 
    value: App.encrypt(x.ua.to_json), 
    expires: Time.now + (Waxx['cookie']['agent']['expires_years'].to_i * 31536000), 
    secure: Waxx['cookie']['agent']['secure']
  )
end

#setup_threadsObject



273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
# File 'waxx/server.rb', line 273

def setup_threads
  Waxx.debug "setup_threads"
  Thread.current[:name]="main"
  @@queue = Queue.new
  thread_count = Waxx['server']['min_threads'] || Waxx['server']['threads'] || 4
  1.upto(thread_count).each do |i|
    begin
      create_thread(i)
    rescue => e
      Waxx.debug "Error creating thread #{i}: #{e}", 1
    end
  end
  Waxx.debug "Created #{thread_count} threads", 7
  thread_count
end

#start(options = {}) ⇒ Object



295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
# File 'waxx/server.rb', line 295

def start(options={})
  @@last_load_time = Time.new
  Waxx.debug "start #{$$}"
  thread_count = setup_threads
  server = TCPServer.new(Waxx['server']['host'], Waxx['server']['port'])
  puts "Listening on #{server.addr} with #{thread_count} threads (max_threads: #{Waxx['server']['max_threads'] || Waxx['server']['threads']})"
  while s = server.accept
    Waxx.debug "server.accept", 7
    reload_code if Waxx['debug']['auto_reload_code']
    @@queue << s
    Waxx.debug "q.size: #{@@queue.size}", 7
    Waxx.debug "q.waiting:  #{@@queue.num_waiting}", 7
    # Check threads
    Waxx::Supervisor.check
  end
  Waxx.debug "end start", 9
end

#stop(opts = {}) ⇒ Object



313
314
315
316
317
318
319
320
321
322
323
# File 'waxx/server.rb', line 313

def stop(opts={})
  Waxx.debug "stop #{$$}"
  puts "Stopping #{Thread.list.size - 1} worker threads..."
  Thread.list.each{|t| 
    next if t[:name] == "main"
    puts "Killing #{t[:name]} with status #{t[:status]}"
    t[:db].close
    t.exit
  }
  puts "Done"
end