Module: Waxx::Server
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
-
#last_load_time ⇒ Object
readonly
Returns the value of attribute last_load_time.
-
#queue ⇒ Object
readonly
Returns the value of attribute queue.
Instance Method Summary collapse
- #create_thread(id) ⇒ Object
- #csrf?(x) ⇒ Boolean
- #default_cookies ⇒ Object
- #default_response_headers(req, ext) ⇒ Object
- #fatal_error(x, e) ⇒ Object
- #finish(x, io) ⇒ Object
- #parse_uri(r) ⇒ Object
- #process_request(io, db) ⇒ Object
- #reload ⇒ Object
- #reload_code ⇒ Object
-
#require_apps ⇒ Object
Require first level apps in the Waxx::Root/app directory.
- #restart ⇒ Object
- #run_app(x) ⇒ Object
- #serve_file(io, uri) ⇒ Object
- #set_cookies(x) ⇒ Object
- #setup_threads ⇒ Object
- #start(options = {}) ⇒ Object
- #stop(opts = {}) ⇒ Object
Instance Attribute Details
#last_load_time ⇒ Object (readonly)
Returns the value of attribute last_load_time.
16 17 18 |
# File 'lib/waxx/server.rb', line 16 def last_load_time @last_load_time end |
#queue ⇒ Object (readonly)
Returns the value of attribute queue.
17 18 19 |
# File 'lib/waxx/server.rb', line 17 def queue @queue end |
Instance Method Details
#create_thread(id) ⇒ Object
255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 |
# File 'lib/waxx/server.rb', line 255 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
41 42 43 44 45 46 47 48 49 |
# File 'lib/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 end false end |
#default_cookies ⇒ Object
34 35 36 37 38 39 |
# File 'lib/waxx/server.rb', line 34 def { "#{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
51 52 53 54 55 56 |
# File 'lib/waxx/server.rb', line 51 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
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 223 |
# File 'lib/waxx/server.rb', line 182 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\nHostname: #{`hostname`}\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
167 168 169 170 171 172 173 174 175 176 177 178 179 180 |
# File 'lib/waxx/server.rb', line 167 def finish(x, io) # Set last activity x.usr['la'] = Time.new.to_i (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 'lib/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
76 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 134 |
# File 'lib/waxx/server.rb', line 76 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::Http.(env['cookie']) begin usr = [Waxx['cookie']['user']['name']] ? JSON.parse(::App.decrypt([Waxx['cookie']['user']['name']][0])) : [Waxx['cookie']['user']['name']] rescue => e Waxx.debug e.to_s, 1 usr = [Waxx['cookie']['user']['name']] end begin ua = [Waxx['cookie']['agent']['name']] ? JSON.parse(::App.decrypt([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, , 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, , 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 usr['id'].nil? and (get/:qlk or post/:qlk) App::Usr.login_by_qlk(x, post/:qlk || get/:qlk) end 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 |
#reload ⇒ Object
237 238 239 |
# File 'lib/waxx/server.rb', line 237 def reload reload_code end |
#reload_code ⇒ Object
241 242 243 244 245 246 247 248 249 250 251 252 253 |
# File 'lib/waxx/server.rb', line 241 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_apps ⇒ Object
Require first level apps in the Waxx::Root/app directory
226 227 228 229 230 231 232 233 234 235 |
# File 'lib/waxx/server.rb', line 226 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 |
#restart ⇒ Object
290 291 292 293 294 |
# File 'lib/waxx/server.rb', line 290 def restart stop sleep(1) start end |
#run_app(x) ⇒ Object
136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 |
# File 'lib/waxx/server.rb', line 136 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.login_needed(x) end end end App.not_found(x) end |
#serve_file(io, uri) ⇒ Object
58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 |
# File 'lib/waxx/server.rb', line 58 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
152 153 154 155 156 157 158 159 160 161 162 163 164 165 |
# File 'lib/waxx/server.rb', line 152 def (x) return if x.usr/:no_cookies x.res.( name: Waxx['cookie']['user']['name'], value: App.encrypt(x.usr.to_json), secure: Waxx['cookie']['user']['secure'] ) x.res.( 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_threads ⇒ Object
274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 |
# File 'lib/waxx/server.rb', line 274 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
296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 |
# File 'lib/waxx/server.rb', line 296 def start(={}) @@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
314 315 316 317 318 319 320 321 322 323 324 |
# File 'lib/waxx/server.rb', line 314 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 |