-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.py
1887 lines (1781 loc) · 82.2 KB
/
app.py
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
#!/usr/bin/env python3
# Virtualenv:
# https://scoutapm.com/blog/python-flask-tutorial-getting-started-with-flask
# To run (in the virtualenv):
# $ source bin/activate
# $ export FLASK_APP=app.py
# $ export FLASK_ENV=development
# $ export FLASK_DEBUG=1
# $ flask run
# app.py
import time
from flask import Flask, render_template, request, send_from_directory
from urllib.parse import urlparse
import urllib.request
import netifaces
import os
import os.path
import subprocess
import sys
import inspect
import reprlib
import socket
import functools
from urllib.parse import urlparse, urlunparse
from url_normalize import url_normalize
import re
import pathlib
import json
import rdflib
from dumper import dump
import datetime
##################### IsList ####################
# Is the given node (in graph g) a list?
# It is a list if it is RDF.nil or has an RDF.rest elemement.
def IsList(g, node):
return (node is rdflib.RDF.nil
or g.value(node, rdflib.RDF.rest) is not None)
##################### ToList ####################
# Given an RDF list, return it as a python list.
def ToList(g, node):
if node is rdflib.RDF.nil :
return []
return list(rdflib.collection.Collection(g, node))
# This is not really kosher to add this to the Graph class,
# but it is convenient:
rdflib.Graph.IsList = IsList
rdflib.Graph.ToList = ToList
#######################################################################
###################### Global constants ###########################
#######################################################################
global RDF_PIPELINE_DEV_DIR
RDF_PIPELINE_DEV_DIR = None
global PATH
PATH = None
def SetEnvDefault(yourDict, yourKey, defaultValue):
yourDict[yourKey] = yourDict.get(yourKey, defaultValue)
SetEnvDefault(os.environ, 'DOCUMENT_ROOT', "/var/www")
### TODO: Set $baseUri properly. Needs port?
SetEnvDefault(os.environ, 'SERVER_NAME', "localhost")
SERVER_NAME = os.environ.get('SERVER_NAME', '')
SetEnvDefault(os.environ, 'SERVER_SCHEME', "http")
SERVER_SCHEME = os.environ.get('SERVER_SCHEME', '')
if SERVER_SCHEME not in ['http', 'https'] :
raise ValueError(f'$SERVER_SCHEME must be "http" or "https": "{SERVER_SCHEME}"')
# SERVER_PORT must be set as a string.
SetEnvDefault(os.environ, 'SERVER_PORT', '')
SERVER_PORT = os.environ.get('SERVER_PORT', '')
# Default port for http is 80; https is 443.
if (SERVER_SCHEME == 'http' and SERVER_PORT == '80') or (SERVER_PORT == 'https' and SERVER_PORT == '443') :
Warn(f"[WARNING] Setting $SERVER_PORT={SERVER_PORT} to '', because it was the default for $SERVER_SCHEME={SERVER_SCHEME}")
os.environ['SERVER_PORT'] = ''
SERVER_PORT = ''
#######################################################################
###################### Functions start here ###########################
#######################################################################
######################### Die ########################
# Replacement for perl's die
def Die(error_message='Died'):
raise Exception(error_message)
################ LocalIps #################
# Return all the IPs by which this host is locally known.
# Results are cached for fast repeated lookup.
# Works for all my known local hostnames or IP addresses, e.g.,
# 127.0.0.1 192.168.90.152 10.8.0.54 localhost dbooth-t470p
# This function might not be needed.
def LocalIps():
if not hasattr(LocalIps, "_localIps") :
# https://stackoverflow.com/questions/270745/how-do-i-determine-all-of-my-ip-addresses-when-i-have-multiple-nics#answer-33946251
LocalIps._localIps = set([netifaces.ifaddresses(iface)[netifaces.AF_INET][0]['addr'] for iface in netifaces.interfaces() if netifaces.AF_INET in netifaces.ifaddresses(iface)])
# https://stackoverflow.com/questions/270745/how-do-i-determine-all-of-my-ip-addresses-when-i-have-multiple-nics#answer-16412986
LocalIps._localIps.update([i[4][0] for i in socket.getaddrinfo(socket.gethostname(), None)])
#### TODO: is there an IPv6 localhost convention that also needs to be checked?
#### TODO: Do I really need to check for the ^127\. pattern?
# WarnLine("LocalIps: " + " ".join(LocalIps._localIps))
return(LocalIps._localIps)
################ IsCurrentWebServer #################
# Is the given host name, which may be either a domain name or
# an IP address, hosted on this same web server?
# This is used to canonicalize URIs in a pipeline definition, so
# that we can determine whether a request made to a URI would actually
# (recursively) go to the current web server, which we need to avoid.
# My laptop is currently accessible by these IPs:
# # 127.0.0.1 192.168.90.152 10.8.0.54 localhost dbooth-t470p
# When flask is run in dev mode, it normally only responds
# to requests made to localhost (which is 127.0.0.1),
# whereas in production mode (run with --host=0.0.0.0) it will respond to
# external requests, i.e., requests to any of the above IP addresses.
# This means that, although in dev mode flask
# won't respond to requests made to 192.168.90.152 (for example),
# the framework should still work, because it will canonicalize
# that IP to localhost, recognize it as the current web server host,
# and avoid making an HTTP request anyway.
# Results are cached for fast repeated lookup.
@functools.lru_cache(maxsize=None)
def IsCurrentWebServer(host, port=None):
if host == '' : return False
# First compare the ports. If the ports differ then its a different
# web server.
# Default them to '' for easier comparison:
p = '' if port is None else port
sp = '' if SERVER_PORT is None else SERVER_PORT
# Warn(f"IsCurrentWebServer({host}, {p}) SERVER_PORT={sp} port={p}")
if p != sp :
Warn(f"IsCurrentWebServer SERVER_PORT != port; returning False")
return False
# Now compare the hostname. This is more complex because we need
# to consider aliases that go to the same IP address. We used to
# also consider multiple IP addresses for this server, but I think
# that was wrong, since I think the server only listens on one
# IP address.
try:
#### TODO: is there an IPv6 localhost convention that also needs to be checked?
# Warn("Calling gethostbyname...")
h_ip = socket.gethostbyname(host)
sn_ip = socket.gethostbyname(SERVER_NAME)
# Warn(f"h_ip: {h_ip} sn_ip: {sn_ip}")
if h_ip == sn_ip :
# Warn(f"IsCurrentWebServer host is local; returning True")
return True
except OSError as error:
# As a sanity check, make sure we can get the localhost IP.
# If not, re-throw the original exception because we cannot run:
try:
localhostIp = socket.gethostbyname('localhost')
except OSError:
raise error
# Inability to resolve a given host is non-fatal. We consider
# the host non-local:
# Warn(f"IsCurrentWebServer returning False 3")
return False
# Warn(f"IsCurrentWebServer non-local IP -- returning False 2")
return False
################ CanonicalizeUri #################
# Canonicalize the given URI: If it is an absolute local http URI,
# then canonicalize it to $SERVER_NAME localhost or 127.0.0.1 .
# Other URIs are passed through unchanged.
# The reason for canonicalizing only node URIs on this web server is because
# the RDF Pipeline Framework will be handling requests for them, so
# it needs to be able to distinguish them from foreign URIs, both
# to avoid an infinite recursion of HTTP requests and to lookup
# metadata based on the URI. If the URI were a synonym, such as
# http://127.0.0.1/node/foo instead of http://localhost/node/foo ,
# then the metadata lookup would fail to find the metadata.
# @functools.lru_cache(maxsize=None)
def CanonicalizeUri(oldUri):
# Warn(f"CanonicalizeUri({oldUri})")
# urlparse returns a hostname of None if a relative URI is given.
oldParsed = urlparse(oldUri)
host = oldParsed.hostname
port = oldParsed.port
if host :
# Pass it through url_normalize before reparsing,
# to get rid of any default port. We had to test for non-empty
# host before doing this, because oldUri may be something like 'foo'
# or 'rdfs:subClassOf', which would be treated by url_normalize
# as a relative URI or an rdfs scheme.
oldParsed = urlparse(url_normalize(oldUri))
host = oldParsed.hostname
port = oldParsed.port
# Convert port to string:
host = '' if host is None else host
port = '' if port is None else str(port)
# Warn(f"CanonicalizeUri({oldUri}) oldParsed: {dump(oldParsed)}")
Warn(f"CanonicalizeUri host: {host} port: {port}")
if not IsCurrentWebServer(host, port) :
# Warn(f"CanonicalizeUri not IsCurrentWS; returning oldUri: {oldUri}")
return oldUri
# Prefer SERVER_NAME over localhost or 127.0.0.1
localUri = oldUri
if host != SERVER_NAME :
# Warn(f"CanonicalizeUri using SERVER_NAME: {SERVER_NAME}")
netloc = SERVER_NAME
if (port is not None and port != '') :
netloc += f':{port}'
# Warn(f"CanonicalizeUri netloc: {netloc}")
localUri = urlunparse(oldParsed._replace(netloc=netloc))
# Warn(f"CanonicalizeUri localUri: {localUri}")
# url_normalize adds a slash if needed, but we don't want it.
# TODO: Figure out the impact of removing the final slash.
if oldUri[-1] != '/' and localUri[-1] == '/' :
# Warn(f"CanonicalizeUri removing trailing slash")
localUri = localUri[0:-1]
Warn(f"CanonicalizeUri returning 260: {localUri}")
return str(localUri)
########## ReadFile ############
def ReadFile(filename):
with open(filename, "r", encoding='utf-8') as f:
return f.read()
####################### WriteFile #####################
# UTF-8 python3
def WriteFile(filename, s):
with open(filename, "w", encoding="utf8") as f:
f.write(s)
####################### AppendFile #####################
# UTF-8 python3
def AppendFile(filename, s):
with open(filename, "a+", encoding="utf8") as f:
f.write(s)
################# findall_sub #####################
# Python3 function to perform string substitution while
# also returning group matches.
def findall_sub(pattern, repl, string, count=0, flags=0):
""" Call findall and sub, and return a tuple: newString, matches """
newString = string
matches = re.findall(pattern, string, flags)
if (matches) :
newString = re.sub(pattern, repl, string, count, flags)
return newString, matches
########## PrintLog ############
def PrintLog(msgs):
global logFile;
AppendFile(logFile, msgs)
########## WarnLine ############
def WarnLine(msg, level=0):
Warn(msg + "\n")
########## Warn ############
# Log a warning if the current $debug >= $level for this warning.
# This will go to the apache error log: /var/log/apache2/error.log
# and also to $logFile .
def Warn(msg, level=0):
global debugStackDepth
global debug
# As a debugging convenience, force a newline at the end:
if not msg.endswith('\n') :
msg = msg + "\n";
if debug is None :
# sys.stderr.write("debug not defined!\n")
raise NameError("debug not defined!\n")
if level is not None and debug < level :
return 1
maxRecursion = 30
# depth = debugStackDepth + &CallStackDepth() -2;
depth = debugStackDepth + len(inspect.stack(0)) - debugStackDepthOffset
if depth >= maxRecursion :
raise RecursionError(f"PANIC!!! Deep recursion > {maxRecursion}! debug {debug} \n Maybe a cycle in the pipeline graph?\n")
indent = depth *2
# Additional indent like Warn(" One\nTwo\n") will be applied to
# all lines in the given string also, producing:
# One
# Two
moreSpaces = "";
# $moreSpaces = $1 if $msg =~ s/^(\s+)//;
# findall_sub(pattern, repl, string, count=0, flags=0):
msg, matches = findall_sub(r'^(\s+)', '', msg)
if (matches) :
# $msg =~ s/^/$spaces/mg;
moreSpaces = matches[0]
spaces = (" " * indent) + moreSpaces
# When there is a newline at the end, perl prevents it from
# matching ^, but python doesn't, which adds extra indent at the end.
# To work around this problem and prevent extra spaces
# after the final newline, we use ^(?=.|\n) here instead.
# msg = re.sub(r'^', spaces, msg, flags=re.MULTILINE)
msg = re.sub(r'^(?=.|\n)', spaces, msg, flags=re.MULTILINE)
PrintLog(msg)
#### TODO: Is this test needed? It looks like a debugging remnant.
global configLastModified
if configLastModified is None :
sys.stderr.write("configLastModified not defined!\n")
# if !defined($level) || $debug >= $level;
if level is None or debug >= level :
sys.stderr.write(msg)
return 1
#################################################################
####################### Global Variables ########################
#################################################################
logFile = "/tmp/rdf-pipeline-log.txt"
timingLogFile = "/tmp/rdf-pipeline-timing.tsv"
timingLogFileIsOpen = 0
timingLogFH = None
timingLogExists = 0
# unlink $logFile || die;
# Find the directory where this script is running
script_dirname = os.path.realpath(sys.path[0])
isLocal = {} # Cache for IsCurrentWebServer
localIp = None # IP address of this host
######################### Node Types ########################
# TODO: use RDF::Pipeline::ExampleHtmlNode;
# TODO: use RDF::Pipeline::GraphNode;
################## Debugging and testing ##################
# debug verbosity:
DEBUG_OFF = 0 # No debug output. Warnings/errors only.
DEBUG_NODE_UPDATES = 1 # Show nodes updated.
DEBUG_PARAM_UPDATES = 2; # Also show parameters updated.
DEBUG_CACHES = 3 # Also show caches updated.
DEBUG_CHANGES = 4 # Also show them unchanged. This verbosity is normally used for regression testing.
DEBUG_REQUESTS = 5 # Also show requests.
DEBUG_DETAILS = 6 # Show requests plus more detail.
# debug level is set using an env var:
debug = int(os.getenv('RDF_PIPELINE_DEBUG', str(DEBUG_DETAILS)))
rawDebug = debug;
# Allows symbolic $debug value (not supported in python version):
# $debug = eval $debug if defined($debug) && $debug =~ m/^\$\w+$/;
debugStackDepth = 0 # Used for indenting debug messages.
# Compensate for flask stack depth:
debugStackDepthOffset = len(inspect.stack(0)) + 6
test = None # For testing outside of apache2
################### Runtime data ####################
configLastModified = 0
ontLastModified = 0
internalsLastModified = 0
configLastInode = 0
ontLastInode = 0
internalsLastInode = 0
config = {} # Maps: $s->{$p}->[v1, v2, ... vn]
# Node metadata distilled for the pipeline is held in $nm. It is
# a combination of several kinds of maps from subject to predicate
# to one or more objects.
# The objects may be different kinds, depending on the predicate,
# but these data structures don't bother to keep track of which
# predicate uses which object type. Instead, we generate all
# object types for all predicates. The main data structure is $nm
# for "node metadata").
# But For ease of access the following variables point to various different
# slices of the $nm data structure.
# For single-valued predicates:
# my $nmv = $nm->{value};
# my $value = $nmv->{$subject}->{$predicate};
# For list-valued predicates:
# my $nml = $nm->{list};
# my $listRef = $nml->{$subject}->{$predicate};
# my @list = @{$listRef};
# For hash-valued predicates:
# my $nmh = $nm->{hash};
# my $hashRef = $nmh->{$subject}->{$predicate};
# my $value = $hashRef->{$key};
# For multi-valued predicates:
# my $nmm = $nm->{multi};
# my $hashRef = $nmm->{$subject}->{$predicate};
# For list of unique values (for non-unique use {list} instead):
# my @values = keys %{$hashRef};
# To see if a particular value exists (each $value is mapped to 1):
# if ($hashRef->{$value}) ...
# Since each predicate uses only one of these, we could obviously save
# memory if we kept track of which predicate holds which kind of object,
# and then only store that kind for that predicate.
nm = {"value": {}, "list": {}, "hash": {}, "multi": {}}
# CheckKeys(nm)
################## Constants for this server ##################
ontologyPrefix = "http://purl.org/pipeline/ont#" # Pipeline ont prefix
# 80 and 443 are the default ports for http and https:
if SERVER_PORT is not None and SERVER_PORT in {"80", "443"} :
Die(f"[ERROR] SERVER_PORT={SERVER_PORT} must not be set if it is the default for the scheme, because it will mess up IsCurrentWebServer tests.\n")
if not IsCurrentWebServer(SERVER_NAME, SERVER_PORT) :
Die(f"[ERROR] Non-local $SERVER_NAME:$SERVER_PORT {SERVER_NAME}:{SERVER_PORT}\n")
# Die("[DUMP] Non-local $SERVER_NAME: {"+os.environ['SERVER_NAME']+"}\n")
serverName = "localhost"
# If "localhost" is not recognized current web server, then
# at least 127.0.0.1 should be.
if not IsCurrentWebServer(serverName, SERVER_PORT) :
serverName = "127.0.0.1"
if not IsCurrentWebServer(serverName, SERVER_PORT) :
Die(f"[ERROR] Not recognized as local: {serverName} SERVER_PORT: {SERVER_PORT}")
# $baseUri is the URI prefix that corresponds directly to DOCUMENT_ROOT.
# baseUri = CanonicalizeUri(f"http://127.0.0.1:{SERVER_PORT}");
baseUri = f"{SERVER_SCHEME}://{SERVER_NAME}"
if SERVER_PORT != '' :
baseUri += f":{SERVER_PORT}"
# $baseUri will normally now be "http://localhost:5000" -- ready for use.
# url_normalize adds a trialing slash:
if f"{baseUri}/" != url_normalize(baseUri) :
Die(f"[ERROR] Configuration error: baseURI/={baseUri}/\n does not match normalized baseUri={url_normalize(baseUri)}\n Is $SERVER_PORT={SERVER_PORT} set wrong?\n It should not be set if it is the default for this $SERVER_SCHEME={SERVER_SCHEME}")
baseUriPattern = re.escape(baseUri)
basePath = os.environ['DOCUMENT_ROOT'] # Synonym, for convenience
basePathPattern = re.escape(basePath)
nodeBaseUri = baseUri + "/node" # Base for nodes
nodeBaseUriPattern = re.escape(nodeBaseUri)
nodeBasePath = basePath + "/node"
nodeBasePathPattern = re.escape(nodeBasePath)
lmCounterFile = basePath + "/lm/lmCounter.txt"
rdfsPrefix = "http://www.w3.org/2000/01/rdf-schema#"
# our $subClassOf = $rdfsPrefix . "subClassOf";
subClassOf = "rdfs:subClassOf"
# This $configFile will be used only if $RDF_PIPELINE_MASTER_URI is not set:
configFile = nodeBasePath + "/pipeline.ttl"
ontFile = basePath + "/ont/ont.n3"
internalsFile = basePath + "/ont/internals.n3"
tmpDir = basePath + "/tmp"
#### $nameType constants used by SaveLMs/LookupLMs:
#### TODO: Change to "use Const".
URI = 'URI'
FILE = 'FILE'
# These query parameters are used by the RDF Pipeline Framework:
systemArgs = ['debug', 'debugStackDepth', 'callerUri', 'callerLM', 'method']
Warn(f'Starting with debug: {debug}\n')
Warn("********** NEW APACHE THREAD INSTANCE **********\n", DEBUG_DETAILS)
#### Hopefully this is not needed in python:
# my $hasHiResTime = &Time::HiRes::d_hires_stat()>0;
# $hasHiResTime || die;
#### Command-line testing is not implemented in the python version
##################### handler #######################
# handler will be called by apache2 to handle any request that has
# been specified in /etc/apache2/sites-enabled/000-default .
def handler(r):
# my $r = shift || die;
# base_url omits the query params
thisUri = r.base_url
oldThisUri = thisUri
thisUri = CanonicalizeUri(thisUri)
qp = r.args;
args = {k: v[0] for k, v in qp.items()}
global debug
if 'debug' in args :
debug = args['debug']
#### Not implemented in python version:
# # Allows symbolic $debug value:
# $debug = eval $debug if defined($debug) && $debug =~ m/^\$\w+$/;
global debugStackDepth
debugStackDepth = 0
if 'debugStackDepth' in args :
debugStackDepth = args['debugStackDepth']
# warn("="x30 . " handler " . "="x30 + "\n");
Warn("="*30 + " handler " + "="*30 + "\n", DEBUG_DETAILS);
Warn(f"handler debug level: {debug}\n", DEBUG_DETAILS);
# Warn("" . `date`, DEBUG_DETAILS);
Warn("" + os.popen('date').read(), DEBUG_DETAILS);
# Warn("SERVER_NAME: $ENV{SERVER_NAME} serverName: $serverName\n", DEBUG_DETAILS);
Warn("SERVER_NAME: " + SERVER_NAME + f" serverName: {serverName}\n", DEBUG_DETAILS);
Warn(f"oldThisUri: {oldThisUri}\n", DEBUG_DETAILS);
Warn(f"thisUri: {thisUri}\n", DEBUG_DETAILS);
Warn(f"baseUri: {baseUri}\n", DEBUG_DETAILS);
Warn(f"basePath: {basePath}\n", DEBUG_DETAILS);
# Warn("DOCUMENT_ROOT: $ENV{DOCUMENT_ROOT}\n", DEBUG_DETAILS);
Warn("DOCUMENT_ROOT: " + os.environ.get('DOCUMENT_ROOT', '') + "\n", DEBUG_DETAILS);
# Set $RDF_PIPELINE_DEV_DIR and $PATH so that updaters will inherit them.
# For some reason, in apache2/mod_perl it does not work to set this only once when the thread
# starts. $ENV{PATH}, at least, seems to be reset each time the handler
# is called after the first time. I don't know what happens in flask.
global RDF_PIPELINE_DEV_DIR
if RDF_PIPELINE_DEV_DIR is None :
RDF_PIPELINE_DEV_DIR = os.environ.get('RDF_PIPELINE_DEV_DIR')
if RDF_PIPELINE_DEV_DIR is None :
# execute the set_env.sh script so we can get the variables in our env
# RDF_PIPELINE_DEV_DIR = `. $script_dirname/set_env.sh ; echo -n \$RDF_PIPELINE_DEV_DIR`
script = f'. "{script_dirname}/set_env.sh" ; echo -n \\$RDF_PIPELINE_DEV_DIR'
Warn(f"RDF_PIPELINE_DEV_DIR script: {script}")
RDF_PIPELINE_DEV_DIR = os.popen(script).read()
if not os.path.isdir(RDF_PIPELINE_DEV_DIR) :
Die("[INTERNAL ERROR] RDF_PIPELINE_DEV_DIR is not set or not a dir: {RDF_PIPELINE_DEV_DIR}\n")
os.environ['RDF_PIPELINE_DEV_DIR'] = RDF_PIPELINE_DEV_DIR
# Warn(f"RDF_PIPELINE_DEV_DIR: {RDF_PIPELINE_DEV_DIR}")
# Set PATH in env
global PATH
dirs = []
if PATH is None :
# To make sure that PATH is set correctly,
# execute the set_env.sh script to set it.
# If it was already set, this will cause no harm, because
# it will only append to the path.
# PATH = `. $script_dirname/set_env.sh ; echo -n \$PATH`
script = f'. "{script_dirname}/set_env.sh" ; echo -n "$PATH"'
Warn(f"PATH script: {script}")
PATH = os.popen(script).read()
# As a sanity check, make sure at least two elements of $PATH
# are directories, and make sure it contains the tools dir:
# dirs = filter(lambda f: os.path.isdir(f), PATH.split(os.pathsep))
dirs = [d for d in PATH.split(os.pathsep) if os.path.isdir(d)]
toolsDir = RDF_PIPELINE_DEV_DIR + "/tools"
# Warn(f"dirs: {dirs}")
# Warn(f"toolsDir: {toolsDir}")
if len(dirs) < 2 or not (toolsDir in PATH) :
Die(f"[INTERNAL ERROR] PATH is not set properly: {PATH}\n")
os.environ['PATH'] = PATH
# Warn(f"PATH: {PATH}")
# Flattened list of key/value pairs:
argsList = [item for pair in args for item in pair]
nArgs = len(argsList)
Warn(f"Query string (elements {nArgs}): {argsList}\n", DEBUG_DETAILS);
# Warn("-"*20 + "handler" + "-"*20 + "\n", DEBUG_DETAILS);
ret = RealHandler(r, thisUri, args);
Warn(f"RealHandler returned: {str(ret)}\n", DEBUG_DETAILS);
Warn("="*60 + "\n", DEBUG_DETAILS);
return ret;
########## AbsUri ############
# Converts (possibly relative) URI to absolute URI, using $baseUri.
def AbsUri(uri):
# From RFC 3986:
# scheme = ALPHA *( ALPHA / DIGIT / "+" / "-" / "." )
#### TODO: change this to use the perl URI module:
#### http://lwp.interglacial.com/ch04_04.htm
# if ($uri !~ m/\A[a-zA-Z][a-zA-Z0-9\+\-\.]*\:/) {
if not re.match(r'[a-zA-Z][a-zA-Z0-9\+\-\.]*\:', uri) :
# Relative URI
# $uri =~ s|\A\/||; # Chop leading / if any
if uri[0] == '/' :
uri = uri[1:]
uri = baseUri + "/" + uri
return uri
########## UriToPath ############
# Converts (possibly relative) URI to absolute file path (if local)
# or returns "". Extra parameters ($baseUri and $hostRoot) are ignored
# and globals $baseUriPattern and $basePath are used instead.
def UriToPath(uri):
### Ignore these parameters and use globals $baseUriPattern and $basePath:
path = AbsUri(uri)
#### TODO: Make this work for IPv6 addresses.
#### TODO: Why are we only stripping port 80?
# Get rid of superfluous port 80 before converting:
path = re.sub(r'\A(http(s?)\:\/\/[^\/\:]+)\:80\/', r'\1\/', path)
oldPath = path
path = re.sub(r'\A' + baseUriPattern + r'\/', f"{basePath}/", path)
Warn(f"UriToPath uri: {uri}")
Warn(f"UriToPath oldPath: {oldPath}")
Warn(f"UriToPath path: {path}")
if oldPath != path :
return path
return ""
################ IsLocalNode #################
# No longer needed. Use IsCurrentWebServer instead.
def IsLocalNode(n):
return IsCurrentWebServer(n)
################ def Mirror #################
# Conditionally GET content from a URL, saving to a given file.
# Return 1 iff the file was updated.
mirrorHeaders = {}
def Mirror(url, filepath):
Warn(f"Mirror called with url={url} filepath={filepath}")
headers = mirrorHeaders[url] if url in mirrorHeaders else {}
Warn(f" Old headers: {json.dumps(headers, indent=2)}")
if not os.path.isfile(filepath) :
# If the file got deleted, force an unconditional GET:
Warn(f" File is gone! Clearing headers.")
headers = {}
req = urllib.request.Request(url, headers = headers)
try:
response = urllib.request.urlopen(req)
Warn(f" response.status={response.status}")
Warn(f" response.getheaders()={json.dumps(response.getheaders(), indent=2)}")
if response.status == 200 :
newHeaders = {}
etag = response.getheader('ETag')
if etag is not None :
Warn(f" Got ETag: {etag}")
newHeaders['If-None-Match'] = etag
lm = response.getheader('Last-Modified')
if lm is not None :
Warn(f" Got Last-Modified: {lm}")
newHeaders['If-Modified-Since'] = lm
mirrorHeaders[url] = newHeaders
content = response.read()
MakeParentDirs(filepath)
with open(filepath,"wb") as fp:
fp.write(content)
Warn(f" wrote file: {filepath}")
return 1
else :
Die(f"[ERROR] Mirror: GET return unknown status={response.status}")
except urllib.error.HTTPError as e:
# Oddly, urllib.request treats a 304 response as an exception,
# which I think was a design mistake.
if e.code == 304 :
Warn(f" 304 Not modified.")
return 0
else :
Warn(f" Error: {e.code}")
raise e
# return content
########## MakeParentDirs ############
# Ensure that parent directories exist before creating this file.
# Optionally, directories that have already been created are remembered, so
# we won't waste time trying to create them again.
def MakeParentDirs(path):
fDir, tail = os.path.split(path)
if not os.path.isdir(fDir) :
os.makedirs(fDir, exist_ok=True)
############### MTime #################
# Return the nanoseconds last modified time for the given file.
def MTime(path):
mtime, inode = MTimeAndInode(path)
return mtime
############### MTimeAndInode #################
# Return the nanoseconds last modified time and inode for the given file.
def MTimeAndInode(path):
s = os.stat(path)
return s.st_mtime, s.st_ino
############### LM Constants ##############
# An LM is derived from the (floating point) number of seconds (with
# microseconds) since the epoch, followed by some counter digits that
# ensure that the LM is unique even if the clock did not change
# noticeably between calls.
#
# Example LM: 0123456789.123456000001
# | | | || |
# + seconds+ + μs ++ counter
#
# Zero-padded digits of seconds left of decimal point:
lmSecondsWidth = 10
# Digits right of decimal point (microseconds or μs):
lmDecimalPlaces = 6
# Number of digits in the LM counter:
lmCounterWidth = 6
# These are for convenience:
lmSecondsDPWidth = lmSecondsWidth + 1 + lmDecimalPlaces
nsPerSecond = 1000 * 1000 * 1000
lmNsPerTick = nsPerSecond
lmTicksPerSecond = 1
for _ in range(lmDecimalPlaces):
lmNsPerTick //= 10
lmTicksPerSecond *= 10
if lmNsPerTick == 0 :
Die(f"Too many decimal places for nanosecond clock values in lmDecimalPlaces: '{lmDecimalPlaces}'")
lmCounterMax = 1
for _ in range(lmCounterWidth):
lmCounterMax *= 10
lmCounterMax -= 1
if lmCounterMax < 9 :
Die(f"Bad lmCounterMax ({lmCounterMax}) computed from lmCounterWidth: {lmCounterWidth}")
########## FormatTime ############
# Turn a floating point time (in seconds) into a string.
# The seconds should also have microseconds.
# The string is padded with leading zeros for easy string comparison,
# ensuring that $a lt $b iff $a < $b.
# An empty string "" will be returned if the time is 0.
def FormatTime(timeSec, decimalPlaces=lmDecimalPlaces):
if not timeSec or timeSec == 0 :
return ""
# Enough digits to work through year 2286:
# my $lmt = sprintf("%010.6f", $time);
lmt = f"{timeSec:0{lmSecondsWidth}.{decimalPlaces}f}"
# length($lmt) == 10+1+6 or confess "Too many digits in time!";
if len(lmt) != lmSecondsWidth+1+decimalPlaces :
Die(f"FormatTime: Wrong number of digits in LM time: '{lmt}'")
return lmt
########## FormatCounter ############
# Format a counter for use in an LM string.
# The counter becomes the lowest order digits.
# The string is padded with leading zeros for easy string comparison,
# ensuring that $a lt $b iff $a < $b.
def FormatCounter(counter):
if counter is None :
counter = 0
lmCounterWidth = 6
# my $sCounter = sprintf("%0$lmCounterWidth" . "d", $counter);
sCounter = f"{counter:0{lmCounterWidth}}"
if len(sCounter) > lmCounterWidth :
Die(f"FormatCounter: Counter overflow! Need more than lmCounterWidth={lmCounterWidth} digits in counter!")
return sCounter
########## TimeToLM ############
# Turn a floating time (in seconds) and optional int counter into an LM string,
# for use in headers, etc. The counter becomes the lowest order digits.
# The string is padded with leading zeros for easy string comparison,
# ensuring that $a lt $b iff $a < $b.
# As generated, these are monotonic. But in general the system does
# not require LMs to be monotonic, because they could be checksums.
# The only guarantee that the system requires is that they change
# if a node output has changed.
# An empty string "" will be returned if the timeSec is 0.
# If counter is None, then the lower-order precision of the given timeSec is
# used instead of the counter. This is useful for generating an LM from
# a static file modification time.
def TimeToLM(timeSec, counter):
if not timeSec :
return ""
if counter is None :
return FormatTime(timeSec, lmDecimalPlaces+lmCounterWidth)
return FormatTime(timeSec) + FormatCounter(counter)
############# TestLmGenerator ##############
def TestLmGenerator(n):
oldLm = 0
for _ in range(n):
lm = GenerateNewLM(oldLm)
if lm[-1] != '0' :
raise ValueError("lm: "+lm)
oldLm = lm
############# GenerateNewLM ##############
# Generate a new LM, based on the current time, that is guaranteed unique
# on this server even if this function is called faster than the
# clock resolution. Within the same thread
# it is guaranteed to increase monotonically (assuming the
# clock increases monotonically). This is done by
# appending a counter to the lower order digits of the current time.
# Even if the clock is not monotonic, it will still generate a different
# LM from the given oldLm, by incrementing the counter if the
# time is otherwise the same. If there is no oldLm then the empty
# string should be passed as oldLm.
#
# Example LM: 0123456789.123456000001
# | | | || |
# + seconds+ + μs ++ counter
#
def GenerateNewLM(oldLm):
oldCounter = -1 # Will be incremented before use
tSec = time.time()
tSecString = FormatTime(tSec)
# tSecString looks like: "0123456789.123456" (i.e., no counter)
if oldLm :
# oldLm looks like: "0123456789.123456000001"
if len(oldLm) != lmSecondsDPWidth+lmCounterWidth :
Die(f"GenerateNewLM: corrupt oldLm: '{oldLm}'")
# Extract the old ms time as string, i.e., chop off the counter.
# oldSecString will look like: "0123456789.123456"
oldSecString = oldLm[0 : lmSecondsDPWidth]
# Still the same time? If so, grab the old counter.
if tSecString == oldSecString :
oldCounterString = oldLm[lmSecondsDPWidth : ]
oldCounter = int(oldCounterString)
counterString = FormatCounter(oldCounter+1)
lm = tSecString + counterString
if len(lm) != lmSecondsDPWidth+lmCounterWidth :
Die(f"GenerateNewLM: Internal error in generating lm: '{lm}'")
return lm
################ IsExecutable #################
def IsExecutable(f):
return os.access(f, os.X_OK)
########## NodeAbsPath ############
# Converts (possibly relative) file path to absolute path,
# using $nodeBasePath.
def NodeAbsPath(path):
if not path.startswith("/") :
# Relative path
path = f"{nodeBasePath}/{path}"
return path
############# FileNodeRunUpdater ##############
# Run the updater, returning the new LM.
# If there is no updater (i.e., static state) then we must generate
# an LM from the state.
def FileNodeRunUpdater(nm, thisUri, updater, state, thisInputs, thisParameters,
oldThisLM, callerUri, callerLM):
Warn(f"FileNodeRunUpdater(nm, {thisUri}, {updater}, {state}, ...) called.\n", DEBUG_DETAILS)
# CheckKeys(nm)
if not updater :
# Retain as many digits of MTime as possible
# when dealing with a static file, instead of using a counter
# at the end of the LM.
return TimeToLM(MTime(state), None)
state or Die();
state = NodeAbsPath(state)
updater = NodeAbsPath(updater)
Warn(f"Abs state: {state} Abs updater: {updater}\n", DEBUG_DETAILS)
# TODO: Move this warning to when the metadata is loaded?
if not IsExecutable(updater) :
Die(f"ERROR: {thisUri} updater {updater} is not executable by web server!")
# The FileNode updater args are local filenames for all
# inputs and parameters.
# my $inputFiles = join(" ", map {quotemeta($_)}
# @{$nm->{list}->{$thisUri}->{inputCaches}});
inputFiles = " ".join([re.escape(f) for f in
nm['list'].get(thisUri,{}).get('inputCaches',[])])
Warn(f"inputFiles: {inputFiles}\n", DEBUG_DETAILS)
# my $parameterFiles = join(" ", map {quotemeta($_)}
# @{$nm->{list}->{$thisUri}->{parameterCaches}});
parameterFiles = " ".join([re.escape(f) for f in
nm['list'].get(thisUri,{}).get('parameterCaches',[])])
Warn(f"parameterFiles: {parameterFiles}\n", DEBUG_DETAILS)
ipFiles = f"{inputFiles} {parameterFiles}";
Die(f"**** FileNodeRunUpdater STOPPED HERE ****")
commentOut = '''
#### TODO: Move this code out of this function and pass $latestQuery
#### as a parameter to FileNodeRunUpdater.
#### TODO QUERY:
my $thisVHash = $nm->{value}->{$thisUri} || Die;
my $parametersFile = $thisVHash->{parametersFile} || Die;
my ($lm, $latestQuery, %requesterQueries) =
&LookupLMs($FILE, $parametersFile);
$lm = $lm; # Avoid unused var warning
my $qLatestQuery = quotemeta($latestQuery);
my $exportqs = "export QUERY_STRING=$qLatestQuery";
$exportqs = &ConstructQueryStringExports($latestQuery) . " $exportqs";
# my $qss = quotemeta(&BuildQueryString(%requesterQueries));
my $qss = quotemeta(join(" ", sort values %requesterQueries));
my $exportqss = "export QUERY_STRINGS=$qss";
####
my $stderr = $nm->{value}->{$thisUri}->{stderr};
# Make sure parent dirs exist for $stderr and $state:
&MakeParentDirs($stderr, $state);
# Ensure no unsafe chars before invoking $cmd:
my $qThisUri = quotemeta($thisUri);
my $qState = quotemeta($state);
my $qUpdater = quotemeta($updater);
my $qStderr = quotemeta($stderr);
my $useStdout = 0;
my $stateOriginal = $nm->{value}->{$thisUri}->{stateOriginal} || "";
&Warn("stateOriginal: $stateOriginal\n", $DEBUG_DETAILS);
$useStdout = 1 if $updater && !$stateOriginal;
Die "[INTERNAL ERROR] RDF_PIPELINE_DEV_DIR not set in environment! "
if !$ENV{RDF_PIPELINE_DEV_DIR};
my $qToolsDir = quotemeta("$ENV{RDF_PIPELINE_DEV_DIR}/tools");
Die "[INTERNAL ERROR] PATH not set properly: $ENV{PATH} "
if $ENV{PATH} !~ m/$qToolsDir/;
&Warn("ENV{PATH}: $ENV{PATH}\n", $DEBUG_DETAILS);
&Warn("ENV{RDF_PIPELINE_DEV_DIR}: $ENV{RDF_PIPELINE_DEV_DIR}\n", $DEBUG_DETAILS);
my $qPath = quotemeta($ENV{PATH}) || Die;
my $cmd = "( cd '$nodeBasePath' ; export THIS_URI=$qThisUri ; export PATH=$qPath ; $qUpdater $qState $ipFiles > $qStderr 2>&1 )";
$cmd = "( cd '$nodeBasePath' ; export THIS_URI=$qThisUri ; export PATH=$qPath ; $qUpdater $ipFiles > $qState 2> $qStderr )"
if $useStdout;
#### TODO QUERY:
$cmd = "( cd '$nodeBasePath' ; export THIS_URI=$qThisUri ; export PATH=$qPath ; $exportqs ; $exportqss ; $qUpdater $qState $ipFiles > $qStderr 2>&1 )";
$cmd = "( cd '$nodeBasePath' ; export THIS_URI=$qThisUri ; export PATH=$qPath ; $exportqs ; $exportqss ; $qUpdater $ipFiles > $qState 2> $qStderr )"
if $useStdout;
####
&Warn("cmd: $cmd\n", $DEBUG_DETAILS);
my $result = (system($cmd) >> 8);
my $saveError = $?;
&Warn("FileNodeRunUpdater: Updater returned " . ($result ? "error code:" : "success:") . " $result.\n", $DEBUG_DETAILS);
if (-s $stderr) {
&Warn("FileNodeRunUpdater: Updater stderr" . ($useStdout ? "" : " and stdout") . ":\n[[\n", $DEBUG_DETAILS);
&Warn(&ReadFile("<$stderr"), $DEBUG_DETAILS);
&Warn("]]\n", $DEBUG_DETAILS);
}
# unlink $stderr;
if ($result) {
&Warn("FileNodeRunUpdater: UPDATER ERROR: $saveError\n");
return "";
}
my $newLM = &GenerateNewLM();
&Warn("FileNodeRunUpdater returning newLM: $newLM\n", $DEBUG_DETAILS);
return $newLM;
}
'''
############# FileNodeRunParametersFilter ##############
def FileNodeRunParametersFilter():
Warn("FileNodeRunParametersFilter not implemented")
############# RegisterWrappers ##############
def RegisterWrappers(nm):
# CheckKeys(nm)
# TODO: Wrapper registration should be done differently so that the
# framework can verify that all required properties have been set for
# a new node type, and issue a warning if not. Somehow, the framework
# needs to know what node types are being registered.
Warn("RegisterWrappers starting\n", DEBUG_DETAILS)
FileNodeRegister(nm)
ExampleHtmlNodeRegister(nm)
GraphNodeRegister(nm)
# CheckKeys(nm)
Warn("RegisterWrappers finished\n", DEBUG_DETAILS)
############# FileExists ##############
def FileExists(f):
return os.path.exists(f)
############# FileNodeRegister ##############
def FileNodeRegister(nm):
Warn("FileNodeRegister starting\n", DEBUG_DETAILS)
nm["value"]["FileNode"] = {}
nm["value"]["FileNode"]["fSerializer"] = ""
nm["value"]["FileNode"]["fDeserializer"] = ""
nm["value"]["FileNode"]["fUriToNativeName"] = UriToPath
nm["value"]["FileNode"]["fRunUpdater"] = FileNodeRunUpdater
nm["value"]["FileNode"]["fRunParametersFilter"] = FileNodeRunParametersFilter
nm["value"]["FileNode"]["fExists"] = FileExists
nm["value"]["FileNode"]["defaultContentType"] = "text/plain"
Warn("FileNodeRegister finished\n", DEBUG_DETAILS)
############# ExampleHtmlNodeRegister ##############
def ExampleHtmlNodeRegister(nm):
Warn("[WARNING] ExampleHtmlNodeRegister not implemented")
############# GraphNodeRegister ##############
def GraphNodeRegister(nm):
Warn("[WARNING] GraphNodeRegister not implemented")
############# Unique ##############
# Return the unique items in the given list (or iterator).
def Unique(oldList):
seen = {}
newList = []
for x in oldList:
if x not in seen:
newList.append(x)
seen[x] = 1
return newList
############## PrintNodeMetadata ################
def PrintNodeMetadata(nm):
nmv = nm['value'] or {}
nml = nm['list'] or {}
nmh = nm['hash'] or {}
nmm = nm['multi'] or {}
PrintLog("\nNode Metadata:\n")
allSubjects = Unique(list(nmv.keys()) + list(nml.keys()) + list(nmh.keys()) + list(nmm.keys()))
# Warn(f"Number of subjects: {len(allSubjects)}")
for s in allSubjects :
allPredicates = []
if s in nmv :
allPredicates.extend(nmv[s].keys())
if s in nml :
allPredicates.extend(nml[s].keys())
if s in nmh :
allPredicates.extend(nmh[s].keys())
if s in nmm :
allPredicates.extend(nmm[s].keys())
# foreach my $p (sort keys %allPredicates)
allPredicates = Unique(allPredicates)
for p in allPredicates :
# CheckKeys(nm)
if (s in nmv and p in nmv[s]) :
v = nmv[s][p]
PrintLog(f" {s} -> {p} -> {v}\n")
if (s in nml and p in nml[s]) :
vList = nml[s][p]
vl = " ".join(vList)
PrintLog(f" {s} -> {p} -> ({vl})\n")
if (s in nmh and p in nmh[s]) :
vHash = nmh[s][p]
# my @vHash = map {($_,vHash{$_})} sort keys %vHash;
sortedKeys = sorted(vHash.keys())
# sortedKeys and Warn(f"sortedKeys: {' '.join(sortedKeys)}")
pairs = map(lambda k: k+" "+vHash[k], sortedKeys)
vh = " ".join(pairs)
PrintLog(f" {s} -> {p} -> {{{vh}}}\n");
if (s in nmm and p in nmm[s]) :
vHash = nmm[s][p]
vHashSorted = sorted(vHash.keys())
for k in vHashSorted :
v = vHash[k]
if (v != 1) :
Die(f"BAD nmm value vHash{{{k}}}: {v}\n")
vh = " ".join(vHashSorted)
PrintLog(f" {s} -> {p} -> [{vh}]\n")
PrintLog("\n")
################### GraphToDict #####################
# Turn a graph into: s Dict -> p Dict -> o list of objects.
# If s+p only have one o value then the list will contain only one item.