-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathkernel
1499 lines (1252 loc) · 50 KB
/
kernel
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
<?xml version="1.0" encoding="UTF-8"?>
<rdf:RDF
xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
xmlns:rdfs="http://www.w3.org/2000/01/rdf-schema#"
xmlns:rdfe="http://redfoot.net/3.0/rdf#"
xmlns:code="http://redfoot.net/3.0/code#"
xmlns:command="http://redfoot.net/3.0/command#"
xmlns:kernel="http://redfoot.net/3.0/kernel#"
>
<rdfs:Resource rdf:ID="Globals">
<rdfs:label>Redfoot Globals</rdfs:label>
<rdfs:comment></rdfs:comment>
</rdfs:Resource>
<rdf:Property rdf:ID="persona">
<rdfs:label>persona</rdfs:label>
<rdfs:comment>The identity the Kernel is to use to personify itself</rdfs:comment>
<rdfs:range rdf:resource="#Kernel"/>
</rdf:Property>
<rdfs:Class rdf:ID="Admin">
<rdfs:label>Kernel Admin</rdfs:label>
<rdfs:comment></rdfs:comment>
<rdfs:subClassOf rdf:resource="kernel#Resource"/>
</rdfs:Class>
<rdfs:Class rdf:ID="Program">
<rdfs:label>Kernel Program</rdfs:label>
<rdfs:comment></rdfs:comment>
<rdfs:subClassOf rdf:resource="code#Code"/>
</rdfs:Class>
<rdfs:Class rdf:ID="OnLoad">
<rdfs:label>Kernel OnLoad Handler</rdfs:label>
<rdfs:comment></rdfs:comment>
<rdfs:subClassOf rdf:resource="code#Code"/>
</rdfs:Class>
<rdf:Description rdf:about="#">
<code:python rdf:datatype="redfoot#Python">
<![CDATA[
import redfootlib
import logging, sys
_logger = logging.getLogger()
redfootlib_version = tuple([int(x) for x in redfootlib.__version__.split(".", 2)])
REDFOOTLIB_MINIMUM = (2, 7, 0)
if redfootlib_version < REDFOOTLIB_MINIMUM:
_logger.warning("This version of the redfoot kernel is still in development.")
_logger.critical("This kernel requires redfootlib %s or greater. Found redfootlib version %s. easy_install -U redfoot==dev" % ("%s.%s.%s" % REDFOOTLIB_MINIMUM, redfootlib.__version__))
_logger.warning("If you wish to keep running with redfoot 2.1.x please run: redfoot --program=https://svn.redfoot.net/branches/2.1/kernel# --set-default")
sys.exit(-1)
]]>
</code:python>
</rdf:Description>
<code:Module rdf:ID="module">
<rdfs:label>Redfoot Kernel</rdfs:label>
<rdfs:comment>
</rdfs:comment>
<code:python rdf:datatype="http://www.w3.org/2001/XMLSchema#string">
<![CDATA[
# TODO: put in check that this is being run with boot#loader ?
import sys, logging
from datetime import datetime
from urlparse import urldefrag
from itertools import chain
from rdflib import URIRef, Literal, BNode
from rdflib import RDF, RDFS
from rdflib.Graph import Graph, ConjunctiveGraph
from rdflib.Namespace import NamespaceDict as Namespace
from rdflib.Journal import JournalReader, JournalWriter
from rdflib.events import Dispatcher, Event
from rdflib import TextIndex
# To work around rdflib 2.4.0's TextIndex indexing base64binary like
# crazy... only index on word boundaries for now.
import re
TextIndex.word_pattern = re.compile(r"(?u)\S+")
_logger = logging.getLogger("hypercode.%s" % redfoot_loader.label(__uri__))
KERNEL = Namespace(URIRef("http://redfoot.net/3.0/kernel#"))
RDFE = Namespace(URIRef("http://redfoot.net/3.0/rdf#"))
CODE = Namespace(URIRef("http://redfoot.net/3.0/code#"))
DCTERMS = Namespace(URIRef("http://purl.org/dc/elements/1.1/"))
DC = Namespace(URIRef("http://purl.org/dc/terms/"))
class Kernel(ConjunctiveGraph):
def __init__(self, store):
super(Kernel, self).__init__(store)
self.uri = __uri__ # uri to the version of redfoot that's running
self.__index = None
self.__base = None
self.__uri_map = set()
self.__namespaces = {}
self.dispatcher = Dispatcher()
self.xmpp = None
self.__globals = None
self.__text_index = None
self.map(URIRef("http://xmlns.com/foaf/0.1/"), URIRef("http://xmlns.com/foaf/0.1/index.rdf"))
def _get_crypto(self):
try:
return redfoot_loader.crypto
except NoCryptoSupport, e:
_logger.warning("No Crypto Support... flying in the clear!")
class Crypto(object):
def encrypt(self, value):
return value
def decrypt(self, value):
return value
return Crypto()
crypto = property(_get_crypto, doc="object with crypto methods")
def __get_base(self):
if self.__base is None:
self.__base = self.value(KERNEL.Globals, KERNEL.base)
if self.__base is None:
self.__base = self.absolutize("")
return self.__base
def __set_base(self, base):
self.index.set((KERNEL.Globals, KERNEL.base, base))
base = property(__get_base, __set_base)
def __get_text_index(self):
if self.__text_index is None:
self.__text_index = TextIndex.TextIndex(store="Sleepycat")
self.__text_index.open("redfoot-text_index", create=True)
self.__text_index.subscribe_to(self)
self.__text_index.link_to(self)
return self.__text_index
text_index = property(__get_text_index)
def open(self, path, rebuild=False):
_logger.debug("opening with store=%s and configuration=%s" % (self.store, path))
if rebuild==True:
_logger.info("rebuilding store from journal file...")
os.rename(path, "%s-backup-%s" % (path, date_time()))
self.open(path)
JournalReader(self.store, "%s-journal" % path)
self.close()
_logger.info("done rebuilding.")
journal = JournalWriter(self.store, filename="%s-journal" % path)
super(Kernel, self).open(path, create=True)
self.text_index # so that we hook up the text indexing... may want to move this, but for now hard code it here
onLoadHandlers = []
for uri in self.instances(KERNEL.OnLoad):
rank = self.value(uri, KERNEL.onLoadRank) or 0
onLoadHandlers.append((rank, uri))
onLoadHandlers.sort()
_logger.info("TODO: replace onLoadRank with info about which depend on which. a depends on b, etc.")
_logger.debug("onLoadHandlers: %s" % onLoadHandlers)
for rank, uri in onLoadHandlers:
try:
self.execute(uri, redfoot=self)
except Exception, e:
_logger.info("While trying to execute %s" % uri)
_logger.exception(e)
def close(self, commit_pending_transaction=False):
super(Kernel, self).close(commit_pending_transaction=commit_pending_transaction)
self.text_index.close(commit_pending_transaction=commit_pending_transaction)
def _get_globals(self):
if self.__globals is None:
self.__globals = {"redfoot": self,
"RDF": RDF, "RDFS": RDFS,
#"REDFOOT": self.namespace("http://redfoot.net/"),
#"BNode": BNode,
"URIRef": URIRef, "Literal": Literal}
return self.__globals
globals = property(_get_globals)
def __get_index(self):
if self.__index is None:
self.__index = Graph() # To stop recursion
self.__index = self.get_context(URIRef("#index", base=__uri__), creator=__uri__)
return self.__index
index = property(__get_index, doc="context where redfoot stores data about contexts")
def get_context(self, identifier, creator=None):
""" Returns a Context graph for the given identifier, which
must be a URIRef or BNode."""
result = Graph(store=self.store, identifier=identifier, namespace_manager=self)
self.index.remove((identifier, RDF.type, KERNEL.DeletedContext))
self.index.add((identifier, RDF.type, KERNEL.Context))
if creator and not (identifier, DCTERMS.creator, None) in self.index:
self.index.add((identifier, DCTERMS.creator, creator))
if (identifier, DC.created, None) not in self.index:
self.index.add((identifier, DC.created, Literal(datetime.utcnow())))
return result
def remove_context(self, context):
"""removes both the context and metadata about the context."""
if isinstance(context, URIRef) or isinstance(context, BNode):
context = self.get_context(context)
self.index.remove((context.identifier, None, None))
self.index.add((context.identifier, RDF.type, KERNEL.DeletedContext))
super(Kernel, self).remove_context(context)
def map(self, logical, physical):
"""Map all URIRefs starting with logical to corresponding ones starting with physical."""
_logger.info("mapping %s -> %s" % (logical, physical))
# TODO: sanity checks
self.__uri_map.add((logical, physical))
def physical(self, uri):
"Concert from logical uri to physical uri"
for logical, physical in self.__uri_map:
if uri.startswith(logical):
return URIRef(uri.replace(logical, physical, 1))
return uri
def logical(self, uri):
"Concert from physical uri to logical uri"
for logical, physical in self.__uri_map:
if uri.startswith(physical):
return URIRef(uri.replace(physical, logical, 1))
return uri
def label(self, subject, default=''):
# TODO: push this subproperty support back down into rdflib
label = super(Kernel, self).label(subject, None)
if label is None:
for subproperty in self.transitive_subjects(RDFS.subPropertyOf, RDFS.label):
label = self.value(subject, subproperty, default=None, any=True)
if label is not None:
return label
return label or default
def check(self, uri, creator=None):
"""
Checks to see if redfoot knows anything about uri
Currently, if not, Kernel will attempt to load from uri.
"""
if isinstance(uri, URIRef):
_logger.debug("checking %s" % uri)
location = uri.defrag()
context_uri = self.context_id(location)
if not (context_uri, RDF.type, KERNEL.Context) in self.index:
# request the context so it gets created thus avoiding recursion
self.get_context(context_uri, creator=creator)
try:
self.load(location, creator=creator)
except Exception, e:
_logger.warning("couldn't load %s while checking: %s\n" % (uri, e))
else:
_logger.warning("%r is not an instance of rdflib.URIRef\n" % uri)
#raise ValueError("wrong type")
return (uri, None, None) in self
def load(self, location, format="xml", publicID=None, creator=None, scutter=False):
"""
location is a relative or absolute URI
publicID if specified will override location as the xml:base
contextID
"""
if "#" in location:
location = URIRef(urldefrag(location)[0])
location = self.physical(location)
publicID = publicID or self.absolutize(location)
publicID = self.absolutize(publicID, defrag=False)
publicID = self.logical(publicID)
context_id = self.context_id(publicID)
context = self.get_context(context_id, creator=creator)
absolute_location = self.absolutize(location)
context.remove((None, None, None))
logical = self.logical(location)
_logger.info("loading: %s" % logical)
if logical!=location:
_logger.info(" from: %s" % location)
context.load(absolute_location, publicID=publicID, format=format)
self.index.remove((context_id, RDFE.source, None))
self.index.add((context_id, RDFE.source, location))
self.index.remove((context_id, RDFE.publicID, None))
self.index.add((context_id, RDFE.publicID, publicID))
if (context_id, RDFS.label, None) not in self:
label = self.label(URIRef("#", base=publicID))
if label:
self.index.add((context_id, RDFS.label, label))
if format=="xml":
self.index.add((publicID.defrag(), RDF.type, URIRef("http://redfoot.net/3.0/rdf#RDFXMLDocument")))
return context
def module(self, uri, check_cache=True):
if not isinstance(uri, URIRef):
uri = URIRef(uri)
self.check(uri)
module_name = uri
if check_cache:
module = sys.modules.get(module_name, None)
if module:
return module
_logger.info("creating module for: %s" % uri)
import types
safe_module_name = "__uri___%s" % hash(uri)
module = types.ModuleType(safe_module_name)
module.__name__ = module_name
module.__file__ = uri
module.__ispkg__ = 0
sys.modules[module_name] = module
module.__dict__.update(self.globals)
self.execute(uri, context=module.__dict__)
return module
# _logger.debug("creating module: %s" % this.__uri__)
# module_name = this.__uri__
# if (uri, RDF.type, CODE.PythonModule) not in self:
# _logger.warning("%r not of type CODE.PythonModule" % uri)
# this = self.instance(uri, type=CODE.PythonModule)
# return this
def instance(self, uri, type=None):
class Object(object):
def __repr__(self):
return "<Redfoot Module %s %s>" % (id(self), dir(self))
this = Object()
this.execute = self.execute
this.__uri__ = uri
if type:
types = [type]
else:
types = self.objects(uri, RDF.type)
for type in types:
constructor = self.value(type, CODE.constructor)
if constructor is None:
raise ValueError("Didn't find constructor for %s" % type)
self.execute(constructor, this=this)
return this
def execute(self, uri, context=None, **args):
if self.check(uri):
if CODE.Code not in self.types(uri):
_logger.warning("%s not of type CODE.Code" % uri)
_logger.debug(" types: %s" % list(self.types(uri)))
for other in self.objects(uri, RDFS.seeAlso):
self.check(other)
value = self.value(uri, CODE.python)
if value is None:
raise Exception("Couldn't execute %s (has no CODE.python)" % uri)
if context==None:
context = dict(self.globals)
for k, v in args.items():
context[k] = v
context["__uri__"] = uri
from types import CodeType
if isinstance(value, CodeType):
_logger.info("Wheeee: %s", uri)
exec value in context
else:
value = value.replace("\r\n", "\n")
value = value.replace("\r", "\n")
c = compile(value+"\n", uri, "exec")
exec c in context
return context
else:
raise Exception("Couldn't execute %s (nothing known about resource)" % uri)
def context_id(self, uri, context_id=None):
""" URI#context """
uri, frag = urldefrag(uri)
frag = context_id or frag or "context"
if frag.startswith("#"):
frag = frag[1:]
if uri.endswith("/"):
uri = uri[:-1]
return URIRef("%s#%s" % (uri, frag))
def namespace(self, uri, creator=None, context=None):
uri = URIRef(uri)
namespace = self.__namespaces.get(uri)
if namespace is None:
if context is None:
self.check(uri, creator=creator)
context_uri = self.context_id(uri)
context = self.get_context(context_uri, creator=creator)
namespace = Namespace(uri, context)
self.__namespaces[uri] = namespace
return namespace
def bind(self, prefix, namespace, override=True):
"""
Override Graphs bind to additionally declare the namespace to
be of RDF.type RDFE.Namespce. And to load it if it's not
already been loaded.
"""
namespace = URIRef(namespace)
if not (namespace, RDF.type, RDFE.Namespace) in self.index:
try:
self.check(namespace)
except Exception, e:
_logger.exception(e)
self.index.add((namespace, RDF.type, RDFE.Namespace))
super(Kernel, self).bind(prefix, namespace, override)
def write(self, s, encoding="utf-8"):
sys.stdout.write(s.encode(encoding))
def subclasses(self, uri, direct=True):
"""
Applies brute force RDFS entailment to infer additional classification
"""
if uri==RDFS.Resource:
# TODO: direct=False
for subclass in self.subjects(RDF.type, RDFS.Class):
for c in self.objects(subclass, RDFS.subClassOf):
if c==RDFS.Resource or not (c, RDF.type, RDFS.Class) in self:
yield subclass
break
return
if direct==True:
for subclass in self.subjects(RDFS.subClassOf, uri):
yield subclass
else:
seen = set()
for subclass in self.transitive_subjects(RDFS.subClassOf, uri):
if subclass not in seen:
seen.add(subclass)
yield subclass
def instances(self, uri):
seen = set()
for instance in self.subjects(RDF.type, uri):
if instance not in seen:
seen.add(instance)
yield instance
for subclass in self.subclasses(uri, direct=False):
for instance in self.subjects(RDF.type, subclass):
if instance not in seen:
seen.add(instance)
yield instance
def types(self, subject):
"""
generator over the types of subject ordered from most specific to least
Applies brute force RDFS entailment to infer additional classification
"""
seen = set()
l = []
for type in self.objects(subject, RDF.type):
for t in self.transitive_objects(type, RDFS.subClassOf):
num = len(list(self.transitive_objects(t, RDFS.subClassOf)))
if t not in seen:
seen.add(t)
l.append((num, t))
if isinstance(subject, URIRef):
for type in self.objects(subject.abstract(), RDF.type):
for t in self.transitive_objects(type, RDFS.subClassOf):
num = len(list(self.transitive_objects(t, RDFS.subClassOf)))
if t not in seen:
seen.add(t)
l.append((num, t))
l.sort()
l.reverse()
for num, type in l:
yield type
def possible_properties(self, type):
for object in self.transitive_objects(type, RDFS.subClassOf):
for subject in self.subjects(RDFS.domain, object):
for property in self.transitive_subjects(RDFS.subPropertyOf, subject):
yield property
def possible_properties_for_subject(self, subject):
seen = set()
for type in chain([RDFS.Resource], self.objects(subject, RDF.type)):
for property in self.possible_properties(type):
if not property in seen:
seen.add(property)
yield property
def getLogger(self, uri):
return logging.getLogger("hypercode.%s" % self.label(uri) or uri)
]]>
</code:python>
</code:Module>
<kernel:Program rdf:ID="runner">
<rdfs:label>Command Runner</rdfs:label>
<code:python rdf:datatype="http://www.w3.org/2001/XMLSchema#string">
<![CDATA[
import logging
_logger = logging.getLogger(__uri__)
CODE = redfoot.namespace(URIRef("http://redfoot.net/3.0/code#"))
COMMAND = redfoot.namespace(URIRef("http://redfoot.net/3.0/command#"))
commands = {}
for command in redfoot.instances(COMMAND.Command):
redfoot.check(command)
label = redfoot.label(command)
commands[label] = command
# TODO: command line parsing and usage
if not args:
args = [""]
command = args[0]
# find code object by label or full URIRef
code = commands.get(command, URIRef(command))
if code:
redfoot.execute(code, stdout=redfoot, stderr=redfoot, args=args[1:])
else:
if command:
redfoot.write("Command '%s' not found.\n" % command)
command_list = commands.keys()
command_list.sort()
redfoot.write("available commands: \n %s\n" % ", ".join(command_list))
]]>
</code:python>
</kernel:Program>
<command:Command rdf:ID="load">
<rdfs:label>load</rdfs:label>
<code:python rdf:datatype="http://www.w3.org/2001/XMLSchema#string">
<![CDATA[
if len(args)==0 or len(args)>3:
print "usage: ./redfoot.py load <uri> [<publicID>]"
else:
import os
from urllib import pathname2url
from urlparse import urljoin
url = URIRef(args[0], base="%s/" % urljoin("file:", pathname2url(os.getcwd())))
try:
publicID = URIRef(redfoot.absolutize(args[1], defrag=False))
except:
publicID = None
print "loading: %s" % url
if publicID:
print " with publicID: %s" % publicID
redfoot.load(url, publicID=publicID, creator=__uri__)
]]>
</code:python>
</command:Command>
<command:Command rdf:ID="run_tests">
<rdfs:label>run_tests</rdfs:label>
<code:python rdf:datatype="http://www.w3.org/2001/XMLSchema#string">
<![CDATA[
_logger = redfoot.getLogger(__uri__)
from optparse import OptionParser
parser = OptionParser("""This command is for running tests on hypercode.""")
try:
options, args = parser.parse_args(args)
except SystemExit, e:
pass
else:
for uri, _, value in redfoot.triples((None, RDF.value, None)):
if isinstance(value, Literal):
_logger.warning("%s has an old RDF.value of datatype REDFOOT.Python" % uri)
]]>
</code:python>
</command:Command>
<command:Command rdf:ID="update_text_index">
<rdfs:label>update_text_index</rdfs:label>
<code:python rdf:datatype="redfoot#Python">
<![CDATA[
from optparse import OptionParser
parser = OptionParser("""
Update the text index""")
try:
options, args = parser.parse_args(args)
except SystemExit, e:
pass
else:
redfoot.text_index.index_graph(redfoot)
]]>
</code:python>
</command:Command>
<command:Command rdf:ID="set_base">
<rdfs:label>set_base</rdfs:label>
<code:python rdf:datatype="redfoot#Python">
<![CDATA[
from optparse import OptionParser
parser = OptionParser("""
This command is for adding a Redfoot user and expects one argument, the user identifier.""")
parser.add_option("--password", dest="password", help="password for the admin being added")
parser.add_option("--xmpp_id", dest="xmpp_id", help="xmpp_id for the admin being added")
try:
options, args = parser.parse_args(args)
done = False
except SystemExit, e:
done = True
#else:
if not done:
if len(args)==1:
redfoot.base = URIRef(args[0])
stdout.write("kernel base set to %s\n" % redfoot.base)
else:
stdout.write("No base identifier specified.\n")
parser.print_help()
]]>
</code:python>
</command:Command>
<command:Command rdf:ID="user_add">
<rdfs:label>user_add</rdfs:label>
<rdfs:comment>Example:
redfoot add_user [email protected] --password --digest-only --id=/users/user/eikeon# --full-name="Daniel Krech"
</rdfs:comment>
<code:python rdf:datatype="redfoot#Python">
<![CDATA[
from getpass import getpass
from optparse import OptionParser
import sha
_logger = redfoot.getLogger(__uri__)
KERNEL = redfoot.namespace("http://redfoot.net/3.0/kernel#")
USER = redfoot.namespace("http://redfoot.net/3.0/user#")
FOAF = redfoot.namespace("http://xmlns.com/foaf/0.1/")
XMPP = redfoot.namespace("http://redfoot.net/3.0/xmpp#")
parser = OptionParser("""This command is for adding a Redfoot user and expects one argument, the user@host.""")
parser.add_option("--full-name", dest="full_name", help="full name of user being added")
parser.add_option("--password", dest="password", help="password for the user being added")
parser.add_option("--digest-only", dest="digest_only", action="store_true",
help="""Only store digests of password. Otherwise also stores an encrypted version of the password as well.""")
parser.add_option("--xmpp_id", dest="xmpp_id", help="add additional xmpp_id")
parser.add_option("--admin", dest="admin", action="store_true", help="add additional xmpp_id")
parser.add_option("--kernel", dest="kernel", action="store_true", help="persona of kernel")
parser.set_defaults(password=None)
try:
options, args = parser.parse_args(args)
except SystemExit, e:
pass
else:
if len(args)==1:
username, hostname = args[0].split("@", 1)
uri = URIRef("/users/%s#" % username, base=redfoot.base)
c = redfoot.get_context((URIRef("#context", base=uri)), creator=__uri__)
full_name = options.full_name or username
c.add((uri, RDFS.label, Literal(full_name)))
c.add((uri, RDF.type, USER.User))
c.add((uri, FOAF.mbox, URIRef("mailto:%s@%s" % (username, hostname))))
c.add((uri, XMPP.uid, URIRef("xmpp:%s@%s" % (username, hostname))))
if options.admin:
c.add((uri, RDF.type, KERNEL.Admin))
if options.kernel:
c.set((redfoot.uri, KERNEL.persona, uri))
if options.xmpp_id:
xmpp_id = options.xmpp_id
if not xmpp_id.startswith("xmpp:"):
xmpp_id = "xmpp:%s" % xmpp_id
c.add((uri, XMPP.uid, URIRef("%s" % xmpp_id)))
if options.password is not None:
if options.password=="":
password = getpass("password:")
try:
e = redfoot.crypto.encrypt(password)
except Exception, e:
_logger.warning("Couldn't store encrypted password: %s" % e)
else:
from base64 import b64encode, b64decode
base64Binary = URIRef("http://www.w3.org/2001/XMLSchema#base64Binary")
value = Literal(b64encode(e), datatype=base64Binary)
_logger.info("%r" % value)
ee = b64decode(value)
assert ee==e, "%r!=%r" % (ee, e)
c.set((uri, USER.encrypted_password, value))
password = Literal(password.strip())
hexdigest = Literal(sha.new(password).hexdigest())
c.set((uri, USER.hexdigest, hexdigest))
_logger.debug("\nassertions added:\n%s" % c.serialize(format="n3"))
stdout.write("added user with identifier '%s'\n" % uri)
else:
stdout.write("%prog expects one argument, the user@host.\n")
parser.print_help()
]]>
</code:python>
</command:Command>
<kernel:OnLoad rdf:about="#xmpp_authentication">
<kernel:onLoadRank rdf:datatype="http://www.w3.org/2001/XMLSchema#float">9.0</kernel:onLoadRank>
<rdfs:label>XMPP Authentication</rdfs:label>
<rdfs:comment></rdfs:comment>
<code:python rdf:datatype="redfoot#Python">
<![CDATA[
_logger = redfoot.getLogger(__uri__)
KERNEL = redfoot.namespace("http://redfoot.net/3.0/kernel#")
USER = redfoot.namespace("http://redfoot.net/3.0/user#")
XMPP = redfoot.namespace("http://redfoot.net/3.0/xmpp#")
xmpp = redfoot.module(URIRef("http://redfoot.net/3.0/xmpp#client"))
persona = redfoot.value(redfoot.uri, KERNEL.persona)
if persona:
xmpp_id = redfoot.value(persona, XMPP.uid)
ep = redfoot.value(persona, USER.encrypted_password)
if ep is None:
raise Exception("no encrypted password")
from base64 import b64decode
xmpp_password = redfoot.crypto.decrypt(b64decode(ep))
if xmpp_id and xmpp_password:
redfoot.xmpp = xmpp.Client(xmpp_id, xmpp_password)
import logging
xmpp_logging = redfoot.module(URIRef("http://redfoot.net/3.0/xmpp#logging"))
_root_logger = logging.getLogger()
_xmpp_handler = xmpp_logging.XMPPHandler(KERNEL.Admin)
_xmpp_formatter = logging.Formatter('[%(name)s] %(message)s')
_xmpp_handler.setFormatter(_xmpp_formatter)
_root_logger.addHandler(_xmpp_handler)
]]>
</code:python>
</kernel:OnLoad>
<command:Command rdf:ID="test_module">
<rdfs:label>test_module</rdfs:label>
<code:python rdf:datatype="redfoot#Python">
<![CDATA[
]]>
</code:python>
</command:Command>
<command:Command rdf:ID="run">
<rdfs:label>run</rdfs:label>
<rdfs:comment>Run the twisted event loop</rdfs:comment>
<code:python rdf:datatype="redfoot#Python">
<![CDATA[
_logger = redfoot.getLogger(__uri__)
_logger.info("Running twisted's event loop")
try:
import twisted
except ImportError, e:
raise ImportError("Twisted not installed. Please install Twisted-2.5.0 ( http://twistedmatrix.com/trac/#Downloading )")
from twisted.internet import reactor
try:
try:
reactor.run()
except ValueError:
reactor.run(installSignalHandlers=0)
except KeyboardInterrupt: # TODO:
_logger.info("Shutting down twisted's event loop")
reactor.shutdown()
]]>
</code:python>
</command:Command>
<command:Command rdf:ID="save">
<rdfs:label>save</rdfs:label>
<code:python rdf:datatype="http://www.w3.org/2001/XMLSchema#string">
<![CDATA[
RDFE = redfoot.namespace("http://redfoot.net/3.0/rdf#")
for arg in args:
print "saveing: %s" % arg
source = URIRef(redfoot.absolutize(arg))
print "source:", source
for cid, _, source in redfoot.index.triples((None, RDFE.source, source)):
context = redfoot.get_context(cid)
context.save(source, format="pretty-xml")
print "saved:", source, len(context)
]]>
</code:python>
</command:Command>
<command:Command rdf:ID="print">
<rdfs:label>print</rdfs:label>
<code:python rdf:datatype="http://www.w3.org/2001/XMLSchema#string">
<![CDATA[
import sys
for arg in args:
cid = redfoot.absolutize(arg, defrag=0)
print cid
context = redfoot.get_context(cid)
context.serialize(format="pretty-xml", destination=sys.stdout)
]]>
</code:python>
</command:Command>
<command:Command rdf:ID="serialize">
<rdfs:label>serialize</rdfs:label>
<code:python rdf:datatype="http://www.w3.org/2001/XMLSchema#string">
<![CDATA[
_logger = redfoot.getLogger(__uri__)
import sys
from rdflib.Graph import Graph
prefix = redfoot.absolutize(args[0], defrag=0)
if len(args)>1:
base = redfoot.absolutize(args[1])
else:
base = prefix
out = Graph(namespace_manager=redfoot.namespace_manager)
for cid in redfoot.contexts():
if cid.identifier.startswith(prefix):
c = redfoot.get_context(cid.identifier)
out += c
out.serialize(destination=sys.stdout, base=base)
]]>
</code:python>
</command:Command>
<command:Command rdf:ID="contexts">
<rdfs:label>contexts</rdfs:label>
<code:python rdf:datatype="http://www.w3.org/2001/XMLSchema#string">
<![CDATA[
RDFE = redfoot.namespace("http://redfoot.net/3.0/rdf#")
for context in redfoot.contexts():
try:
cid = context.identifier
source = redfoot.index.value(cid, RDFE.source)
if source is None or cid.startswith(source):
redfoot.write(cid+"\n")
else:
print "%s\n source: %s" % (cid, source) #, len(redfoot.get_context(cid))
except Exception, e:
print cid, e
]]>
</code:python>
</command:Command>
<command:Command rdf:ID="remove_context">
<rdfs:label>remove_context</rdfs:label>
<code:python rdf:datatype="http://www.w3.org/2001/XMLSchema#string">
<![CDATA[
RDFE = redfoot.namespace("http://redfoot.net/3.0/rdf#")
for arg in args:
if arg.startswith("_"):
uri = BNode(arg[1:])
else:
uri = URIRef(redfoot.absolutize(arg, defrag=0))
for context in redfoot.contexts():
if uri== context.identifier:
print "removing:", uri
redfoot.remove_context(context)
for cid in redfoot.index.subjects(RDFE.source, uri):
print "removing: %s\n source: %s" % (cid, uri)
redfoot.remove_context(redfoot.get_context(cid))
]]>
</code:python>
</command:Command>
<command:Command rdf:ID="reload">
<rdfs:label>reload</rdfs:label>
<code:python rdf:datatype="http://www.w3.org/2001/XMLSchema#string">
<![CDATA[
RDFE = redfoot.namespace("http://redfoot.net/3.0/rdf#")
import logging
_logger = redfoot.getLogger(__uri__)
from optparse import OptionParser
parser = OptionParser("""
This command is for reloading all redfoot contexts that start with a prefix.""")
parser.add_option("--ignore-source", action="store_true", dest="ignore_source", help="ignore-source when reloading ")
try:
options, args = parser.parse_args(args)
done = False
except SystemExit, e:
done = True
if not done:
from rdflib import exceptions
# usage reload all contexts starting with prefix (first arg)... defaults to all contexts
try:
prefix = args[0]
except:
prefix = ""
prefix = redfoot.absolutize(prefix, defrag=False)
DC_creator = URIRef("http://purl.org/dc/elements/1.1/creator")
for context in redfoot.contexts():
cid = context.identifier
if cid.startswith(prefix):
try:
if options.ignore_source:
source = cid
else:
source = redfoot.index.value(cid, RDFE.source)
except exceptions.UniquenessError, e:
_logger.warning("Multiple sources for %s: %s" % (cid, list(redfoot.objects(cid, RDFE.source))))
source = None
if source is not None:
publicID = redfoot.index.value(cid, RDFE.publicID, any=True)
if cid.startswith(source):
print "reloading: %s" % (cid,)
else:
print "reloading: %s\n source: %s" % (cid, source)
redfoot.load(source, publicID=publicID)
]]>
</code:python>
</command:Command>
<command:Command rdf:ID="save_all">
<rdfs:label>save_all</rdfs:label>
<code:python rdf:datatype="http://www.w3.org/2001/XMLSchema#string">
<![CDATA[
RDFE = redfoot.namespace("http://redfoot.net/3.0/rdf#")
for cid, _, source in redfoot.index.triples((None, RDFE.source, None)):
if source:
print "saving %s" % source
try:
context = redfoot.get_context(cid)
context.save(source, format="pretty-xml")
except Exception, e:
print e
]]>
</code:python>
</command:Command>
<command:Command rdf:ID="auto_reload">
<rdfs:label>auto_reload</rdfs:label>
<code:python rdf:datatype="http://www.w3.org/2001/XMLSchema#string">
<![CDATA[
RDFE = redfoot.namespace("http://redfoot.net/3.0/rdf#")
DC = redfoot.namespace("http://purl.org/dc/elements/1.1/")