1/* Part of SWI-Prolog 2 3 Author: Jan Wielemaker 4 E-mail: J.Wielemaker@vu.nl 5 WWW: http://www.swi-prolog.org 6 Copyright (c) 2002-2024, University of Amsterdam 7 VU University Amsterdam 8 CWI, Amsterdam 9 SWI-Prolog Solutions b.v. 10 All rights reserved. 11 12 Redistribution and use in source and binary forms, with or without 13 modification, are permitted provided that the following conditions 14 are met: 15 16 1. Redistributions of source code must retain the above copyright 17 notice, this list of conditions and the following disclaimer. 18 19 2. Redistributions in binary form must reproduce the above copyright 20 notice, this list of conditions and the following disclaimer in 21 the documentation and/or other materials provided with the 22 distribution. 23 24 THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 25 "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 26 LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS 27 FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE 28 COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, 29 INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, 30 BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; 31 LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER 32 CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT 33 LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN 34 ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE 35 POSSIBILITY OF SUCH DAMAGE. 36*/ 37 38:- module(thread_httpd, 39 [ http_current_server/2, % ?:Goal, ?Port 40 http_server_property/2, % ?Port, ?Property 41 http_server/2, % :Goal, +Options 42 http_workers/2, % +Port, ?WorkerCount 43 http_add_worker/2, % +Port, +Options 44 http_current_worker/2, % ?Port, ?ThreadID 45 http_stop_server/2, % +Port, +Options 46 http_spawn/2, % :Goal, +Options 47 48 http_requeue/1, % +Request 49 http_close_connection/1, % +Request 50 http_enough_workers/3 % +Queue, +Why, +Peer 51 ]). 52:- use_module(library(debug)). 53:- use_module(library(error)). 54:- use_module(library(option)). 55:- use_module(library(socket)). 56:- use_module(library(thread_pool)). 57:- use_module(library(gensym)). 58:- use_module(http_wrapper). 59:- use_module(http_path). 60:- use_module(http_stream). 61:- use_module(library(settings)). 62 63:- autoload(library(uri), [uri_resolve/3]). 64 65:- setting(http:max_keep_alive_drain, nonneg, 65_536, 66 'Max bytes of an unread request body that are skipped to \c 67 keep the connection alive. Else the connection is closed.'). 68:- autoload(library(aggregate), [aggregate_all/3]). 69 70:- predicate_options(http_server/2, 2, 71 [ port(any), 72 unix_socket(atom), 73 entry_page(atom), 74 tcp_socket(any), 75 workers(positive_integer), 76 timeout(number), 77 keep_alive_timeout(number), 78 silent(boolean), 79 ssl(list(any)), % if http/http_ssl_plugin is loaded 80 pass_to(system:thread_create/3, 3) 81 ]). 82:- predicate_options(http_spawn/2, 2, 83 [ pool(atom), 84 pass_to(system:thread_create/3, 3), 85 pass_to(thread_pool:thread_create_in_pool/4, 4) 86 ]). 87:- predicate_options(http_add_worker/2, 2, 88 [ timeout(number), 89 keep_alive_timeout(number), 90 max_idle_time(number), 91 pass_to(system:thread_create/3, 3) 92 ]).
120:- meta_predicate 121 http_server(, ), 122 http_current_server(, ), 123 http_spawn(, ). 124 125:- dynamic 126 current_server/6, % Port, Goal, Thread, Queue, Scheme, StartTime 127 queue_worker/2, % Queue, ThreadID 128 queue_options/2. % Queue, Options 129 130:- multifile 131 make_socket_hook/3, 132 accept_hook/2, 133 close_hook/1, 134 open_client_hook/6, 135 discard_client_hook/1, 136 http:create_pool/1, 137 http:schedule_workers/1. 138 139:- meta_predicate 140 thread_repeat_wait().
AF_UNIX). See socket_create/2.http:max_keep_alive_drain (64Kb) bytes of the body are left.main thread.
If you need to control resource usage you may consider the
spawn option of http_handler/3 and library(thread_pool).true (default false), do not print an informational
message that the server was started.A typical initialization for an HTTP server that uses http_dispatch/1 to relay requests to predicates is:
:- use_module(library(http/thread_httpd)).
:- use_module(library(http/http_dispatch)).
start_server(Port) :-
http_server(http_dispatch, [port(Port)]).
Note that multiple servers can coexist in the same Prolog process. A notable application of this is to have both an HTTP and HTTPS server, where the HTTP server redirects to the HTTPS server for handling sensitive requests.
208http_server(Goal, M:Options0) :- 209 server_address(Address, Options0), 210 !, 211 make_socket(Address, M:Options0, Options), 212 create_workers(Options), 213 create_server(Goal, Address, Options), 214 ( option(silent(true), Options0) 215 -> true 216 ; print_message(informational, 217 httpd_started_server(Address, Options0)) 218 ). 219http_server(_Goal, _:Options0) :- 220 existence_error(server_address, Options0). 221 222server_address(Address, Options) :- 223 ( option(port(Port), Options) 224 -> Address = Port 225 ; option(unix_socket(Path), Options) 226 -> Address = unix_socket(Path) 227 ). 228 229address_port(_IFace:Port, Port) :- !. 230address_port(unix_socket(Path), Path) :- !. 231address_port(Address, Address) :- !. 232 233tcp_address(Port) :- 234 var(Port), 235 !. 236tcp_address(Port) :- 237 integer(Port), 238 !. 239tcp_address(_Iface:_Port). 240 241address_domain(localhost:_Port, Domain) => 242 Domain = inet. 243address_domain(Iface:_Port, Domain) => 244 ( catch(ip_name(IP, Iface), error(_,_), fail), 245 functor(IP, ip, 8) 246 -> Domain = inet6 247 ; Domain = inet 248 ). 249address_domain(_, Domain) => 250 Domain = inet.
queue(QueueId).
261make_socket(Address, M:Options0, Options) :- 262 tcp_address(Address), 263 make_socket_hook(Address, M:Options0, Options), 264 !. 265make_socket(Address, _:Options0, Options) :- 266 option(tcp_socket(_), Options0), 267 !, 268 make_addr_atom('httpd', Address, Queue), 269 Options = [ queue(Queue) 270 | Options0 271 ]. 272make_socket(Address, _:Options0, Options) :- 273 tcp_address(Address), 274 !, 275 address_domain(Address, Domain), 276 socket_create(Socket, [domain(Domain)]), 277 tcp_setopt(Socket, reuseaddr), 278 tcp_bind(Socket, Address), 279 tcp_listen(Socket, 64), 280 make_addr_atom('httpd', Address, Queue), 281 Options = [ queue(Queue), 282 tcp_socket(Socket) 283 | Options0 284 ]. 285:- if(current_predicate(unix_domain_socket/1)). 286make_socket(Address, _:Options0, Options) :- 287 Address = unix_socket(Path), 288 !, 289 unix_domain_socket(Socket), 290 tcp_bind(Socket, Path), 291 tcp_listen(Socket, 64), 292 make_addr_atom('httpd', Address, Queue), 293 Options = [ queue(Queue), 294 tcp_socket(Socket) 295 | Options0 296 ]. 297:- endif.
304make_addr_atom(Scheme, Address, Atom) :- 305 phrase(address_parts(Address), Parts), 306 atomic_list_concat([Scheme,@|Parts], Atom). 307 308address_parts(Var) --> 309 { var(Var), 310 !, 311 instantiation_error(Var) 312 }. 313address_parts(Atomic) --> 314 { atomic(Atomic) }, 315 !, 316 [Atomic]. 317address_parts(Host:Port) --> 318 !, 319 address_parts(Host), [:], address_parts(Port). 320address_parts(ip(A,B,C,D)) --> 321 !, 322 [ A, '.', B, '.', C, '.', D ]. 323address_parts(unix_socket(Path)) --> 324 [Path]. 325address_parts(Address) --> 326 { domain_error(http_server_address, Address) }.
334create_server(Goal, Address, Options) :- 335 get_time(StartTime), 336 option(queue(Queue), Options), 337 scheme(Scheme, Options), 338 autoload_https(Scheme), 339 address_port(Address, Port), 340 make_addr_atom(Scheme, Port, Alias), 341 thread_self(Initiator), 342 thread_create(accept_server(Goal, Initiator, Options), _, 343 [ alias(Alias), 344 class(service) 345 ]), 346 thread_get_message(server_started), 347 assert(current_server(Port, Goal, Alias, Queue, Scheme, StartTime)). 348 349scheme(Scheme, Options) :- 350 option(scheme(Scheme), Options), 351 !. 352scheme(Scheme, Options) :- 353 ( option(ssl(_), Options) 354 ; option(ssl_instance(_), Options) 355 ), 356 !, 357 Scheme = https. 358scheme(http, _). 359 360autoload_https(https) :- 361 \+ clause(accept_hook(_Goal, _Options), _), 362 exists_source(library(http/http_ssl_plugin)), 363 !, 364 use_module(library(http/http_ssl_plugin)). 365autoload_https(_).
373http_current_server(Goal, Port) :-
374 current_server(Port, Goal, _, _, _, _).http or https.390http_server_property(_:Port, Property) :- 391 integer(Port), 392 !, 393 server_property(Property, Port). 394http_server_property(Port, Property) :- 395 server_property(Property, Port). 396 397server_property(goal(Goal), Port) :- 398 current_server(Port, Goal, _, _, _, _). 399server_property(scheme(Scheme), Port) :- 400 current_server(Port, _, _, _, Scheme, _). 401server_property(start_time(Time), Port) :- 402 current_server(Port, _, _, _, _, Time).
415http_workers(Port, Workers) :- 416 integer(Workers), 417 !, 418 must_be(ground, Port), 419 ( current_server(Port, _, _, Queue, _, _) 420 -> resize_pool(Queue, Workers) 421 ; existence_error(http_server, Port) 422 ). 423http_workers(Port, Workers) :- 424 current_server(Port, _, _, Queue, _, _), 425 aggregate_all(count, queue_worker(Queue, _Worker), Workers).
438http_add_worker(Port, Options) :- 439 must_be(ground, Port), 440 current_server(Port, _, _, Queue, _, _), 441 !, 442 queue_options(Queue, QueueOptions), 443 merge_options(Options, QueueOptions, WorkerOptions), 444 atom_concat(Queue, '_', AliasBase), 445 create_workers(1, 1, Queue, AliasBase, WorkerOptions). 446http_add_worker(Port, _) :- 447 existence_error(http_server, Port).
457http_current_worker(Port, ThreadID) :-
458 current_server(Port, _, _, Queue, _, _),
459 queue_worker(Queue, ThreadID).467accept_server(Goal, Initiator, Options) :- 468 Ex = http_stop(Stopper), 469 catch(accept_server2(Goal, Initiator, Options), Ex, true), 470 thread_self(Thread), 471 debug(http(stop), '[~p]: accept server received ~p', [Thread, Ex]), 472 retract(current_server(_Port, _, Thread, Queue, _Scheme, _StartTime)), 473 close_pending_accepts(Queue), 474 close_server_socket(Options), 475 thread_send_message(Stopper, http_stopped). 476 477accept_server2(Goal, Initiator, Options) :- 478 thread_send_message(Initiator, server_started), 479 repeat, 480 ( catch(accept_server3(Goal, Options), E, true) 481 -> ( var(E) 482 -> fail 483 ; accept_rethrow_error(E) 484 -> throw(E) 485 ; print_message(error, E), 486 fail 487 ) 488 ; print_message(error, % internal error 489 goal_failed(accept_server3(Goal, Options))), 490 fail 491 ). 492 493accept_server3(Goal, Options) :- 494 accept_hook(Goal, Options), 495 !. 496accept_server3(Goal, Options) :- 497 memberchk(tcp_socket(Socket), Options), 498 memberchk(queue(Queue), Options), 499 debug(http(connection), 'Waiting for connection', []), 500 tcp_accept(Socket, Client, Peer), 501 sig_atomic(send_to_worker(Queue, Client, Goal, Peer)), 502 http_enough_workers(Queue, accept, Peer). 503 504send_to_worker(Queue, Client, Goal, Peer) :- 505 debug(http(connection), 'New HTTP connection from ~p', [Peer]), 506 thread_send_message(Queue, tcp_client(Client, Goal, Peer)). 507 508accept_rethrow_error(http_stop(_)).
514close_server_socket(Options) :- 515 close_hook(Options), 516 !. 517close_server_socket(Options) :- 518 memberchk(tcp_socket(Socket), Options), 519 !, 520 tcp_close_socket(Socket).
524close_pending_accepts(Queue) :- 525 ( thread_get_message(Queue, Msg, [timeout(0)]) 526 -> close_client(Msg), 527 close_pending_accepts(Queue) 528 ; true 529 ). 530 531close_client(tcp_client(Client, _Goal, _0Peer)) => 532 debug(http(stop), 'Closing connection from ~p during shut-down', [_0Peer]), 533 tcp_close_socket(Client). 534close_client(Msg) => 535 ( discard_client_hook(Msg) 536 -> true 537 ; print_message(warning, http_close_client(Msg)) 538 ).
548http_stop_server(Host:Port, Options) :- % e.g., localhost:4000 549 ground(Host), 550 !, 551 http_stop_server(Port, Options). 552http_stop_server(Port, _Options) :- 553 http_workers(Port, 0), % checks Port is ground 554 current_server(Port, _, Thread, Queue, _Scheme, _Start), 555 retractall(queue_options(Queue, _)), 556 debug(http(stop), 'Signalling HTTP server thread ~p to stop', [Thread]), 557 thread_self(Stopper), 558 thread_signal(Thread, throw(http_stop(Stopper))), 559 ( thread_get_message(Stopper, http_stopped, [timeout(0.1)]) 560 -> true 561 ; catch(connect(localhost:Port), _, true) 562 ), 563 thread_join(Thread, _0Status), 564 debug(http(stop), 'Joined HTTP server thread ~p (~p)', [Thread, _0Status]), 565 message_queue_destroy(Queue). 566 567connect(Address) :- 568 setup_call_cleanup( 569 tcp_socket(Socket), 570 tcp_connect(Socket, Address), 571 tcp_close_socket(Socket)).
579http_enough_workers(Queue, _Why, _Peer) :- 580 message_queue_property(Queue, waiting(_0)), 581 !, 582 debug(http(scheduler), '~D waiting for work; ok', [_0]). 583http_enough_workers(Queue, Why, Peer) :- 584 message_queue_property(Queue, size(Size)), 585 ( enough(Size, Why) 586 -> debug(http(scheduler), '~D in queue; ok', [Size]) 587 ; current_server(Port, _, _, Queue, _, _), 588 Data = _{ port:Port, 589 reason:Why, 590 peer:Peer, 591 waiting:Size, 592 queue:Queue 593 }, 594 debug(http(scheduler), 'Asking to reschedule: ~p', [Data]), 595 catch(http:schedule_workers(Data), 596 error(Formal, Context), 597 print_message(error, error(Formal, Context))) 598 -> true 599 ; true 600 ). 601 602enough(0, _). 603enough(1, keep_alive). % I will be ready myself
accept for a new connection or keep_alive if a
worker tries to reschedule itself.
Note that, when called with reason:accept, we are called in
the time critical main accept loop. An implementation of this
hook shall typically send the event to thread dedicated to
dynamic worker-pool management.
633 /******************************* 634 * WORKER QUEUE OPERATIONS * 635 *******************************/
642create_workers(Options) :- 643 option(workers(N), Options, 5), 644 option(queue(Queue), Options), 645 catch(message_queue_create(Queue), _, true), 646 atom_concat(Queue, '_', AliasBase), 647 create_workers(1, N, Queue, AliasBase, Options), 648 assert(queue_options(Queue, Options)). 649 650create_workers(I, N, _, _, _) :- 651 I > N, 652 !. 653create_workers(I, N, Queue, AliasBase, Options) :- 654 gensym(AliasBase, Alias), 655 thread_create(http_worker(Options), Id, 656 [ alias(Alias), 657 class(http) 658 | Options 659 ]), 660 assertz(queue_worker(Queue, Id)), 661 I2 is I + 1, 662 create_workers(I2, N, Queue, AliasBase, Options).
670resize_pool(Queue, Size) :-
671 findall(W, queue_worker(Queue, W), Workers),
672 length(Workers, Now),
673 ( Now < Size
674 -> queue_options(Queue, Options),
675 atom_concat(Queue, '_', AliasBase),
676 I0 is Now+1,
677 create_workers(I0, Size, Queue, AliasBase, Options)
678 ; Now == Size
679 -> true
680 ; Now > Size
681 -> Excess is Now - Size,
682 thread_self(Me),
683 forall(between(1, Excess, _), thread_send_message(Queue, quit(Me))),
684 forall(between(1, Excess, _), thread_get_message(quitted(_)))
685 ).
If the message quit(Sender) is read from the queue, the worker
stops.
696http_worker(Options) :- 697 debug(http(scheduler), 'New worker', []), 698 prolog_listen(this_thread_exit, done_worker), 699 option(queue(Queue), Options), 700 option(max_idle_time(MaxIdle), Options, infinite), 701 thread_repeat_wait(get_work(Queue, Message, MaxIdle)), 702 debug(http(worker), 'Waiting for a job ...', []), 703 debug(http(worker), 'Got job ~p', [Message]), 704 ( Message = quit(Sender) 705 -> !, 706 thread_self(Self), 707 thread_detach(Self), 708 ( Sender == idle 709 -> true 710 ; retract(queue_worker(Queue, Self)), 711 thread_send_message(Sender, quitted(Self)) 712 ) 713 ; open_client(Message, Queue, Goal, In, Out, 714 Options, ClientOptions), 715 ( catch(http_process(Goal, In, Out, ClientOptions), 716 Error, true) 717 -> true 718 ; Error = goal_failed(http_process/4) 719 ), 720 debug_reset_from_class, % Restore debug mode after user nodebug 721 ( var(Error) 722 -> fail 723 ; current_message_level(Error, Level), 724 print_message(Level, Error), 725 option(peer(Peer), ClientOptions), 726 close_connection(Peer, In, Out), 727 fail 728 ) 729 ). 730 731get_work(Queue, Message, infinite) :- 732 !, 733 thread_get_message(Queue, Message). 734get_work(Queue, Message, MaxIdle) :- 735 ( thread_get_message(Queue, Message, [timeout(MaxIdle)]) 736 -> true 737 ; Message = quit(idle) 738 ).
747open_client(requeue(In, Out, Goal, ClOpts), 748 _, Goal, In, Out, Opts, ClOpts) :- 749 !, 750 option(peer(Peer), ClOpts), 751 option(keep_alive_timeout(KeepAliveTMO), Opts, 2), 752 check_keep_alive_connection(In, KeepAliveTMO, Peer, In, Out). 753open_client(Message, Queue, Goal, In, Out, Opts, 754 [ pool(client(Queue, Goal, In, Out)), 755 timeout(Timeout) 756 | Options 757 ]) :- 758 catch(open_client(Message, Goal, In, Out, Options, Opts), 759 E, report_error(E)), 760 option(timeout(Timeout), Opts, 60), 761 ( debugging(http(connection)) 762 -> memberchk(peer(Peer), Options), 763 debug(http(connection), 'Opened connection from ~p', [Peer]) 764 ; true 765 ).
771open_client(Message, Goal, In, Out, ClientOptions, Options) :- 772 open_client_hook(Message, Goal, In, Out, ClientOptions, Options), 773 !. 774open_client(tcp_client(Socket, Goal, Peer), Goal, In, Out, 775 [ peer(Peer), 776 protocol(http) 777 ], _) :- 778 tcp_open_socket(Socket, In, Out). 779 780report_error(E) :- 781 print_message(error, E), 782 fail.
791check_keep_alive_connection(In, TMO, Peer, In, Out) :-
792 stream_property(In, timeout(Old)),
793 set_stream(In, timeout(TMO)),
794 debug(http(keep_alive), 'Waiting for keep-alive ...', []),
795 catch(peek_code(In, Code), E, true),
796 ( var(E), % no exception
797 Code \== -1 % no end-of-file
798 -> set_stream(In, timeout(Old)),
799 debug(http(keep_alive), '\tre-using keep-alive connection', [])
800 ; ( Code == -1
801 -> debug(http(keep_alive), '\tRemote closed keep-alive connection', [])
802 ; debug(http(keep_alive), '\tTimeout on keep-alive connection', [])
803 ),
804 close_connection(Peer, In, Out),
805 fail
806 ).815done_worker :- 816 thread_self(Self), 817 thread_detach(Self), 818 retract(queue_worker(Queue, Self)), 819 thread_property(Self, status(Status)), 820 !, 821 ( catch(recreate_worker(Status, Queue), _, fail) 822 -> print_message(informational, 823 httpd_restarted_worker(Self)) 824 ; done_status_message_level(Status, Level), 825 print_message(Level, 826 httpd_stopped_worker(Self, Status)) 827 ). 828done_worker :- % received quit(Sender) 829 thread_self(Self), 830 thread_property(Self, status(Status)), 831 done_status_message_level(Status, Level), 832 print_message(Level, 833 httpd_stopped_worker(Self, Status)). 834 835done_status_message_level(true, silent) :- !. 836done_status_message_level(exception('$aborted'), silent) :- !. 837done_status_message_level(exception(unwind(abort)), silent) :- !. 838done_status_message_level(exception(unwind(halt(_))), silent) :- !. 839done_status_message_level(_, informational).
The first clause deals with the possibility that we cannot write to
user_error. This is possible when Prolog is started as a service
using some service managers. Would be nice if we could write an
error, but where?
854recreate_worker(exception(error(io_error(write,user_error),_)), _Queue) :- 855 halt(2). 856recreate_worker(exception(Error), Queue) :- 857 recreate_on_error(Error), 858 queue_options(Queue, Options), 859 atom_concat(Queue, '_', AliasBase), 860 create_workers(1, 1, Queue, AliasBase, Options). 861 862recreate_on_error('$aborted'). 863recreate_on_error(unwind(abort)). 864recreate_on_error(time_limit_exceeded).
873:- multifile 874 message_level/2. 875 876message_level(error(io_error(read, _), _), silent). 877message_level(error(socket_error(epipe,_), _), silent). 878message_level(error(http_write_short(_Obj,_Written), _), silent). 879message_level(error(timeout_error(read, _), _), informational). 880message_level(keep_alive_timeout, silent). 881 882current_message_level(Term, Level) :- 883 ( message_level(Term, Level) 884 -> true 885 ; Level = error 886 ).
http:max_keep_alive_drain. Otherwise we fail, which closes the
connection: reading a large body that nobody needs would occupy
this worker for as long as the client keeps sending.897read_remaining_request(StartBody, Request) :- 898 memberchk(content_length(Len), Request), 899 !, 900 memberchk(pool(client(_Queue, _Goal, In, _Out)), Request), 901 byte_count(In, Here), 902 Left is StartBody+Len-Here, 903 read_incomplete(In, Left). 904read_remaining_request(_, _Request). 905 906read_incomplete(_, 0) :- 907 !. 908read_incomplete(In, Left) :- 909 setting(http:max_keep_alive_drain, Max), 910 Left =< Max, 911 catch(setup_call_cleanup( 912 open_null_stream(Null), 913 copy_stream_data(In, Null, Left), 914 close(Null)), 915 error(_,_), 916 fail).
923http_requeue(Header) :- 924 requeue_header(Header, ClientOptions), 925 memberchk(pool(client(Queue, Goal, In, Out)), ClientOptions), 926 option(peer(Peer), ClientOptions), 927 http_enough_workers(Queue, keep_alive, Peer), 928 thread_send_message(Queue, requeue(In, Out, Goal, ClientOptions)), 929 !. 930http_requeue(Header) :- 931 debug(http(error), 'Re-queue failed: ~p', [Header]), 932 fail. 933 934requeue_header([], []). 935requeue_header([H|T0], [H|T]) :- 936 requeue_keep(H), 937 !, 938 requeue_header(T0, T). 939requeue_header([_|T0], T) :- 940 requeue_header(T0, T). 941 942requeue_keep(pool(_)). 943requeue_keep(peer(_)). 944requeue_keep(protocol(_)).
951http_process(Goal, In, Out, Options) :- 952 debug(http(server), 'Running server goal ~p on ~p -> ~p', 953 [Goal, In, Out]), 954 option(timeout(TMO), Options, 60), 955 set_stream(In, timeout(TMO)), 956 set_stream(Out, timeout(TMO)), 957 http_wrapper(Goal, In, Out, Connection, 958 [ request(Request), 959 byte_count(StartBody) 960 | Options 961 ]), 962 next(Connection, StartBody, Request). 963 964next(Connection, StartBody, Request) :- 965 next_(Connection, StartBody, Request), !. 966next(Connection, StartBody, Request) :- 967 print_message(warning, goal_failed(next(Connection,StartBody,Request))). 968 969next_(switch_protocol(SwitchGoal, _SwitchOptions), _, Request) :- 970 !, 971 memberchk(pool(client(_Queue, _Goal, In, Out)), Request), 972 ( catch(call(SwitchGoal, In, Out), E, 973 ( print_message(error, E), 974 fail)) 975 -> true 976 ; http_close_connection(Request) 977 ). 978next_(spawned(ThreadId), _, _) :- 979 !, 980 debug(http(spawn), 'Handler spawned to thread ~w', [ThreadId]). 981next_(Connection, StartBody, Request) :- 982 downcase_atom(Connection, 'keep-alive'), 983 read_remaining_request(StartBody, Request), 984 http_requeue(Request), 985 !. 986next_(_, _, Request) :- 987 http_close_connection(Request).
994http_close_connection(Request) :-
995 memberchk(pool(client(_Queue, _Goal, In, Out)), Request),
996 memberchk(peer(Peer), Request),
997 close_connection(Peer, In, Out).
1004close_connection(Peer, In, Out) :-
1005 debug(http(connection), 'Closing connection from ~p', [Peer]),
1006 catch(close(In, [force(true)]), _, true),
1007 catch(close(Out, [force(true)]), _, true).If a pool does not exist, this predicate calls the multifile hook create_pool/1 to create it. If this predicate succeeds the operation is retried.
1025http_spawn(Goal, Options) :- 1026 select_option(pool(Pool), Options, ThreadOptions), 1027 !, 1028 current_output(CGI), 1029 Error = error(Formal, _), 1030 catch(thread_create_in_pool(Pool, 1031 wrap_spawned(CGI, Goal), Id, 1032 [ detached(true), 1033 class(http) 1034 | ThreadOptions 1035 ]), 1036 Error, 1037 true), 1038 ( var(Formal) 1039 -> http_spawned(Id) 1040 ; Formal = resource_error(threads_in_pool(_)) 1041 -> throw(http_reply(busy)) 1042 ; Formal = existence_error(thread_pool, Pool), 1043 create_pool(Pool) 1044 -> http_spawn(Goal, Options) 1045 ; throw(Error) 1046 ). 1047http_spawn(Goal, Options) :- 1048 current_output(CGI), 1049 thread_create(wrap_spawned(CGI, Goal), Id, 1050 [ detached(true), 1051 class(http) 1052 | Options 1053 ]), 1054 http_spawned(Id). 1055 1056wrap_spawned(CGI, Goal) :- 1057 set_output(CGI), 1058 cgi_property(CGI, request(Request)), 1059 memberchk(input(Input), Request), 1060 byte_count(Input, StartBody), 1061 http_wrap_spawned(Goal, Request, Connection), 1062 next(Connection, StartBody, Request).
1072create_pool(Pool) :- 1073 E = error(permission_error(create, thread_pool, Pool), _), 1074 catch(http:create_pool(Pool), E, true). 1075create_pool(Pool) :- 1076 print_message(informational, httpd(created_pool(Pool))), 1077 thread_pool_create(Pool, 10, []). 1078 1079 1080 /******************************* 1081 * WAIT POLICIES * 1082 *******************************/ 1083 1084:- meta_predicate 1085 thread_repeat_wait().
repeat, thread_idle(Goal), choosing whether to use a
long or short idle time based on the average firing rate.1092thread_repeat_wait(Goal) :- 1093 new_rate_mma(5, 1000, State), 1094 repeat, 1095 notrace, 1096 update_rate_mma(State, MMA), 1097 long(MMA, IsLong), 1098 ( IsLong == brief 1099 -> call(Goal) 1100 ; thread_idle(Goal, IsLong) 1101 ). 1102 1103long(MMA, brief) :- 1104 MMA < 0.05, 1105 !. 1106long(MMA, short) :- 1107 MMA < 1, 1108 !. 1109long(_, long).
1123new_rate_mma(N, Resolution, rstate(Base, 0, MaxI, Resolution, N, 0)) :- 1124 current_prolog_flag(max_tagged_integer, MaxI), 1125 get_time(Base). 1126 1127update_rate_mma(State, MMAr) :- 1128 State = rstate(Base, Last, MaxI, Resolution, N, MMA0), 1129 get_time(Now), 1130 Stamp is round((Now-Base)*Resolution), 1131 ( Stamp > MaxI 1132 -> nb_setarg(1, State, Now), 1133 nb_setarg(2, State, 0) 1134 ; true 1135 ), 1136 Diff is Stamp-Last, 1137 nb_setarg(2, State, Stamp), 1138 MMA is round(((N-1)*MMA0+Diff)/N), 1139 nb_setarg(6, State, MMA), 1140 MMAr is MMA/float(Resolution). 1141 1142 1143 /******************************* 1144 * MESSAGES * 1145 *******************************/ 1146 1147:- multifile 1148 prolog:message/3. 1149 1150prologmessage(httpd_started_server(Port, Options)) --> 1151 [ 'Started server at '-[] ], 1152 http_root(Port, Options). 1153prologmessage(httpd_stopped_worker(Self, Status)) --> 1154 [ 'Stopped worker ~p: ~p'-[Self, Status] ]. 1155prologmessage(httpd_restarted_worker(Self)) --> 1156 [ 'Replaced aborted worker ~p'-[Self] ]. 1157prologmessage(httpd(created_pool(Pool))) --> 1158 [ 'Created thread-pool ~p of size 10'-[Pool], nl, 1159 'Create this pool at startup-time or define the hook ', nl, 1160 'http:create_pool/1 to avoid this message and create a ', nl, 1161 'pool that fits the usage-profile.' 1162 ]. 1163 1164http_root(Address, Options) --> 1165 { landing_page(Address, URI, Options) }, 1166 [ url(URI) ]. 1167 1168landing_page(Host:Port, URI, Options) :- 1169 !, 1170 must_be(atom, Host), 1171 must_be(integer, Port), 1172 http_server_property(Port, scheme(Scheme)), 1173 ( default_port(Scheme, Port) 1174 -> format(atom(Base), '~w://~w', [Scheme, Host]) 1175 ; format(atom(Base), '~w://~w:~w', [Scheme, Host, Port]) 1176 ), 1177 entry_page(Base, URI, Options). 1178landing_page(unix_socket(Path), URI, _Options) :- 1179 !, 1180 format(string(URI), 'Unix domain socket "~w"', [Path]). 1181landing_page(Port, URI, Options) :- 1182 landing_page(localhost:Port, URI, Options). 1183 1184default_port(http, 80). 1185default_port(https, 443). 1186 1187entry_page(Base, URI, Options) :- 1188 option(entry_page(Entry), Options), 1189 !, 1190 uri_resolve(Entry, Base, URI). 1191entry_page(Base, URI, _) :- 1192 http_absolute_location(root(.), Entry, []), 1193 uri_resolve(Entry, Base, URI)
Threaded HTTP server
Most code doesn't need to use this directly; instead use library(http/http_server), which combines this library with the typical HTTP libraries that most servers need.
This library defines the HTTP server frontend of choice for SWI-Prolog. It is based on the multi-threading capabilities of SWI-Prolog and thus exploits multiple cores to serve requests concurrently. The server scales well and can cooperate with library(thread_pool) to control the number of concurrent requests of a given type. For example, it can be configured to handle 200 file download requests concurrently, 2 requests that potentially uses a lot of memory and 8 requests that use a lot of CPU resources.
On Unix systems, this library can be combined with library(http/http_unix_daemon) to realise a proper Unix service process that creates a web server at port 80, runs under a specific account, optionally detaches from the controlling terminal, etc.
Combined with library(http/http_ssl_plugin) from the SSL package, this library can be used to create an HTTPS server. See <plbase>/doc/packages/examples/ssl/https for an example server using a self-signed SSL certificate.