-
Notifications
You must be signed in to change notification settings - Fork 14
/
Copy pathpengines.pl
3279 lines (2814 loc) · 110 KB
/
pengines.pl
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
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
67
68
69
70
71
72
73
74
75
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
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
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
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
:- encoding(utf8).
/* Part of SWI-Prolog
Author: Torbjörn Lager and Jan Wielemaker
E-mail: [email protected]
WWW: http://www.swi-prolog.org
Copyright (C): 2014-2024, Torbjörn Lager,
VU University Amsterdam
SWI-Prolog Solutions b.v.
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
1. Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in
the documentation and/or other materials provided with the
distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/
:- module(pengines,
[ pengine_create/1, % +Options
pengine_ask/3, % +Pengine, :Query, +Options
pengine_next/2, % +Pengine. +Options
pengine_stop/2, % +Pengine. +Options
pengine_event/2, % -Event, +Options
pengine_input/2, % +Prompt, -Term
pengine_output/1, % +Term
pengine_respond/3, % +Pengine, +Input, +Options
pengine_debug/2, % +Format, +Args
pengine_self/1, % -Pengine
pengine_pull_response/2, % +Pengine, +Options
pengine_destroy/1, % +Pengine
pengine_destroy/2, % +Pengine, +Options
pengine_abort/1, % +Pengine
pengine_application/1, % +Application
current_pengine_application/1, % ?Application
pengine_property/2, % ?Pengine, ?Property
pengine_user/1, % -User
pengine_event_loop/2, % :Closure, +Options
pengine_rpc/2, % +Server, :Goal
pengine_rpc/3 % +Server, :Goal, +Options
]).
/** <module> Pengines: Web Logic Programming Made Easy
The library(pengines) provides an infrastructure for creating Prolog
engines in a (remote) pengine server and accessing these engines either
from Prolog or JavaScript.
@author Torbjörn Lager and Jan Wielemaker
*/
:- autoload(library(aggregate),[aggregate_all/3]).
:- autoload(library(apply),[maplist/2,partition/4,exclude/3,maplist/3]).
:- autoload(library(broadcast),[broadcast/1]).
:- autoload(library(charsio),[open_chars_stream/2]).
:- use_module(library(debug),[debug/1,debugging/1,debug/3,assertion/1]).
:- autoload(library(error),
[ must_be/2,
existence_error/2,
permission_error/3,
domain_error/2
]).
:- autoload(library(filesex),[directory_file_path/3]).
:- autoload(library(listing),[listing/1]).
:- autoload(library(lists),[member/2,flatten/2,select/3,append/3]).
:- autoload(library(modules),[in_temporary_module/3]).
:- autoload(library(occurs),[sub_term/2]).
:- autoload(library(option),
[select_option/3,option/2,option/3,select_option/4]).
:- autoload(library(prolog_stack),[print_prolog_backtrace/2]).
:- autoload(library(sandbox),[safe_goal/1]).
:- autoload(library(statistics),[thread_statistics/2]).
:- autoload(library(term_to_json),[term_to_json/2]).
:- autoload(library(thread_pool),
[thread_pool_create/3,thread_create_in_pool/4]).
:- autoload(library(time),[alarm/4,call_with_time_limit/2]).
:- autoload(library(uri),
[ uri_components/2,
uri_query_components/2,
uri_data/3,
uri_data/4,
uri_encoded/3
]).
:- autoload(library(http/http_client),[http_read_data/3]).
:- autoload(library(http/http_cors),[cors_enable/0,cors_enable/2]).
:- autoload(library(http/http_dispatch),
[http_handler/3,http_404/2,http_reply_file/3]).
:- autoload(library(http/http_open),[http_open/3]).
:- autoload(library(http/http_parameters),[http_parameters/2]).
:- autoload(library(http/http_stream),[is_cgi_stream/1]).
:- autoload(library(http/http_wrapper),[http_peer/2]).
:- use_module(library(settings),[setting/2,setting/4]).
:- use_module(library(http/http_json),
[http_read_json_dict/2,reply_json_dict/1]).
:- if(exists_source(library(uuid))).
:- autoload(library(uuid), [uuid/2]).
:- endif.
:- meta_predicate
pengine_create(:),
pengine_rpc(+, +, :),
pengine_event_loop(1, +).
:- multifile
write_result/3, % +Format, +Event, +Dict
event_to_json/3, % +Event, -JSON, +Format
prepare_module/3, % +Module, +Application, +Options
prepare_goal/3, % +GoalIn, -GoalOut, +Options
authentication_hook/3, % +Request, +Application, -User
not_sandboxed/2, % +User, +App
pengine_flush_output_hook/0.
:- predicate_options(pengine_create/1, 1,
[ id(-atom),
alias(atom),
application(atom),
destroy(boolean),
server(atom),
ask(compound),
template(compound),
chunk(integer;oneof([false])),
bindings(list),
src_list(list),
src_text(any), % text
src_url(atom),
src_predicates(list)
]).
:- predicate_options(pengine_ask/3, 3,
[ template(any),
chunk(integer;oneof([false])),
bindings(list)
]).
:- predicate_options(pengine_next/2, 2,
[ chunk(integer),
pass_to(pengine_send/3, 3)
]).
:- predicate_options(pengine_stop/2, 2,
[ pass_to(pengine_send/3, 3)
]).
:- predicate_options(pengine_respond/3, 2,
[ pass_to(pengine_send/3, 3)
]).
:- predicate_options(pengine_rpc/3, 3,
[ chunk(integer;oneof([false])),
pass_to(pengine_create/1, 1)
]).
:- predicate_options(pengine_send/3, 3,
[ delay(number)
]).
:- predicate_options(pengine_event/2, 2,
[ listen(atom),
pass_to(system:thread_get_message/3, 3)
]).
:- predicate_options(pengine_pull_response/2, 2,
[ pass_to(http_open/3, 3)
]).
:- predicate_options(pengine_event_loop/2, 2,
[]). % not yet implemented
% :- debug(pengine(transition)).
:- debug(pengine(debug)). % handle pengine_debug in pengine_rpc/3.
goal_expansion(random_delay, Expanded) :-
( debugging(pengine(delay))
-> Expanded = do_random_delay
; Expanded = true
).
do_random_delay :-
Delay is random(20)/1000,
sleep(Delay).
:- meta_predicate % internal meta predicates
solve(+, ?, 0, +),
findnsols_no_empty(+, ?, 0, -),
pengine_event_loop(+, 1, +).
/** pengine_create(:Options) is det.
Creates a new pengine. Valid options are:
* id(-ID)
ID gets instantiated to the id of the created pengine. ID is
atomic.
* alias(+Name)
The pengine is named Name (an atom). A slave pengine (child) can
subsequently be referred to by this name.
* application(+Application)
Application in which the pengine runs. See pengine_application/1.
* server(+URL)
The pengine will run in (and in the Prolog context of) the pengine
server located at URL.
* src_list(+List_of_clauses)
Inject a list of Prolog clauses into the pengine.
* src_text(+Atom_or_string)
Inject the clauses specified by a source text into the pengine.
* src_url(+URL)
Inject the clauses specified in the file located at URL into the
pengine.
* src_predicates(+List)
Send the local predicates denoted by List to the remote pengine.
List is a list of predicate indicators.
Remaining options are passed to http_open/3 (meaningful only for
non-local pengines) and thread_create/3. Note that for thread_create/3
only options changing the stack-sizes can be used. In particular, do not
pass the detached or alias options..
Successful creation of a pengine will return an _event term_ of the
following form:
* create(ID, Term)
ID is the id of the pengine that was created.
Term is not used at the moment.
An error will be returned if the pengine could not be created:
* error(ID, Term)
ID is invalid, since no pengine was created.
Term is the exception's error term.
*/
pengine_create(M:Options0) :-
translate_local_sources(Options0, Options, M),
( select_option(server(BaseURL), Options, RestOptions)
-> remote_pengine_create(BaseURL, RestOptions)
; local_pengine_create(Options)
).
%! translate_local_sources(+OptionsIn, -Options, +Module) is det.
%
% Translate the `src_predicates` and `src_list` options into
% `src_text`. We need to do that anyway for remote pengines. For
% local pengines, we could avoid this step, but there is very
% little point in transferring source to a local pengine anyway as
% local pengines can access any Prolog predicate that you make
% visible to the application.
%
% Multiple sources are concatenated to end up with a single
% src_text option.
translate_local_sources(OptionsIn, Options, Module) :-
translate_local_sources(OptionsIn, Sources, Options2, Module),
( Sources == []
-> Options = Options2
; Sources = [Source]
-> Options = [src_text(Source)|Options2]
; atomics_to_string(Sources, Source)
-> Options = [src_text(Source)|Options2]
).
translate_local_sources([], [], [], _).
translate_local_sources([H0|T], [S0|S], Options, M) :-
nonvar(H0),
translate_local_source(H0, S0, M),
!,
translate_local_sources(T, S, Options, M).
translate_local_sources([H|T0], S, [H|T], M) :-
translate_local_sources(T0, S, T, M).
translate_local_source(src_predicates(PIs), Source, M) :-
must_be(list, PIs),
with_output_to(string(Source),
maplist(list_in_module(M), PIs)).
translate_local_source(src_list(Terms), Source, _) :-
must_be(list, Terms),
with_output_to(string(Source),
forall(member(Term, Terms),
format('~k .~n', [Term]))).
translate_local_source(src_text(Source), Source, _).
list_in_module(M, PI) :-
listing(M:PI).
/** pengine_send(+NameOrID, +Term) is det
Same as pengine_send(NameOrID, Term, []).
*/
pengine_send(Target, Event) :-
pengine_send(Target, Event, []).
/** pengine_send(+NameOrID, +Term, +Options) is det
Succeeds immediately and places Term in the queue of the pengine
NameOrID. Options is a list of options:
* delay(+Time)
The actual sending is delayed by Time seconds. Time is an integer
or a float.
Any remaining options are passed to http_open/3.
*/
pengine_send(Target, Event, Options) :-
must_be(atom, Target),
pengine_send2(Target, Event, Options).
pengine_send2(self, Event, Options) :-
!,
thread_self(Queue),
delay_message(queue(Queue), Event, Options).
pengine_send2(Name, Event, Options) :-
child(Name, Target),
!,
delay_message(pengine(Target), Event, Options).
pengine_send2(Target, Event, Options) :-
delay_message(pengine(Target), Event, Options).
delay_message(Target, Event, Options) :-
option(delay(Delay), Options),
!,
alarm(Delay,
send_message(Target, Event, Options),
_AlarmID,
[remove(true)]).
delay_message(Target, Event, Options) :-
random_delay,
send_message(Target, Event, Options).
send_message(queue(Queue), Event, _) :-
thread_send_message(Queue, pengine_request(Event)).
send_message(pengine(Pengine), Event, Options) :-
( pengine_remote(Pengine, Server)
-> remote_pengine_send(Server, Pengine, Event, Options)
; pengine_thread(Pengine, Thread)
-> thread_send_message(Thread, pengine_request(Event))
; existence_error(pengine, Pengine)
).
%! pengine_request(-Request) is det.
%
% To be used by a pengine to wait for the next request. Such messages
% are placed in the queue by pengine_send/2. Keeps the thread in
% normal state if an event arrives within a second. Otherwise it waits
% for the `idle_limit` setting while using thread_idle/2 to minimis
% resources.
pengine_request(Request) :-
thread_self(Me),
thread_get_message(Me, pengine_request(Request), [timeout(1)]),
!.
pengine_request(Request) :-
pengine_self(Self),
get_pengine_application(Self, Application),
setting(Application:idle_limit, IdleLimit0),
IdleLimit is IdleLimit0-1,
thread_self(Me),
( thread_idle(thread_get_message(Me, pengine_request(Request),
[timeout(IdleLimit)]),
long)
-> true
; Request = destroy
).
%! pengine_reply(+Event) is det.
%! pengine_reply(+Queue, +Event) is det.
%
% Reply Event to the parent of the current Pengine or the given
% Queue. Such events are read by the other side with
% pengine_event/1.
%
% If the message cannot be sent within the `idle_limit` setting of
% the pengine, abort the pengine.
pengine_reply(Event) :-
pengine_parent(Queue),
pengine_reply(Queue, Event).
pengine_reply(_Queue, _Event0) :-
nb_current(pengine_idle_limit_exceeded, true),
!.
pengine_reply(Queue, Event0) :-
arg(1, Event0, ID),
wrap_first_answer(ID, Event0, Event),
random_delay,
debug(pengine(event), 'Reply to ~p: ~p', [Queue, Event]),
( pengine_self(ID),
\+ pengine_detached(ID, _)
-> get_pengine_application(ID, Application),
setting(Application:idle_limit, IdleLimit),
debug(pengine(reply), 'Sending ~p, timeout: ~q', [Event, IdleLimit]),
( thread_send_message(Queue, pengine_event(ID, Event),
[ timeout(IdleLimit)
])
-> true
; thread_self(Me),
debug(pengine(reply), 'pengine_reply: timeout for ~q (thread ~q)',
[ID, Me]),
nb_setval(pengine_idle_limit_exceeded, true),
thread_detach(Me),
abort
)
; thread_send_message(Queue, pengine_event(ID, Event))
).
wrap_first_answer(ID, Event0, CreateEvent) :-
wrap_first_answer_in_create_event(CreateEvent, [answer(Event0)]),
arg(1, CreateEvent, ID),
!,
retract(wrap_first_answer_in_create_event(CreateEvent, [answer(Event0)])).
wrap_first_answer(_ID, Event, Event).
empty_queue :-
pengine_parent(Queue),
empty_queue(Queue, 0, Discarded),
debug(pengine(abort), 'Abort: discarded ~D messages', [Discarded]).
empty_queue(Queue, C0, C) :-
thread_get_message(Queue, _Term, [timeout(0)]),
!,
C1 is C0+1,
empty_queue(Queue, C1, C).
empty_queue(_, C, C).
/** pengine_ask(+NameOrID, @Query, +Options) is det
Asks pengine NameOrID a query Query.
Options is a list of options:
* template(+Template)
Template is a variable (or a term containing variables) shared
with the query. By default, the template is identical to the
query.
* chunk(+IntegerOrFalse)
Retrieve solutions in chunks of Integer rather than one by one. 1
means no chunking (default). Other integers indicate the maximum
number of solutions to retrieve in one chunk. If `false`, the
Pengine goal is not executed using findall/3 and friends and
we do not backtrack immediately over the goal. As a result,
changes to backtrackable global state are retained. This is
similar that using set_prolog_flag(toplevel_mode, recursive).
* bindings(+Bindings)
Sets the global variable '$variable_names' to a list of
`Name = Var` terms, providing access to the actual variable
names.
Any remaining options are passed to pengine_send/3.
Note that the predicate pengine_ask/3 is deterministic, even for queries
that have more than one solution. Also, the variables in Query will not
be bound. Instead, results will be returned in the form of _event
terms_.
* success(ID, Terms, Projection, Time, More)
ID is the id of the pengine that succeeded in solving the query.
Terms is a list holding instantiations of `Template`. Projection
is a list of variable names that should be displayed. Time is
the CPU time used to produce the results and finally, More
is either `true` or `false`, indicating whether we can expect the
pengine to be able to return more solutions or not, would we call
pengine_next/2.
* failure(ID)
ID is the id of the pengine that failed for lack of a solutions.
* error(ID, Term)
ID is the id of the pengine throwing the exception.
Term is the exception's error term.
* output(ID, Term)
ID is the id of a pengine running the query that called
pengine_output/1. Term is the term that was passed in the first
argument of pengine_output/1 when it was called.
* prompt(ID, Term)
ID is the id of the pengine that called pengine_input/2 and Term is
the prompt.
Defined in terms of pengine_send/3, like so:
==
pengine_ask(ID, Query, Options) :-
partition(pengine_ask_option, Options, AskOptions, SendOptions),
pengine_send(ID, ask(Query, AskOptions), SendOptions).
==
*/
pengine_ask(ID, Query, Options) :-
partition(pengine_ask_option, Options, AskOptions, SendOptions),
pengine_send(ID, ask(Query, AskOptions), SendOptions).
pengine_ask_option(template(_)).
pengine_ask_option(chunk(_)).
pengine_ask_option(bindings(_)).
pengine_ask_option(breakpoints(_)).
/** pengine_next(+NameOrID, +Options) is det
Asks pengine NameOrID for the next solution to a query started by
pengine_ask/3. Defined options are:
* chunk(+Count)
Modify the chunk-size to Count before asking the next set of
solutions. This may not be used if the goal was started with
chunk(false).
Remaining options are passed to pengine_send/3. The result of
re-executing the current goal is returned to the caller's message queue
in the form of _event terms_.
* success(ID, Terms, Projection, Time, More)
See pengine_ask/3.
* failure(ID)
ID is the id of the pengine that failed for lack of more solutions.
* error(ID, Term)
ID is the id of the pengine throwing the exception.
Term is the exception's error term.
* output(ID, Term)
ID is the id of a pengine running the query that called
pengine_output/1. Term is the term that was passed in the first
argument of pengine_output/1 when it was called.
* prompt(ID, Term)
ID is the id of the pengine that called pengine_input/2 and Term
is the prompt.
Defined in terms of pengine_send/3, as follows:
==
pengine_next(ID, Options) :-
pengine_send(ID, next, Options).
==
*/
pengine_next(ID, Options) :-
select_option(chunk(Count), Options, Options1),
!,
pengine_send(ID, next(Count), Options1).
pengine_next(ID, Options) :-
pengine_send(ID, next, Options).
/** pengine_stop(+NameOrID, +Options) is det
Tells pengine NameOrID to stop looking for more solutions to a query
started by pengine_ask/3. Options are passed to pengine_send/3.
Defined in terms of pengine_send/3, like so:
==
pengine_stop(ID, Options) :-
pengine_send(ID, stop, Options).
==
*/
pengine_stop(ID, Options) :- pengine_send(ID, stop, Options).
/** pengine_abort(+NameOrID) is det
Aborts the running query. The pengine goes back to state `2', waiting
for new queries.
@see pengine_destroy/1.
*/
pengine_abort(Name) :-
( child(Name, Pengine)
-> true
; Pengine = Name
),
( pengine_remote(Pengine, Server)
-> remote_pengine_abort(Server, Pengine, [])
; pengine_thread(Pengine, Thread),
debug(pengine(abort), 'Signalling thread ~p', [Thread]),
catch(thread_signal(Thread, throw(abort_query)), _, true)
).
/** pengine_destroy(+NameOrID) is det.
pengine_destroy(+NameOrID, +Options) is det.
Destroys the pengine NameOrID. With the option force(true), the pengine
is killed using abort/0 and pengine_destroy/2 succeeds.
*/
pengine_destroy(ID) :-
pengine_destroy(ID, []).
pengine_destroy(Name, Options) :-
( child(Name, ID)
-> true
; ID = Name
),
option(force(true), Options),
!,
( pengine_thread(ID, Thread)
-> catch(thread_signal(Thread, abort),
error(existence_error(thread, _), _), true)
; true
).
pengine_destroy(ID, Options) :-
catch(pengine_send(ID, destroy, Options),
error(existence_error(pengine, ID), _),
retractall(child(_,ID))).
/*================= pengines administration =======================
*/
%! current_pengine(?Id, ?Parent, ?Location)
%
% Dynamic predicate that registers our known pengines. Id is
% an atomic unique datatype. Parent is the id of our parent
% pengine. Location is one of
%
% - thread(ThreadId)
% - remote(URL)
:- dynamic
current_pengine/6, % Id, ParentId, Thread, URL, App, Destroy
pengine_queue/4, % Id, Queue, TimeOut, Time
output_queue/3, % Id, Queue, Time
pengine_user/2, % Id, User
pengine_data/2, % Id, Data
pengine_detached/2. % Id, Data
:- volatile
current_pengine/6,
pengine_queue/4,
output_queue/3,
pengine_user/2,
pengine_data/2,
pengine_detached/2.
:- thread_local
child/2. % ?Name, ?Child
%! pengine_register_local(+Id, +Thread, +Queue, +URL, +App, +Destroy) is det.
%! pengine_register_remote(+Id, +URL, +Queue, +App, +Destroy) is det.
%! pengine_unregister(+Id) is det.
pengine_register_local(Id, Thread, Queue, URL, Application, Destroy) :-
asserta(current_pengine(Id, Queue, Thread, URL, Application, Destroy)).
pengine_register_remote(Id, URL, Application, Destroy) :-
thread_self(Queue),
asserta(current_pengine(Id, Queue, 0, URL, Application, Destroy)).
%! pengine_unregister(+Id)
%
% Called by the pengine thread destruction. If we are a remote
% pengine thread, our URL equals =http= and the queue is the
% message queue used to send events to the HTTP workers.
pengine_unregister(Id) :-
thread_self(Me),
( current_pengine(Id, Queue, Me, http, _, _)
-> with_mutex(pengine, sync_destroy_queue_from_pengine(Id, Queue))
; true
),
retractall(current_pengine(Id, _, Me, _, _, _)),
retractall(pengine_user(Id, _)),
retractall(pengine_data(Id, _)).
pengine_unregister_remote(Id) :-
retractall(current_pengine(Id, _Parent, 0, _, _, _)).
%! pengine_self(-Id) is det.
%
% True if the current thread is a pengine with Id.
pengine_self(Id) :-
thread_self(Thread),
current_pengine(Id, _Parent, Thread, _URL, _Application, _Destroy).
pengine_parent(Parent) :-
nb_getval(pengine_parent, Parent).
pengine_thread(Pengine, Thread) :-
current_pengine(Pengine, _Parent, Thread, _URL, _Application, _Destroy),
Thread \== 0,
!.
pengine_remote(Pengine, URL) :-
current_pengine(Pengine, _Parent, 0, URL, _Application, _Destroy).
get_pengine_application(Pengine, Application) :-
current_pengine(Pengine, _Parent, _, _URL, Application, _Destroy),
!.
get_pengine_module(Pengine, Pengine).
:- if(current_predicate(uuid/2)).
pengine_uuid(Id) :-
uuid(Id, [version(4)]). % Version 4 is random.
:- else.
pengine_uuid(Id) :-
( current_prolog_flag(max_integer, Max1)
-> Max is Max1-1
; Max is 1<<128
),
random_between(0, Max, Num),
atom_number(Id, Num).
:- endif.
%! protect_pengine(+Id, :Goal) is semidet.
%
% Run Goal while protecting the Pengine Id from being destroyed. Used
% by the HTTP I/O routines to avoid that the Pengine's module
% disappears while I/O is in progress. We use a pool of locks because
% the lock may be held relatively long by output routines.
%
% This also runs Goal if the Pengine no longer exists. This deals with
% Pengines terminated through destroy_or_continue/1.
%
% @bug After destroy_or_continue/1 takes the destroy route, the module
% may drop-out at any point in time, resulting in a possible crash.
% Seems the only safe way out is to do (de)serialization inside the
% Pengine.
:- meta_predicate protect_pengine(+, 0).
protect_pengine(Id, Goal) :-
term_hash(Id, Hash),
LockN is Hash mod 64,
atom_concat(pengine_done_, LockN, Lock),
with_mutex(Lock,
( pengine_thread(Id, _)
-> Goal
; Goal
)).
/** pengine_application(+Application) is det.
Directive that must be used to declare a pengine application module. The
module must not be associated to any file. The default application is
=pengine_sandbox=. The example below creates a new application
=address_book= and imports the API defined in the module file
=adress_book_api.pl= into the application.
==
:- pengine_application(address_book).
:- use_module(address_book:adress_book_api).
==
*/
pengine_application(Application) :-
throw(error(context_error(nodirective,
pengine_application(Application)), _)).
:- multifile
system:term_expansion/2,
current_application/1.
%! current_pengine_application(?Application) is nondet.
%
% True when Application is a currently defined application.
%
% @see pengine_application/1
current_pengine_application(Application) :-
current_application(Application).
% Default settings for all applications
:- setting(thread_pool_size, integer, 100,
'Maximum number of pengines this application can run.').
:- setting(thread_pool_stacks, list(compound), [],
'Maximum stack sizes for pengines this application can run.').
:- setting(slave_limit, integer, 3,
'Maximum number of slave pengines a master pengine can create.').
:- setting(time_limit, number, 300,
'Maximum time to wait for output').
:- setting(idle_limit, number, 300,
'Pengine auto-destroys when idle for this time').
:- setting(safe_goal_limit, number, 10,
'Maximum time to try proving safety of the goal').
:- setting(program_space, integer, 100_000_000,
'Maximum memory used by predicates').
:- setting(allow_from, list(atom), [*],
'IP addresses from which remotes are allowed to connect').
:- setting(deny_from, list(atom), [],
'IP addresses from which remotes are NOT allowed to connect').
:- setting(debug_info, boolean, false,
'Keep information to support source-level debugging').
system:term_expansion((:- pengine_application(Application)), Expanded) :-
must_be(atom, Application),
( module_property(Application, file(_))
-> permission_error(create, pengine_application, Application)
; true
),
expand_term((:- setting(Application:thread_pool_size, integer,
setting(pengines:thread_pool_size),
'Maximum number of pengines this \c
application can run.')),
ThreadPoolSizeSetting),
expand_term((:- setting(Application:thread_pool_stacks, list(compound),
setting(pengines:thread_pool_stacks),
'Maximum stack sizes for pengines \c
this application can run.')),
ThreadPoolStacksSetting),
expand_term((:- setting(Application:slave_limit, integer,
setting(pengines:slave_limit),
'Maximum number of local slave pengines \c
a master pengine can create.')),
SlaveLimitSetting),
expand_term((:- setting(Application:time_limit, number,
setting(pengines:time_limit),
'Maximum time to wait for output')),
TimeLimitSetting),
expand_term((:- setting(Application:idle_limit, number,
setting(pengines:idle_limit),
'Pengine auto-destroys when idle for this time')),
IdleLimitSetting),
expand_term((:- setting(Application:safe_goal_limit, number,
setting(pengines:safe_goal_limit),
'Maximum time to try proving safety of the goal')),
SafeGoalLimitSetting),
expand_term((:- setting(Application:program_space, integer,
setting(pengines:program_space),
'Maximum memory used by predicates')),
ProgramSpaceSetting),
expand_term((:- setting(Application:allow_from, list(atom),
setting(pengines:allow_from),
'IP addresses from which remotes are allowed \c
to connect')),
AllowFromSetting),
expand_term((:- setting(Application:deny_from, list(atom),
setting(pengines:deny_from),
'IP addresses from which remotes are NOT \c
allowed to connect')),
DenyFromSetting),
expand_term((:- setting(Application:debug_info, boolean,
setting(pengines:debug_info),
'Keep information to support source-level \c
debugging')),
DebugInfoSetting),
flatten([ pengines:current_application(Application),
ThreadPoolSizeSetting,
ThreadPoolStacksSetting,
SlaveLimitSetting,
TimeLimitSetting,
IdleLimitSetting,
SafeGoalLimitSetting,
ProgramSpaceSetting,
AllowFromSetting,
DenyFromSetting,
DebugInfoSetting
], Expanded).
% Register default application
:- pengine_application(pengine_sandbox).
/** pengine_property(?Pengine, ?Property) is nondet.
True when Property is a property of the given Pengine. Enumerates all
pengines that are known to the calling Prolog process. Defined
properties are:
* self(ID)
Identifier of the pengine. This is the same as the first argument,
and can be used to enumerate all known pengines.
* alias(Name)
Name is the alias name of the pengine, as provided through the
`alias` option when creating the pengine.
* thread(Thread)
If the pengine is a local pengine, Thread is the Prolog thread
identifier of the pengine.
* remote(Server)
If the pengine is remote, the URL of the server.
* application(Application)
Pengine runs the given application
* module(Module)
Temporary module used for running the Pengine.
* destroy(Destroy)
Destroy is =true= if the pengines is destroyed automatically
after completing the query.
* parent(Queue)
Message queue to which the (local) pengine reports.
* source(?SourceID, ?Source)
Source is the source code with the given SourceID. May be present if
the setting `debug_info` is present.
* detached(?Time)
Pengine was detached at Time.
*/
pengine_property(Id, Prop) :-
nonvar(Id), nonvar(Prop),
pengine_property2(Prop, Id),
!.
pengine_property(Id, Prop) :-
pengine_property2(Prop, Id).
pengine_property2(self(Id), Id) :-
current_pengine(Id, _Parent, _Thread, _URL, _Application, _Destroy).
pengine_property2(module(Id), Id) :-
current_pengine(Id, _Parent, _Thread, _URL, _Application, _Destroy).
pengine_property2(alias(Alias), Id) :-
child(Alias, Id),
Alias \== Id.
pengine_property2(thread(Thread), Id) :-
current_pengine(Id, _Parent, Thread, _URL, _Application, _Destroy),
Thread \== 0.
pengine_property2(remote(Server), Id) :-
current_pengine(Id, _Parent, 0, Server, _Application, _Destroy).
pengine_property2(application(Application), Id) :-
current_pengine(Id, _Parent, _Thread, _Server, Application, _Destroy).
pengine_property2(destroy(Destroy), Id) :-
current_pengine(Id, _Parent, _Thread, _Server, _Application, Destroy).
pengine_property2(parent(Parent), Id) :-
current_pengine(Id, Parent, _Thread, _URL, _Application, _Destroy).
pengine_property2(source(SourceID, Source), Id) :-
pengine_data(Id, source(SourceID, Source)).
pengine_property2(detached(When), Id) :-
pengine_detached(Id, When).
/** pengine_output(+Term) is det
Sends Term to the parent pengine or thread.
*/
pengine_output(Term) :-
pengine_self(Me),
pengine_reply(output(Me, Term)).
/** pengine_debug(+Format, +Args) is det
Create a message using format/3 from Format and Args and send this to
the client. The default JavaScript client will call
=|console.log(Message)|= if there is a console. The predicate
pengine_rpc/3 calls debug(pengine(debug), '~w', [Message]). The debug
topic pengine(debug) is enabled by default.
@see debug/1 and nodebug/1 for controlling the pengine(debug) topic
@see format/2 for format specifications
*/
pengine_debug(Format, Args) :-
pengine_parent(Queue),
pengine_self(Self),
catch(safe_goal(format(atom(_), Format, Args)), E, true),
( var(E)
-> format(atom(Message), Format, Args)
; message_to_string(E, Message)
),
pengine_reply(Queue, debug(Self, Message)).
/*================= Local pengine =======================
*/
%! local_pengine_create(+Options)
%
% Creates a local Pengine, which is a thread running
% pengine_main/2. It maintains two predicates:
%
% - The global dynamic predicate id/2 relates Pengines to their
% childs.