forked from hepix-virtualisation/vmcatcher
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathvmcatcher_subscribe
executable file
·1274 lines (1164 loc) · 52.7 KB
/
vmcatcher_subscribe
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 python
import sys
if sys.version_info < (2, 4):
print "Your python interpreter is too old. Please consider upgrading."
sys.exit(1)
if sys.version_info < (2, 5):
import site
import os.path
from distutils.sysconfig import get_python_lib
found = False
module_dir = get_python_lib()
for name in os.listdir(module_dir):
lowername = name.lower()
if lowername[0:10] == 'sqlalchemy' and 'egg' in lowername:
sqlalchemy_dir = os.path.join(module_dir, name)
if os.path.isdir(sqlalchemy_dir):
site.addsitedir(sqlalchemy_dir)
found = True
break
if not found:
print "Could not find SQLAlchemy installed."
sys.exit(1)
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from sqlalchemy.exc import IntegrityError, DatabaseError, ProgrammingError
import vmcatcher.databaseDefinition as model
import os
import re
import logging
import optparse
from smimeX509validation import TrustStore, LoadDirChainOfTrust,smimeX509validation, smimeX509ValidationError
from vmcatcher.__version__ import version
import vmcatcher
import urllib2
import urllib
import hashlib
import datetime
import uuid
from hepixvmitrust.vmitrustlib import VMimageListDecoder as VMimageListDecoder
from hepixvmitrust.vmitrustlib import time_format_definition as time_format_definition
try:
import simplejson as json
except:
import json
# command line error codes.
# 10 failed to download image list.
# 11 failed to validate image list.
# 12 metadata and certificate dont match.
# 13 Endorser not authorised on subscription.
# 14 trust anchor missing
# 15 Database integrity error.
# 16 New version number is same as old version number.
# 17 New version number is less than old version number.
# 31 imagelist dc:identifier invalid.
# 32 image dc:identifier invalid.
# 33 imagelist dc:date:created invalid.
# 34 image has missing parameters in the message.
# 35 image has missing parameters in the message.
# 36 image is not registeresd with subscription.
# 37 Message was not valid JSON.
# 38 Message JSON was not valid to build image list.
regdelexp = re.compile('[-,.\/]')
regnumeric = re.compile('[0-9]+')
def split_line_by_delimiter(line,regex):
splitline = []
splititr = regex.finditer(line)
lstart = 0
for i in splititr:
(mstart,mend) = i.span()
if lstart != mstart:
splitline.append(line[lstart:mstart])
splitline.append(line[mstart:mend])
lstart = mend
linelen = len(line)
if lstart != linelen:
splitline.append(line[lstart:linelen])
return splitline
def string_sort(x,y):
xsplit = split_line_by_delimiter(x,regnumeric)
ysplit = split_line_by_delimiter(y,regnumeric)
ysplitlen = len(ysplit)
xsplitlen = len(xsplit)
minsplitlen = ysplitlen
if xsplitlen < ysplitlen:
minsplitlen = xsplitlen
for i in range(minsplitlen):
if xsplit[i] == ysplit[i]:
continue
if (xsplit[i].isdigit() and ysplit[i].isdigit()):
rc = int(0)
if int(xsplit[i]) > int(ysplit[i]):
rc = -1
if int(xsplit[i]) < int(ysplit[i]):
rc = 1
return rc
if xsplit[i].isdigit():
return -1
if ysplit[i].isdigit():
return 1
if xsplit[i] > ysplit[i]:
return -1
if xsplit[i] < ysplit[i]:
return 1
if xsplitlen < ysplitlen:
return 1
if xsplitlen > ysplitlen:
return -1
return 0
def split_numeric_sort(x, y):
xsplit = split_line_by_delimiter(x,regdelexp)
ysplit = split_line_by_delimiter(y,regdelexp)
ysplitlen = len(ysplit)
xsplitlen = len(xsplit)
minsplitlen = ysplitlen
if xsplitlen < ysplitlen:
minsplitlen = xsplitlen
for i in range(minsplitlen):
if xsplit[i] == ysplit[i]:
continue
if (xsplit[i].isdigit() and ysplit[i].isdigit()):
rc = int(0)
if int(xsplit[i]) > int(ysplit[i]):
rc = -1
if int(xsplit[i]) < int(ysplit[i]):
rc = 1
return rc
if xsplit[i].isdigit():
return -1
if ysplit[i].isdigit():
return 1
rc = string_sort(xsplit[i],ysplit[i])
if rc != 0:
return rc
if xsplitlen < ysplitlen:
return 1
if xsplitlen > ysplitlen:
return -1
return 0
class EventObj(object):
def __init__(self,eventExecutionString):
self.eventExecutionString = eventExecutionString
self.env = os.environ
self.log = logging.getLogger("Events")
def launch(self,env):
process = subprocess.Popen([self.eventExecutionString], shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE,env=env)
processRc = None
handleprocess = True
counter = 0
stdout = ''
stderr = ''
timeout = 10
while handleprocess:
counter += 1
cout,cerr = process.communicate()
stdout += cout
stderr += cerr
process.poll()
processRc = process.returncode
if processRc != None:
break
if counter == timeout:
os.kill(process.pid, signal.SIGQUIT)
if counter > timeout:
os.kill(process.pid, signal.SIGKILL)
processRc = -9
break
time.sleep(1)
return (processRc,stdout,stderr)
def eventProcess(self,EventStr,metadata):
# Note keys 'sha512', 'uuid','size' are depricated.
mappingdict = {'sha512' : 'VMCATCHER_EVENT_SL_CHECKSUM_SHA512',
'uuid' : 'VMCATCHER_EVENT_DC_IDENTIFIER',
'size' : 'VMCATCHER_EVENT_HV_SIZE',
'sha512' : 'VMCATCHER_EVENT_SL_CHECKSUM_SHA512',
# End of depricated options
'filename' : 'VMCATCHER_EVENT_FILENAME',
'dc:identifier' : 'VMCATCHER_EVENT_DC_IDENTIFIER',
'hv:uri' : 'VMCATCHER_EVENT_HV_URI',
'hv:size' : 'VMCATCHER_EVENT_HV_SIZE',
'dc:description' : 'VMCATCHER_EVENT_DC_DESCRIPTION',
'dc:title' : 'VMCATCHER_EVENT_DC_TITLE',
'hv:hypervisor' : 'VMCATCHER_EVENT_HV_HYPERVISOR',
'hv:version' : 'VMCATCHER_EVENT_HV_VERSION',
'sl:arch' : 'VMCATCHER_EVENT_SL_ARCH',
'sl:comments' : 'VMCATCHER_EVENT_SL_COMMENTS',
'sl:os' : 'VMCATCHER_EVENT_SL_OS',
'sl:osversion' : 'VMCATCHER_EVENT_SL_OSVERSION',
'sl:checksum:sha512' : 'VMCATCHER_EVENT_SL_CHECKSUM_SHA512'}
newEnv = self.env
newEnv['VMCATCHER_EVENT_TYPE'] = EventStr
for key in mappingdict.keys():
if key in metadata.keys():
newEnv[str(mappingdict[key])] = str(metadata[key])
rc,stdout,stderr = self.launch(newEnv)
if rc == 0:
self.log.debug("event '%s' executed '%s'" % (newEnv['VMCATCHER_EVENT_TYPE'],self.eventExecutionString))
self.log.debug("stdout=%s" % (stdout))
self.log.debug("stderr=%s" % (stderr))
else:
self.log.error("Event '%s' executed '%s' with exit code '%s'." % (newEnv['VMCATCHER_EVENT_TYPE'],self.eventExecutionString,rc))
self.log.info("stdout=%s" % (stdout))
self.log.info("stderr=%s" % (stderr))
return
def eventImageNew(self,metadata):
self.eventProcess("ImageNew",metadata)
class db_actions(object):
def __init__(self,session):
self.session = session
self.log = logging.getLogger("db_actions")
def endorser_get(self,metadata):
return self.session.query(model.Endorser).\
filter(model.Endorser.id==model.EndorserPrincible.id).\
filter(model.EndorserPrincible.hv_dn==metadata[u'hv:dn']).\
filter(model.EndorserPrincible.hv_ca==metadata[u'hv:ca'])
def endorser_create(self,metadata):
hv_dn_str = metadata[u'hv:dn']
gotquery = self.session.query(model.Endorser).\
filter(model.Endorser.id==model.EndorserPrincible.id).\
filter(model.EndorserPrincible.hv_dn==metadata[u'hv:dn'])
if gotquery.count() != 0:
return gotquery
newlist = model.Endorser(metadata)
self.session.add(newlist)
self.session.commit()
new_endorser = model.EndorserPrincible(newlist.id,metadata)
self.session.add(new_endorser)
self.session.commit()
return self.endorser_get(metadata)
def subscription_get(self,metadata):
subscriptionlist = self.session.query(model.Subscription).\
filter(model.Subscription.uri==metadata[u'hv:uri'])
return subscriptionlist
def subscription_create(self,metadata,authorised):
subscription_query = self.subscription_get(metadata)
if subscription_query.count() > 0:
return subscription_query
endorser_list = self.endorser_get(metadata)
if endorser_list.count() == 0:
return subscription_query
endorser = endorser_list.one()
endorserId = int(endorser.id)
new_subscription = model.Subscription(metadata)
# We will make the new subscription enabled by default
new_subscription.authorised = True
self.session.add(new_subscription)
self.session.commit()
new_auth = model.SubscriptionAuth(new_subscription.id,endorser.id,authorised)
self.session.add(new_auth)
try:
self.session.commit()
except IntegrityError,E:
self.log.error("Database integrity error '%s' while subscribing to '%s'." % (E.args,metadata))
self.log.debug(E.params)
self.session.rollback()
return self.subscription_get(metadata)
def ImageDefinition_get(self,subscriptionKey,metadata):
subscriptionlist = self.session.query(model.ImageDefinition).\
filter(model.ImageDefinition.identifier == metadata[u'dc:identifier'])
return subscriptionlist
def ImageDefinition_create(self,subscriptionKey,metadata):
ImageDefinitionQuery = self.ImageDefinition_get(subscriptionKey,metadata)
if ImageDefinitionQuery.count() > 0:
return ImageDefinitionQuery
newlist = model.ImageDefinition(subscriptionKey,metadata)
self.session.add(newlist)
self.session.commit()
ImageDefinitionQuery = self.ImageDefinition_get(subscriptionKey,metadata)
return ImageDefinitionQuery
def ImageDefinition_list(self,subscriptionKey):
imagedefList = self.session.query(model.ImageDefinition).\
filter(model.ImageDefinition.subscription==subscriptionKey)
return imagedefList
class queryby_base(object):
""""Base class for querying subscriptions"""
def __init__(self,session):
self.session = session
def subscription_by_id(self,private_id):
subscriptionlist = self.session.query(model.Subscription).\
filter(model.Subscription.id==private_id)
return subscriptionlist
def subscription_by_uri(self,uri):
subscriptionlist = self.session.query(model.Subscription).\
filter(model.Subscription.uri==uri)
return subscriptionlist
def subscription_by_uuid(self,uuid):
subscriptionlist = self.session.query(model.Subscription).\
filter(model.Subscription.identifier==uuid)
return subscriptionlist
def imagelist_by_id(self,private_id):
subscriptionlist = self.session.query(model.ImageListInstance).\
filter(model.ImageListInstance.id==private_id)
return subscriptionlist
# Now the virtual class
def subscription_get(self,by_id):
return self.subscription_by_id(private_id)
class queryby_uri(queryby_base):
def subscription_get(self,url):
return self.subscription_by_uri(url)
class queryby_uuid(queryby_base):
def subscription_get(self,uuid):
return self.subscription_by_uuid(uuid)
class output_driver_base(object):
def __init__(self,file_pointer,session,anchor):
self.session = session
self.log = logging.getLogger("db_actions")
self.file_pointer = file_pointer
self.anchor = anchor
def display_subscription_imagelist(self,subscription,imagelist):
status = None
self.display_subscription(subscription)
self.display_imagelist(imagelist)
return True
def display_subscription(self,subscription):
pass
def display_imagelist(self,imagelist):
pass
def subscriptions_lister(self):
pass
def display_image_def(self,subscription):
pass
class output_driver_smime(output_driver_base):
def display_subscription(self,subscription):
pass
def display_imagelist(self,imagelist):
self.file_pointer.write (imagelist.data)
class output_driver_message(output_driver_base):
def __init__(self,file_pointer,session,anchor):
output_driver_base.__init__(self,file_pointer,session,anchor)
self.log = logging.getLogger("output_driver_message")
def display_subscription(self,subscription):
pass
def display_imagelist(self,imagelist):
smimeProcessor = smimeX509validation(self.anchor)
try:
smimeProcessor.Process(str(imagelist.data))
except smimeX509ValidationError,E:
self.log.error("Failed to validate text for '%s' produced error '%s'" % (imagelist,E))
return False
if not smimeProcessor.verified:
self.log.error("Failed to validate text for '%s' produced error '%s'" % (subscriptionKey,E))
return False
self.file_pointer.write (smimeProcessor.InputDaraStringIO.getvalue())
return True
class output_driver_lines(output_driver_base):
def display_subscription(self,subscription):
self.file_pointer.write ('subscription.dc:identifier=%s\n' % (subscription.identifier))
self.file_pointer.write ('subscription.dc:description=%s\n' % (subscription.description))
self.file_pointer.write ('subscription.sl:authorised=%s\n' % (subscription.authorised))
self.file_pointer.write ('subscription.hv:uri=%s\n' % (subscription.uri))
if subscription.updated:
self.file_pointer.write ('subscription.dc:date:updated=%s\n' % (subscription.updated.strftime(time_format_definition)))
else:
self.file_pointer.write ('subscription.dc:date:updated=%s\n'% (False))
return True
def display_imagelist(self,imagelist):
self.file_pointer.write ('imagelist.dc:date:imported=%s\n' % (imagelist.imported.strftime(time_format_definition)))
self.file_pointer.write ('imagelist.dc:date:created=%s\n' % (imagelist.created.strftime(time_format_definition)))
self.file_pointer.write ('imagelist.dc:date:expires=%s\n' % (imagelist.expires.strftime(time_format_definition)))
if imagelist.expired == None:
self.file_pointer.write ('imagelist.expired=0\n')
else:
self.file_pointer.write ('imagelist.expired=%s\n' % (imagelist.expired.strftime(time_format_definition)))
def subscriptions_lister(self):
subauthq = self.session.query(model.Subscription).all()
for item in subauthq:
self.file_pointer.write ("%s\t%s\t%s\n" % (item.identifier,item.authorised,item.uri))
def display_image_def(self,imagedef):
self.file_pointer.write ('subscription.image.dc:identifier=%s\n' % (imagedef.identifier))
class fileView(object):
def __init__(self,anchor,fileRaw,MatchMetadata):
self.log = logging.getLogger("fileView")
self.anchor = anchor
self.data = fileRaw
self.errorNo = 0
self.vmilist = None
self.MatchMetadata = MatchMetadata
self.Json = None
self.checkmessage()
def checkmessage(self):
# hello
#print str(self.MatchMetadata)
now = datetime.datetime.utcnow()
smimeProcessor = smimeX509validation(self.anchor)
try:
smimeProcessor.Process(str(self.data))
except smimeX509ValidationError,E:
self.log.error(E)
# Error code - failed to validate image list.
self.errorNo = 11
return
if not smimeProcessor.verified:
self.log.error("Failed to validate text for '%s' produced error '%s'" % (subscriptionKey,E))
self.errorNo = 11
return
data = smimeProcessor.InputDaraStringIO.getvalue()
self.subject = smimeProcessor.InputCertMetaDataList[0]['subject']
self.issuer = smimeProcessor.InputCertMetaDataList[0]['issuer']
jsonData = json.loads(data)
if jsonData == None:
self.log.error("Downlaoded metadata from '%s' was not valid JSON." % (subscriptionKey))
self.errorNo = 37
return
try:
vmilist = VMimageListDecoder(jsonData)
except E:
self.log.error("Exception passing '%s' was not a valid imagelist: %s." % (subscriptionKey,E))
self.errorNo = 39
return
if vmilist == None:
self.log.error("Downlaoded metadata from '%s' was not valid image list Object." % (subscriptionKey))
self.errorNo = 38
return
self.vmilist = vmilist
if vmilist.endorser.metadata[u'hv:dn'] != self.subject:
self.log.error("Endorser DN does not match signature for '%s'" (self.MatchMetadata[u'dc:identifier']))
self.log.info("Expected DN '%s'" % (vmilist.endorser.metadata[u'hv:dn']))
self.log.info("Downloaded DN '%s'" % (self.subject))
# Error code - metadata and certificate dont match.
self.errorNo = 12
return
if vmilist.endorser.metadata[u'hv:ca'] != self.issuer:
self.log.error("list hv:ca does not match signature for '%s'" % (self.MatchMetadata[u'dc:identifier']))
self.log.info("Expected CA '%s'" % (vmilist.endorser.metadata[u'hv:ca']))
self.log.info("Downloaded CA '%s'" % (self.issuer))
# Error code - metadata and certificate dont match.
self.errorNo = 12
return
if vmilist.metadata[u'hv:uri'] != self.MatchMetadata[u'hv:uri']:
self.log.error("list hv:uri does not match subscription uri for '%s'" % (self.MatchMetadata[u'dc:identifier']))
self.log.info("Expected URI '%s'" % (subscription.uri))
self.log.info("Downloaded URI '%s'" % (vmilist.metadata[u'hv:uri']))
# Error code - metadata and certificate dont match.
self.errorNo = 12
return
if vmilist.metadata[u'dc:identifier'] != self.MatchMetadata[u'dc:identifier']:
self.log.info("Expected identifier '%s'" % (self.MatchMetadata[u'dc:identifier']))
self.log.info("Downloaded identifier '%s'" % (vmilist.metadata[u'dc:identifier']))
# Error code - imagelist dc:identifier invalid.
self.errorNo = 31
return
now = datetime.datetime.utcnow()
if now < vmilist.metadata[u'dc:date:created']:
self.log.error("Image list '%s' has an invalid creation date as in the future." % (self.MatchMetadata[u'dc:identifier']))
self.errorNo = 33
return
if now > vmilist.metadata[u'dc:date:expires']:
self.log.warning("Downloaded image list '%s' has expired." % (self.MatchMetadata[u'dc:identifier']))
self.errorNo = 34
return
self.vmilist = vmilist
self.errorNo = 0
self.Json = jsonData
return
class db_controler(object):
def __init__(self,dboptions,dblog = False):
self.log = logging.getLogger("db_controler")
self.engine = create_engine(dboptions, echo=dblog)
model.init(self.engine)
self.SessionFactory = sessionmaker(bind=self.engine)
self.anchor = None
self.factory_selector = None
self.factory_view = None
# Set all callbacks to empty
self.callbackEventImageNew = None
def setup_trust_anchor(self,directory):
self.anchor = LoadDirChainOfTrust(directory)
def setup_selector_factory(self,factory):
self.factory_selector = factory
def setup_view_factory(self,factory):
self.factory_view = factory
# Utility functions
def check_factories(self):
if self.factory_view == None:
self.log.warning("factory_view not available.")
return False
if self.factory_selector == None:
self.log.warning("selector not available.")
return False
return True
def unsigned_message_by_identifier_tofilepath(self,instructions):
Session = self.SessionFactory()
db = db_actions(Session)
for instruction in instructions:
print instruction
for selection_uuid in subscriptions_selected:
db.sdsdsd(selection_uuid)
Session.commit()
def sessions_list(self):
Session = self.SessionFactory()
selector = self.factory_selector(Session)
view = self.factory_view(sys.stdout,Session,self.anchor)
view.subscriptions_lister()
return True
def subscriptions_delete(self,subscriptions_selected):
foundOne = False
Session = self.SessionFactory()
db = db_actions(Session)
selector = self.factory_selector(Session)
for selection_item in subscriptions_selected:
query_subscription = selector.subscription_get(selection_item)
for a_sub in query_subscription:
# should not need thsi code but do maybe a bug in slqalchamy or more likely my db definition"
query_image_def_linked = db.ImageDefinition_list(a_sub.id)
for image_def_linked in query_image_def_linked:
Session.delete(image_def_linked)
Session.delete(a_sub)
foundOne = True
Session.commit()
return foundOne
def subscriptions_subscribe(self,urls_selected,autoEndorse):
rc = True
Session = self.SessionFactory()
db = db_actions(Session)
for uri in urls_selected:
if not self.subscribe_file(Session,self.anchor,uri,autoEndorse):
rc = False
return rc
def subscriptions_info(self,subscriptions_selected,outputfiles):
if not self.check_factories():
return False
pairs, extra_selectors ,extra_paths = pairsNnot(subscriptions_selected,outputfiles)
for item in extra_selectors:
pairs.append([item,None])
errorhappened = False
Session = self.SessionFactory()
selector = self.factory_selector(Session)
for pair in pairs:
selector_filter = pair[0]
output_file_name = pair[1]
output_fileptr = sys.stdout
if output_file_name != None:
output_fileptr = open(output_file_name,'w+')
output_fileptr.flush()
query_subscription = selector.subscription_get(selector_filter)
if query_subscription.count() == 0:
self.log.warning("Selections '%s' does not match any known subscriptions." % (selector_filter))
continue
view = self.factory_view(output_fileptr,Session,self.anchor)
for item in query_subscription:
view.display_subscription(item)
query_imagelist = selector.imagelist_by_id(item.imagelist_latest)
for imagelist in query_imagelist:
view.display_imagelist(imagelist)
if output_file_name != None:
output_fileptr.close()
def setEventObj(self,obj):
self.eventObj = obj
def subscribe_file(self,Session,anchor,filename,autoEndorse):
req = urllib2.Request(url=filename)
f = urllib2.urlopen(req)
smimeProcessor = smimeX509validation(anchor)
try:
smimeProcessor.Process(f.read())
except smimeX509ValidationError,E:
self.log.error("Validate text '%s' produced error '%s'" % (filename,E))
return False
if not smimeProcessor.verified:
self.log.error("Failed to verify text '%s'" % (filename))
return False
jsontext = json.loads(smimeProcessor.InputDaraStringIO.getvalue())
if jsontext == None:
self.log.error("Message downlaoded from '%s' was not valid JSON." % (filename))
return False
vmilist = VMimageListDecoder(jsontext)
if vmilist == None:
self.log.error("Failed to decode the json as an image list Object for '%s'." % (filename))
return False
metadata = {}
metadata.update(vmilist.metadata)
metadata.update(vmilist.endorser.metadata)
if u'dc:identifier' not in metadata.keys():
self.log.error('list dc:identifier does not found')
return False
if metadata[u'hv:dn'] != smimeProcessor.InputCertMetaDataList[0]['subject']:
self.log.error('Endorser DN does not match signature')
return False
if metadata[u'hv:ca'] != smimeProcessor.InputCertMetaDataList[0]['issuer']:
self.log.error('list hv:ca does not match signature')
return False
if metadata[u'hv:uri'] != filename:
self.log.warning('list hv:uri does not match subscription uri')
db = db_actions(Session)
endorser_list = db.endorser_get(metadata)
if endorser_list.count() == 0:
if not autoEndorse:
self.log.error("Endorser '%s':'%s' was not found in database." % (metadata[u'hv:dn'],metadata[u'hv:ca']))
self.log.info("Use '--auto-endorse' to add endorser '%s':'%s' to subscription database." % (metadata[u'hv:dn'],metadata[u'hv:ca']))
return False
else:
# We can create an endorser.
newmetadata = dict(metadata)
newmetadata[u'dc:identifier'] = unicode(uuid.uuid4())
endorser_list = db.endorser_create(newmetadata)
self.log.warning("Endorser '%s':'%s' added to database." % (metadata[u'hv:dn'],metadata[u'hv:ca']))
if endorser_list.count() == 0:
self.log.error('Failed to create an authorised endorser in Database.')
return False
subscription_query = db.subscription_create(metadata,True)
if subscription_query.count() != 1:
self.log.error('Creation of Subscription referance failed.')
return False
subscription = subscription_query.one()
subscriptionKey = int(subscription.id)
failedToCreateImages = []
for imageReferance in vmilist.images:
# Now we creat image definitions
metadata = {}
metadata.update(imageReferance.metadata)
metadata['cache'] = 0
ImageDefinition_query = db.ImageDefinition_create(subscriptionKey,metadata)
if ImageDefinition_query.count() != 1:
self.log.error('Creation of ImageDefinition referance failed.')
failedToCreateImages.append(imageReferance)
continue
if len(failedToCreateImages) > 0:
return False
return True
def subscript_update_image(self,Session,subscription,imagelistref,imageObj):
subscriptionKey = subscription.id
ProcessingSubscriptionUuid = subscription.identifier
if not u'dc:identifier' in imageObj.metadata.keys():
self.log.error('Image had no ID so ignored')
# Error code - imagelist dc:identifier invalid.
return 31
db = db_actions(Session)
imageDefQuery = db.ImageDefinition_get(subscriptionKey,imageObj.metadata)
if imageDefQuery.count() != 1:
if self.callbackEventImageNew != None:
self.callbackEventImageNew(imageObj.metadata)
# Triggor an event for new image.
self.log.info("ImageId '%s' refused by subscription '%s'" %
(imageObj.metadata[u'dc:identifier'],ProcessingSubscriptionUuid))
# Error code - image dc:identifier invalid.
return 32
ThisImageDef = imageDefQuery.one()
ThisImageDefId = int(ThisImageDef.id)
#print ("ThisImageDefId=%s" % (ThisImageDefId))
try:
imageinstance = model.ImageInstance(imagelistref,ThisImageDefId,imageObj.metadata)
except KeyError, E:
self.log.error("missing parameters '%s'" % E.message)
Session.rollback()
return 34
Session.add(imageinstance)
try:
Session.commit()
except IntegrityError,E:
self.log.error("Database integrity error '%s' processing '%s'." % (E.args,ProcessingSubscriptionUuid))
self.log.debug(E.params)
Session.rollback()
return 0
# So now we have done the updating of the database and just need to update
# the latest image instance record in the database.
latestimageInstanceQuery = Session.query(model.ImageInstance).\
filter(model.ImageInstance.fkimagelistinstance == imagelistref).\
filter(model.ImageInstance.fkIdentifier == ThisImageDefId)
if latestimageInstanceQuery.count() != 1:
return 0
imageInstancelatest = latestimageInstanceQuery.one()
imageDefQuery = db.ImageDefinition_get(subscriptionKey,imageObj.metadata)
if imageDefQuery.count() != 1:
self.log.error("ImageId '%s' not accepted for subscription '%s'" %
(imageObj.metadata[u'dc:identifier'],ProcessingSubscriptionUuid))
return 36
ThisImageDef = imageDefQuery.one()
ThisImageDef.latest = imageInstancelatest.id
Session.add(ThisImageDef)
Session.commit()
return 0
def subscription_update(self,Session,subscription):
subscriptionKey = int(subscription.id)
ProcessingSubscriptionUuid = str(subscription.identifier)
self.log.info("Updating:%s" % (ProcessingSubscriptionUuid))
req = urllib2.Request(url=subscription.uri)
try:
f = urllib2.urlopen(req)
except urllib2.URLError,E:
# Python 2.6 Exception
self.log.error("Download of url '%s' failed." % (subscription.uri))
# Error code - failed to download image list.
return 10
except OSError:
# Python 2.4 Exception
self.log.error("Download of url '%s' failed." % (subscription.uri))
# Error code - failed to download image list.
return 10
update_unprocessed = str(f.read())
# Now we have the update lets first check its hash
messagehash = hashlib.sha512(update_unprocessed).hexdigest()
now = datetime.datetime.utcnow()
metadataFV = {
u'hv:uri' : str(subscription.uri),
u'dc:identifier' : str(subscription.identifier),
}
#self.log.error("errr:%s" % (ProcessingSubscriptionUuid))
checker = fileView(self.anchor,update_unprocessed,metadataFV)
if checker.errorNo != 0:
self.log.error("Failed to verify subscription '%s' with URI '%s'" % (subscription.identifier,subscription.uri))
return checker.errorNo
if checker.Json == None:
return 14
metadata = checker.vmilist.metadata
metadata[u'data'] = update_unprocessed
metadata[u'data-hash'] = messagehash
if checker.errorNo != 0:
self.log.info('Message Expired:%s' % (ProcessingSubscriptionUuid))
metadata[u'expired'] = now
Session.commit()
# Now we know the data better check the SubscriptionAuth
subq = Session.query(model.Subscription, model.SubscriptionAuth).\
filter(model.Endorser.id == model.EndorserPrincible.id).\
filter(model.EndorserPrincible.hv_dn == checker.subject).\
filter(model.EndorserPrincible.hv_ca == checker.issuer).\
filter(model.SubscriptionAuth.endorser == model.Endorser.id).\
filter(model.SubscriptionAuth.subscription == model.Subscription.id).\
filter(model.Subscription.id == subscription.id)
count = subq.count()
if count == 0:
self.log.error('Endorser not authorised on subscription %s' % (ProcessingSubscriptionUuid))
# Error code - Endorser not authorised on subscription.
return 13
if count != 1:
self.log.error('Database Error processing subq:%s' % (ProcessingSubscriptionUuid))
assert (False)
subscription, auth = subq.one()
# Sets
VersionCompare = 0
qeryJunction = Session.query(model.ImageListInstance).\
filter(model.Subscription.imagelist_latest == model.ImageListInstance.id).\
filter(model.Subscription.id == subscription.id)
if qeryJunction.count() == 0:
#"we have no older version"
self.log.info("First version of:%s" % (ProcessingSubscriptionUuid))
else:
if qeryJunction.count() != 1:
self.log.error('Database Error processing qeryJunction:%s' % (ProcessingSubscriptionUuid))
assert (False)
imageList = qeryJunction.one()
if imageList.data_hash == messagehash:
self.log.debug('Same version:%s' % (ProcessingSubscriptionUuid))
if now > imageList.expires:
self.log.info("Image list '%s' has expired on: '%s'" % (ProcessingSubscriptionUuid,imageList.expires))
if imageList.expired == None:
imageList.expired = now
Session.commit()
# We now know imageList is not too old.
if ((imageList.expired != None) and (checker.errorNo == 0)):
# we have expired previously but now it looks good.
self.log.info('imageList Validated:%s' % (ProcessingSubscriptionUuid))
imageList.expired = None
Session.commit()
if ((imageList.expired == None) and (checker.errorNo != 0)):
# should expire.
self.log.info('imageList Expired:%s' % (ProcessingSubscriptionUuid))
imageList.expired = now
Session.commit()
return 0
messageVersion = checker.Json[u'hv:imagelist'][u'hv:version']
self.log.debug('Downloaded version:%s' % (messageVersion))
VersionCompare = split_numeric_sort(imageList.version,messageVersion)
if VersionCompare == 0:
self.log.warning('Downloaded version "%s" version "%s" has the same version number than the old version "%s".' % (ProcessingSubscriptionUuid,messageVersion, imageList.version))
#return 16 # 16 New version number is same as old version number.
if VersionCompare < 0:
self.log.error('Downloaded version "%s" version "%s" has lower version number than the old version "%s".' % (ProcessingSubscriptionUuid,messageVersion, imageList.version))
return 17 # 17 New version number is less than old version number.
imagelist = model.ImageListInstance(auth.id,metadata)
Session.add(imagelist)
try:
Session.commit()
except IntegrityError,E:
self.log.error("Database integrity error '%s' processing '%s'." % (E.args,ProcessingSubscriptionUuid))
self.log.debug(E.params)
Session.rollback()
# Error code - Database integrity error.
return 15
imagelistref = int(imagelist.id)
# Now make a global return number
globalRc = 0
for imageObj in checker.vmilist.images:
# Now update each Image
thisRc = self.subscript_update_image(Session,subscription,imagelistref,imageObj)
if thisRc != 0:
globalRc = thisRc
if subscription.imagelist_latest != None:
oldimagelist_q = Session.query(model.ImageListInstance).\
filter(model.ImageListInstance.id == subscription.imagelist_latest)
for imagelist in oldimagelist_q:
imagelist.authorised = False
Session.add(imagelist)
subscription.updated = datetime.datetime.utcnow()
subscription.imagelist_latest = imagelistref
Session.add(subscription)
Session.commit()
return globalRc
def subscriptions_update(self):
if self.anchor == None:
self.log.warning("No enabled certificates, check your x509 dir.")
return 12
Session = self.SessionFactory()
db = db_actions(Session)
rc = 0
subscriptionlist = Session.query(model.Subscription).all()
for subscription in subscriptionlist:
thisRc = self.subscription_update(Session,subscription)
if thisRc != 0:
rc = thisRc
return rc
def subscriptions_image_list(self,subscriptions_selected,outputfiles):
if not self.check_factories():
return False
pairs, extra_selectors ,extra_paths = pairsNnot(subscriptions_selected,outputfiles)
for item in extra_selectors:
pairs.append([item,None])
errorhappened = False
Session = self.SessionFactory()
selector = self.factory_selector(Session)
for pair in pairs:
selector_filter = pair[0]
output_file_name = pair[1]
output_fileptr = sys.stdout
if output_file_name != None:
output_fileptr = open(output_file_name,'w+')
output_fileptr.flush()
query_subscription = selector.subscription_get(selector_filter)
if query_subscription.count() == 0:
self.log.warning("Selections '%s' does not match any known subscriptions." % (selector_filter))
continue
view = self.factory_view(output_fileptr,Session,self.anchor)
for item in query_subscription:
view.display_subscription(item)
query_image_def = Session.query(model.ImageDefinition).\
filter(model.ImageDefinition.subscription==item.id)
for imagedef in query_image_def:
view.display_image_def(imagedef)
if output_file_name != None:
output_fileptr.close()
def subscriptions_image_accept(self,subscriptions,images):
pairs, extra_subscriptions ,extra_images = pairsNnot(subscriptions,images)
if len(extra_subscriptions) > 0:
self.log.error('Not enough images selected')
return False
if len(extra_images) > 0:
self.log.error('Not enough subscriptions selected')
return False
Session = self.SessionFactory()
errors = 0
for sub_uuid, image_uuid in pairs:
image_known = Session.query(model.ImageDefinition.identifier,model.Subscription.identifier).\
filter(model.ImageDefinition.identifier == image_uuid).\
filter(model.ImageDefinition.subscription == model.Subscription.id)
if image_known.count() > 0:
iident, sident = image_known.one()
self.log.error("Subscription '%s' has image '%s' already." % (sident,iident))
errors = errors + 1
continue
sub_known = Session.query(model.Subscription).\
filter(model.Subscription.identifier == sub_uuid)
if sub_known.count() == 0:
self.log.error("Subscription '%s' is unknown." % (sub_uuid))
errors = errors + 1
return False
subscription = sub_known.one()
subscription.imagelist_latest = None
key = subscription.id
metadata = { 'dc:identifier' : image_uuid,
'cache' : 0}
newlist = model.ImageDefinition(key,metadata)
Session.add(newlist)
Session.add(subscription)
Session.commit()
#self.log.info("Subscription '%s' include image '%s'." % (sub_uuid,image_uuid))
if errors != 0:
return False
return True
def subscriptions_image_refuse(self,subscriptions,images):
pairs, extra_subscriptions ,extra_images = pairsNnot(subscriptions,images)
if len(extra_subscriptions) > 0:
self.log.error('Not enough images selected')
return False
if len(extra_images) > 0:
self.log.error('Not enough subscriptions selected')
return False
Session = self.SessionFactory()
errors = 0
for sub_uuid, image_uuid in pairs:
image_known = Session.query(model.Subscription,model.ImageDefinition).\
filter(model.ImageDefinition.identifier == image_uuid).\
filter(model.ImageDefinition.subscription == model.Subscription.id).\
filter(model.Subscription.identifier == sub_uuid)
if image_known.count() == 0:
self.log.error("Subscription '%s' already refuses image '%s'." % (sub_uuid,image_uuid))
errors = errors + 1
continue
subscription ,imageDef = image_known.one()
imageInstance_known = Session.query(model.ImageInstance).\
filter(model.ImageInstance.fkIdentifier == imageDef.id)
for instance in imageInstance_known:
Session.delete(instance)
subscription.imagelist_latest = None
Session.delete(imageDef)
Session.add(subscription)
Session.commit()
if errors != 0:
return False
return True
# User interface
def pairsNnot(list_a,list_b):
len_generate_list = len(list_a)
len_image_list = len(list_b)
ocupies_generate_list = set(range(len_generate_list))
ocupies_image_list = set(range(len_image_list))
ocupies_pairs = ocupies_image_list.intersection(ocupies_generate_list)
diff_a = ocupies_generate_list.difference(ocupies_image_list)