forked from GENI-NSF/geni-tools
-
Notifications
You must be signed in to change notification settings - Fork 0
/
am_api_accept.py
executable file
·2029 lines (1773 loc) · 97.6 KB
/
am_api_accept.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 python
#----------------------------------------------------------------------
# Copyright (c) 2011-2015 Raytheon BBN Technologies
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and/or hardware specification (the "Work") to
# deal in the Work without restriction, including without limitation the
# rights to use, copy, modify, merge, publish, distribute, sublicense,
# and/or sell copies of the Work, and to permit persons to whom the Work
# is furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Work.
#
# THE WORK IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
# OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
# HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
# WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE WORK OR THE USE OR OTHER DEALINGS
# IN THE WORK.
#----------------------------------------------------------------------
""" Acceptance tests for AM API v1, v2, and v3."""
import datetime
import dateutil.parser
import json
import os
import pprint
import re
import sys
import time
import tempfile
import unittest
import xml.etree.ElementTree as etree
from gcf.geni.util import rspec_util
from gcf.geni.util.rspec_schema import *
from gcf.geni.util import urn_util
from gcf.geni.util import error_util
import gcf.oscript as omni
import omni_unittest as ut
from omni_unittest import NotSuccessError, NotDictAssertionError, NotNoneAssertionError
from omni_unittest import NotXMLAssertionError, NoResourcesAssertionError, WrongRspecType
from gcf.omnilib.util import OmniError, NoSliceCredError, RefusedError, AMAPIError, naiveUTC
import gcf.omnilib.util.json_encoding as json_encoding
import gcf.omnilib.util.credparsing as credparsing
from gcf.sfa.trust.credential import Credential
# Works at PLC
PGV2_RSPEC_NAME = "ProtoGENI"
PGV2_RSPEC_NUM = '2'
RSPEC_NAME = "GENI"
RSPEC_NUM = '3'
TMP_DIR="."
REQ_RSPEC_FILE="request.xml"
REQ_RSPEC_FILE_1="request1.xml"
REQ_RSPEC_FILE_2="request2.xml"
REQ_RSPEC_FILE_3="request3.xml"
BAD_RSPEC_FILE="bad.xml"
SLEEP_TIME=30 # Pause between AM API calls in seconds
SUCCESS = 0
################################################################################
#
# Test AM API calls for accurate and complete functionality.
#
# This script relies on the unittest module.
#
# To run all tests:
# ./am_api_accept.py -a <AM to test>
#
# To run a single test:
# ./am_api_accept.py -a <AM to test> Test.test_GetVersion
#
# To add a new test:
# Create a new method with a name starting with 'test_". It will
# automatically be run when am_api_accept.py is called.
#
################################################################################
class Test(ut.OmniUnittest):
"""Acceptance tests for GENI AM API."""
def setUp( self ):
ut.OmniUnittest.setUp(self)
# Set up RSpec type/version
if self.options_copy.protogeniv2:
self.options_copy.rspectype = (PGV2_RSPEC_NAME, PGV2_RSPEC_NUM)
self.manifest_namespace = PG_2_NAMESPACE
self.manifest_schema = PG_2_MAN_SCHEMA
self.request_namespace = PG_2_NAMESPACE
self.request_schema = PG_2_REQ_SCHEMA
self.ad_namespace = PG_2_NAMESPACE
self.ad_schema = PG_2_AD_SCHEMA
else:
self.options_copy.rspectype = (RSPEC_NAME, RSPEC_NUM)
self.manifest_namespace = GENI_3_NAMESPACE
self.manifest_schema = GENI_3_MAN_SCHEMA
self.request_namespace = GENI_3_NAMESPACE
self.request_schema = GENI_3_REQ_SCHEMA
self.ad_namespace = GENI_3_NAMESPACE
self.ad_schema = GENI_3_AD_SCHEMA
self.success = False
self.logger = omni.configure_logging(self.options_copy)
def tearDown( self ):
ut.OmniUnittest.tearDown(self)
if self.options_copy.monitoring:
# MONITORING test_TestName 1
print "\nMONITORING %s %d" % (self.id().split('.',2)[-1],int(not self.success))
def checkAdRSpecVersion(self):
return self.checkRSpecVersion(type='ad')
def checkRequestRSpecVersion(self):
return self.checkRSpecVersion(type='request')
def checkRSpecVersion(self, type='ad'):
"""type is either 'ad' or 'request' """
if type not in ('ad', 'request'):
print "type must be either 'ad' or 'request', received '%s' instead" % type
return False
rspec_type = type+"_rspec_versions"
rtype = self.options_copy.rspectype[0]
rver = self.options_copy.rspectype[1]
# call GetVersion
omniargs = ['getversion', "-o", "--ForceUseGetVersionCache"]
self.logger.info("\n=== doing checkRSpecVersion ===")
(text, version) = self.call(omniargs, self.options_copy)
mymessage = ""
for agg, thisVersion in version.items():
self.assertTrue( thisVersion,
"AM %s didn't respond to GetVersion" % (agg) )
if self.options_copy.api_version >= 2:
value = thisVersion['value']
rspec_version = self.assertReturnKeyValueType(
'GetVersion', agg, value,
'geni_'+rspec_type,
list )
else:
value = thisVersion
rspec_version = self.assertReturnPairKeyValue(
'GetVersion', agg, value,
rspec_type,
'geni_'+rspec_type,
list )
# foreach item in the list that is the val
match = False
for availversion in rspec_version:
if not(str(availversion['type']).lower().strip() == rtype.lower().strip()):
continue
if not(str(availversion['version']).lower().strip() == str(rver).lower().strip()):
continue
match = True
rtype=availversion['type']
rver=availversion['version']
break
self.assertTrue(match,
"Agg doesn't support requested version: %s %s" % (rtype, rver))
return match
def test_GetVersion(self):
"""test_GetVersion: Passes if a 'GetVersion' returns an XMLRPC struct containing
'geni_api' and other parameters defined in Change Set A or APIv2 or APIv3, as appropriate.
"""
# Do AM API call
omniargs = ["getversion"]
self.logger.info("\n=== Test.test_GetVersion ===")
(text, ret_dict) = self.call(omniargs, self.options_copy)
pprinter = pprint.PrettyPrinter(indent=4)
# If this isn't a dictionary, something has gone wrong in Omni.
self.assertDict(ret_dict,
"Return from 'GetVersion' " \
"expected to contain dictionary" \
"but instead returned:\n %s"
% (pprinter.pformat(ret_dict)))
# An empty dict indicates a misconfiguration!
self.assertTrue(ret_dict,
"Return from 'GetVersion' " \
"expected to contain dictionary keyed by aggregates " \
"but instead returned empty dictionary. " \
"This indicates there were no aggregates checked. " \
"Look for misconfiguration.")
# Checks each aggregate
for (agg, ver_dict) in ret_dict.items():
value = self.assertReturnKeyValueType( 'GetVersion', agg, ver_dict,
'geni_api', int )
self.assertEqual(value, self.options_copy.api_version,
"Return from 'GetVersion' at aggregate '%s' " \
"expected to have 'geni_api=%d' " \
"but instead 'geni_api=%d.'"
% (agg, self.options_copy.api_version, value))
# If we only want to test Pure AM API v1 stop here
if self.options_copy.api_version == 1 and self.options_copy.pure_v1:
self.success = True
return
if self.options_copy.api_version >= 2:
err_code, msg = self.assertCodeValueOutput( 'GetVersion',
agg, ver_dict )
self.assertSuccess( err_code )
value = ver_dict['value']
api_vers = self.assertReturnKeyValueType(
'GetVersion', agg, value,
'geni_api_versions',
dict )
self.assertKeyValueType( 'GetVersion', agg, api_vers,
str(self.options_copy.api_version),
str )
# Check v3+ AM optional geni_single_allocation and geni_allocate
if self.options_copy.api_version >= 3:
self.assertGeniSingleAllocationIfExists( "GetVersion", agg, value )
self.assertGeniAllocateIfExists( "GetVersion", agg, value )
if self.options_copy.api_version >= 2:
request_rspec_versions = self.assertReturnKeyValueType(
'GetVersion', agg, value,
'geni_request_rspec_versions',
list )
else:
request_rspec_versions = self.assertReturnPairKeyValue(
'GetVersion', agg, ver_dict,
'request_rspec_versions',
'geni_request_rspec_versions',
list )
if self.options_copy.protogeniv2:
exp_type = PGV2_RSPEC_NAME
exp_num = PGV2_RSPEC_NUM
else:
exp_type = RSPEC_NAME
exp_num = RSPEC_NUM
request = False
for vers in request_rspec_versions:
self.assertKeyValueType( 'GetVersion', agg, vers, 'type', str)
self.assertKeyValueType( 'GetVersion', agg, vers, 'version', str, )
# V3 changed these to be required but possibly empty
if self.options_copy.api_version >= 3:
self.assertKeyValueType( 'GetVersion', agg, vers, 'schema', str )
self.assertKeyValueType( 'GetVersion', agg, vers, 'namespace', str )
self.assertKeyValueType( 'GetVersion', agg, vers, 'extensions', list )
try:
self.assertKeyValueLower( 'GetVersion', agg, vers,
'type', exp_type )
self.assertKeyValueLower( 'GetVersion', agg, vers,
'version', exp_num )
request = True
except:
pass
self.assertKeyValueType( 'GetVersion', agg, vers, 'extensions', type([]) )
# End loop over advertised request rspec versions
self.assertTrue( request,
"Return from 'GetVersion' at %s " \
"expected to have entry " \
"'geni_request_rspec_versions' of " \
"type='%s' and value='%s' " \
"but did not."
% (agg, exp_type, exp_num) )
if self.options_copy.api_version >= 2:
ad_rspec_versions = self.assertReturnKeyValueType(
'GetVersion', agg, value,
'geni_ad_rspec_versions',
list )
else:
ad_rspec_versions = self.assertReturnPairKeyValue(
'GetVersion', agg, ver_dict,
'ad_rspec_versions',
'geni_ad_rspec_versions',
list )
ad = False
for vers in ad_rspec_versions:
self.assertKeyValueType( 'GetVersion', agg, vers, 'type', str)
self.assertKeyValueType( 'GetVersion', agg, vers, 'version', str, )
# V3 changed these to be required but possibly empty
if self.options_copy.api_version >= 3:
self.assertKeyValueType( 'GetVersion', agg, vers,
'schema', str )
self.assertKeyValueType( 'GetVersion', agg, vers,
'namespace', str )
self.assertKeyValueType( 'GetVersion', agg, vers,
'extensions', list )
try:
self.assertKeyValueLower( 'GetVersion', agg, vers,
'type', exp_type )
self.assertKeyValueLower( 'GetVersion', agg, vers,
'version', exp_num )
ad = True
except:
pass
self.assertKeyValueType( 'GetVersion', agg, vers,
'extensions', list )
# End of loop over advertised ad rspec versions
self.assertTrue( ad,
"Return from 'GetVersion' at %s " \
"expected to have entry " \
"'geni_ad_rspec_versions' of " \
"'type'=%s and 'value'=%s" \
"but did not."
% (agg, exp_type, exp_num) )
# Check v3+ AM advertises geni_sfa credential support
if self.options_copy.api_version >= 3:
cred_types = self.assertReturnKeyValueType(
'GetVersion', agg, value,
'geni_credential_types',
list )
hasSfa = False
for creds in cred_types:
geni_type = self.assertReturnKeyValueType(
'GetVersion', agg, creds,
'geni_type', str)
geni_version = self.assertReturnKeyValueType(
'GetVersion', agg, creds,
'geni_version', str )
if geni_type == Credential.SFA_CREDENTIAL_TYPE \
and (geni_version == '2' or geni_version == '3'):
hasSfa = True
continue
self.assertTrue( hasSfa,
"Return from 'GetVersion' at %s " \
"expected to have at least one entry " \
"'geni_credential_types' of " \
"'geni_type'='sfa' and 'geni_version'= 3 (or 2) " \
"but did not."
% (agg) )
self.success = True
def test_ListResources(self):
"""test_ListResources: Passes if 'ListResources' returns an advertisement RSpec.
"""
self.logger.info("\n=== Test.test_ListResources ===")
if self.options_copy.api_version > 1:
self.options_copy.arbitrary_option = True
# omni sets 'geni_compress' = True
self.subtest_ListResources()
self.success = True
def test_ListResources_geni_compressed(self):
"""test_ListResources_geni_compressed: Passes if 'ListResources' returns an advertisement RSpec.
"""
# omni sets 'geni_compressed' = True, override
self.logger.info("\n=== Test.test_ListResources_geni_compressed ===")
self.options_copy.geni_compressed = False
self.subtest_ListResources()
self.success = True
def test_ListResources_geni_available(self):
"""test_ListResources_geni_available: Passes if 'ListResources' returns an advertisement RSpec.
"""
# omni sets 'geni_available' = False, override
self.logger.info("\n=== Test.test_ListResources_geni_available ===")
self.options_copy.geni_available = True
self.subtest_ListResources()
self.success = True
def subtest_Describe_geni_compressed(self, slicename):
"""test_Describe_geni_compressed: Passes if 'Describe' returns an advertisement RSpec.
"""
# omni sets 'geni_compressed' = True, override
self.options_copy.geni_compressed = False
self.subtest_Describe( slicename=slicename )
self.success = True
def test_ListResources_badCredential_malformedXML(self):
"""test_ListResources_badCredential_malformedXML: Run ListResources with
a User Credential that is missing it's first character (so that it is invalid XML). """
self.logger.info("\n=== Test.test_ListResources_badCredential_malformedXML. Should FAIL ===")
self.subtest_ListResources_badCredential(self.removeFirstChar)
self.success = True
def test_ListResources_badCredential_alteredObject(self):
"""test_ListResources_badCredential_alteredObject: Run ListResources with
a User Credential that has been altered (so the signature doesn't match). """
self.logger.info("\n=== Test.test_ListResources_badCredential_alteredObject. Should FAIL ===")
self.subtest_ListResources_badCredential(self.alterSignedObject)
self.success = True
# FIXME: Would love to test supplying a list of credentials, 1 good and 1 bad,
# but Omni doesn't support it yet
def test_ListResources_badCredential_badtype(self):
"""test_ListResources_badCredential_badtype: Run ListResources in API v3+ with
a User Credential that says it is of a nonexistent type only: should fail """
if self.options_copy.api_version < 3:
self.success = True
return
# (1) Get the usercredential
omniargs = ["getusercred", "-o"]
self.logger.info("\n=== Test.test_ListResources_badCredential_badtype -- Should FAIL ===")
(text, usercredstruct) = self.call(omniargs, self.options_copy)
geni_type, geni_version, usercred = self.assertUserCred(usercredstruct)
brokencredstruct = dict()
brokencredstruct['geni_type'] = geni_type + "BROKEN"
brokencredstruct['geni_version'] = geni_version
brokencredstruct['geni_value'] = usercred
self.options_copy.devmode = True
self.assertRaises((NotSuccessError, NotDictAssertionError), self.subtest_ListResources,
usercred=json.dumps(brokencredstruct, cls=json_encoding.DateTimeAwareJSONEncoder))
self.options_copy.devmode = False
def subtest_ListResources_slice_with_usercred(self, slicename):
"""test_ListResources_slice_with_usercred: Run ListResources with
a User Credential pretending to be the slice cred: should fail """
# (1) Get the usercredential
omniargs = ["getusercred", "-o"]
self.logger.info("\n=== Test.test_ListResources_slice_with_usercred ===")
(text, usercredstruct) = self.call(omniargs, self.options_copy)
self.options_copy.devmode = True
user_cred=json.dumps(usercredstruct, cls=json_encoding.DateTimeAwareJSONEncoder)
if self.options_copy.api_version == 1:
self.assertRaises((NotSuccessError, NotDictAssertionError, AMAPIError, NotNoneAssertionError), self.subtest_generic_ListResources,
slicename=slicename,
slicecred=user_cred)
else:
self.assertRaises((NotSuccessError, NotDictAssertionError, AMAPIError), self.subtest_generic_ListResources,
slicename=slicename,
slicecred=user_cred)
self.options_copy.devmode = False
def removeFirstChar( self, usercred ):
return usercred[1:]
def alterSignedObject( self, usercred ):
try:
root = etree.fromstring(usercred)
except:
raise ValueError, "'usercred' is not an XML document."
newElement = etree.Element("foo")
root.insert(0, newElement)
newcred = etree.tostring(root)
return newcred
def subtest_ListResources_badCredential(self, mundgeFcn):
"""test_ListResources_badCredential: Passes if 'ListResources' FAILS to return
an advertisement RSpec when using a bad credential.
"""
# (1) Get the usercredential
omniargs = ["getusercred", "-o"]
self.logger.info("\n=== Test.test_ListResources_badCredential ===")
(text, usercredstruct) = self.call(omniargs, self.options_copy)
if self.options_copy.api_version >= 3:
geni_type, geni_version, usercred = self.assertUserCred(usercredstruct)
else:
usercred = usercredstruct
self.assertStr( usercred,
"Return from 'getusercred' " \
"expected to be string " \
"but instead returned: %r"
% (usercred))
# Test if file is XML
self.assertTrue(rspec_util.is_wellformed_xml( usercred ),
"Return from 'getusercred' " \
"expected to be XML " \
"but instead returned: \n" \
"%s\n" \
"... edited for length ..."
% (usercred[:100]))
# (2) Create a broken usercred
broken_usercred = mundgeFcn(usercred)
# (3) Call listresources with this broken credential
# We expect this to fail
# self.subtest_ListResources(usercred=broken_usercred)
# with slicename left to the default
self.options_copy.devmode = True
if self.options_copy.api_version == 1:
self.assertRaises((AMAPIError, NotSuccessError, NotDictAssertionError, NotNoneAssertionError), self.subtest_ListResources,
usercred=broken_usercred)
else:
self.assertRaises((AMAPIError, NotSuccessError, NotDictAssertionError), self.subtest_ListResources,
usercred=broken_usercred)
self.options_copy.devmode = False
def subtest_ListResources_wrongSlice(self, slicelist):
num_slices = len(slicelist)
for i in xrange(num_slices):
slice = slicelist[i]
# (1) Get the slicecredential
omniargs = ["getslicecred", slice, "-o"]
self.logger.info("\n=== Test.test_ListResources_wrongSlice ===")
(text, slicecredstruct) = self.call(omniargs, self.options_copy)
if self.options_copy.api_version >= 3:
tmpRetVal = self.assertSliceCred(slicecredstruct)
self.assertIsNotNone( tmpRetVal )
geni_type, geni_version, slicecred = tmpRetVal
else:
slicecred = slicecredstruct
self.assertStr( slicecred,
"Return from 'getslicered' " \
"expected to be string " \
"but instead returned: %r"
% (slicecred))
# Test if file is XML
self.assertTrue(rspec_util.is_wellformed_xml( slicecred ),
"Return from 'getslicecred' " \
"expected to be XML " \
"but instead returned: \n" \
"%s\n" \
"... edited for length ..."
% (slicecred[:100]))
# (2) Call listresources on the next slice
# We expect this to fail
# self.subtest_ListResources(slice)
self.options_copy.devmode = True
if self.options_copy.api_version == 1:
self.assertRaises((AMAPIError, NotSuccessError, NotDictAssertionError, NotNoneAssertionError), self.subtest_generic_ListResources,
slicename=slicelist[(i+1)%num_slices], slicecred=slicecred)
else:
self.assertRaises((AMAPIError, NotSuccessError, NotDictAssertionError), self.subtest_generic_ListResources,
slicename=slicelist[(i+1)%num_slices], slicecred=slicecred)
self.options_copy.devmode = False
def file_to_string( self, filename ):
with open(filename) as f:
contents = f.readlines()
output = "".join(contents)
return output
def get_cred_schema_info( self, version ):
if version.lower() in ("protogeni", "pg"):
return (PG_CRED_NAMESPACE,
PG_CRED_SCHEMA)
def is_delegated_cred( cls, xml):
try:
root = etree.fromstring(xml)
except:
return False
# ns, schema = cls.get_cred_schema_info( version=version )
# prefix = "{%s}"%ns
parent = root.findall( 'credential/parent' )
if len(parent) > 0:
return True
else:
return False
def get_slice_name_from_cred( cls, xml):
"""Get the slice_name from the credential (retrieve the first if there is more than one)"""
try:
root = etree.fromstring(xml)
except:
return False
# ns, schema = cls.get_cred_schema_info( version=version )
# prefix = "{%s}"%ns
target = root.findall( 'credential/parent/credential/target_urn' )
urn = target[0].text
# urn is of form: ...+slice+name
# (1) check that second to last part of URN is 'slice'
# (1) return the last part of the URN
urn_type = urn.rsplit("+")[-2]
if urn_type == 'slice':
slice_name = urn.rsplit("+")[-1]
return slice_name
else:
return None
def test_ListResources_untrustedCredential(self):
"""test_ListResources_untrustedCredential: Passes if 'ListResources' FAILS to
return an advertisement RSpec when using a credential from an untrusted Clearinghouse.
"""
# Call listresources with this credential
# We expect this to fail
# with slicename left to the default
self.logger.info("\n=== Test.test_ListResources_untrustedCredential - should FAIL ===")
if self.options_copy.api_version == 1:
self.assertRaises((AMAPIError, NotSuccessError, NotDictAssertionError, NotNoneAssertionError), self.subtest_ListResources,
usercredfile=self.options_copy.untrusted_usercredfile)
else:
self.assertRaises((AMAPIError, NotSuccessError, NotDictAssertionError), self.subtest_ListResources,
usercredfile=self.options_copy.untrusted_usercredfile)
self.success = True
def subtest_Describe( self, slicename=None, slicecred=None, usercred=None,
usercredfile=None, slicecredfile=None, typeOnly=False,
sliverurns=[], expectedExpiration=None):
return self.subtest_query_rspec( AMAPI_call="Describe", slicename=slicename,
slicecred=slicecred, usercred=usercred, usercredfile=usercredfile,
slicecredfile=slicecredfile, typeOnly=typeOnly, sliverurns=sliverurns, expectedExpiration=expectedExpiration )
def subtest_ListResources( self, slicename=None, slicecred=None, usercred=None, usercredfile=None,
slicecredfile=None, typeOnly=False, ):
return self.subtest_query_rspec( AMAPI_call="ListResources", slicename=slicename,
slicecred=slicecred, usercred=usercred, usercredfile=usercredfile,
slicecredfile=slicecredfile, typeOnly=typeOnly )
def subtest_query_rspec(self, AMAPI_call="ListResources", slicename=None, slicecred=None,
usercred=None, usercredfile=None, slicecredfile=None, typeOnly=False, sliverurns=[], expectedExpiration=None):
if not slicecred:
self.assertTrue( self.checkAdRSpecVersion() )
else:
self.assertTrue(self.checkRequestRSpecVersion())
# Check to see if 'rspeclint' can be found before doing the hard (and
# slow) work of calling ListResources at the aggregate
if self.options_copy.rspeclint:
rspec_util.rspeclint_exists()
if slicename:
rspec_namespace = self.manifest_namespace
rspec_schema = self.manifest_schema
else:
rspec_namespace = self.ad_namespace
rspec_schema = self.ad_schema
omniargs = ["-o"]
if slicename:
omniargs = omniargs + [AMAPI_call, str(slicename)]
else:
omniargs = omniargs + [AMAPI_call]
for urn in sliverurns:
omniargs = omniargs + ['-u', urn]
# Force actual omni output to a file? Then to debug things
# we'd need to save those files, and they might step on each other...
# omniargs = omniargs + ['-o']
if usercred and slicecred:
with tempfile.NamedTemporaryFile() as f:
# make a temporary file containing the user credential
f.write( usercred )
f.seek(0)
# Keeping f open...
with tempfile.NamedTemporaryFile() as f2:
# make a temporary file containing the slice credential
f2.write( slicecred )
f2.seek(0)
# keeping both files open...
omniargs = omniargs + ["--usercredfile", f.name] + ["--slicecredfile", f2.name]
# run command here while temporary file is open
(text, ret_dict) = self.call(omniargs, self.options_copy)
elif slicecred and not(usercred):
with tempfile.NamedTemporaryFile() as f2:
# make a temporary file containing the slice credential
f2.write( slicecred )
f2.seek(0)
# Keeping f2 open...
omniargs = omniargs + ["--slicecredfile", f2.name]
(text, ret_dict) = self.call(omniargs, self.options_copy)
elif usercred and not(slicecred):
with tempfile.NamedTemporaryFile() as f:
# make a temporary file containing the user credential
f.write( usercred )
f.seek(0)
# Keeping f open...
omniargs = omniargs + ["--usercredfile", f.name]
# run command here while temporary file is open
(text, ret_dict) = self.call(omniargs, self.options_copy)
elif usercredfile:
omniargs = omniargs + ["--usercredfile", usercredfile]
(text, ret_dict) = self.call(omniargs, self.options_copy)
elif slicecredfile:
omniargs = omniargs + ["--slicecredfile", slicecredfile]
(text, ret_dict) = self.call(omniargs, self.options_copy)
else:
(text, ret_dict) = self.call(omniargs, self.options_copy)
self.assertDict(ret_dict,
"Call to '%s' failed or not possible " \
"but expected to succeed. " \
"Error returned:\n %s"
% (AMAPI_call, text))
# An empty dict indicates a misconfiguration!
self.assertTrue(ret_dict,
"Return from '%s' " \
"expected to contain dictionary keyed by aggregates " \
"but instead returned empty dictionary. " \
"This indicates there were no aggregates checked. " \
"Look for misconfiguration." % (AMAPI_call) )
if AMAPI_call == "Describe":
# AM API v3+ Describe( slicename )
for agg, indAgg in ret_dict.items():
err_code, msg = self.assertCodeValueOutput( AMAPI_call, agg,
indAgg )
self.assertSuccess( err_code )
# value only required if it is successful
retVal = indAgg['value']
slivers, rspec = self.assertDescribeReturn( agg, retVal)
numslivers = len(slivers)
self.assertRspec( AMAPI_call, rspec,
rspec_namespace, rspec_schema,
self.options_copy.rspeclint)
self.assertRspecType( rspec, 'manifest', typeOnly=typeOnly)
if sliverurns:
reported_urns = []
for sliver in slivers:
reported_urns.append( sliver['geni_sliver_urn'] )
self.assertTrue( set(reported_urns)==set(sliverurns),
"Return from '%s' at aggregate '%s' " \
"expected to only include requested sliver urns " \
"but did not. \nRequested slivers were: " \
"\n%s\n" \
"Returned slivers were: " \
"\n%s"
% (AMAPI_call, agg, str(sliverurns), str(reported_urns)))
# else it should be true that all slivers in the slice are reported
else:
# AM API v1-v3 ListResources() and
# AM API v1-v2 ListResources( slicename )
# but not AM API v3 Describe() <-- which is covered above
for (agg_url, rspec) in ret_dict.items():
if self.options_copy.api_version >= 2:
err_code, msg = self.assertCodeValueOutput( AMAPI_call,
agg_url, rspec )
self.assertSuccess( err_code )
rspec = rspec['value']
self.assertRspec( AMAPI_call, rspec,
rspec_namespace, rspec_schema,
self.options_copy.rspeclint)
if slicename:
self.assertRspecType( rspec, 'manifest', typeOnly=typeOnly)
else:
self.assertRspecType( rspec, 'advertisement', typeOnly=typeOnly)
if self.options_copy.geni_available:
self.assertTrue(rspec_util.rspec_available_only( rspec,
namespace=rspec_namespace,
schema=rspec_schema,
version=self.RSpecVersion() ),
"Return from '%s' at aggregate '%s' " \
"expected to only include available nodes " \
"but did not. Return was: " \
"\n%s\n" \
"... edited for length ..."
% (AMAPI_call, agg_url, rspec[:100]))
return rspec
def test_CreateSliver(self):
"""test_CreateSliver: Passes if the sliver creation workflow succeeds.
Use --rspec-file to replace the default request RSpec."""
self.logger.info("\n=== Test.test_CreateSliver ===")
self.subtest_CreateSliverWorkflow()
self.success = True
def subtest_CreateSliverWorkflow(self, slicename=None, doProvision=True, doPOA=True):
# Check to see if 'rspeclint' can be found before doing the hard (and
# slow) work of calling ListResources at the aggregate
if self.options_copy.rspeclint:
rspec_util.rspeclint_exists()
rspec_namespace = self.manifest_namespace
rspec_schema = self.manifest_schema
else:
rspec_namespace = None
rspec_schema = None
if slicename==None:
slicename = self.create_slice_name()
# if reusing a slice name, don't create (or delete) the slice
if not self.options_copy.reuse_slice_name:
self.subtest_createslice( slicename )
time.sleep(self.options_copy.sleep_time)
# cleanup up any previous failed runs
try:
self.subtest_generic_Delete( slicename )
time.sleep(self.options_copy.sleep_time)
except:
pass
sliceExpiration = self.getSliceExpiration( slicename )
numslivers, manifest, slivers = self.subtest_generic_CreateSliver( slicename, doProvision, doPOA, expectedExpiration=sliceExpiration )
with open(self.options_copy.rspec_file) as f:
req = f.readlines()
request = "".join(req)
try:
self.assertRspec( "CreateSliver", manifest,
rspec_namespace, rspec_schema,
self.options_copy.rspeclint )
self.assertRspecType( request, 'request')
self.assertRspecType( manifest, 'manifest')
# Make sure the Manifest returned the nodes identified in
# the Request
self.assertManifestMatchesRequest( request, manifest,
self.RSpecVersion(),
self.options_copy.bound,
"Created sliver")
time.sleep(self.options_copy.sleep_time)
self.subtest_generic_SliverStatus( slicename )
# in v1/v2 call ListResources(slicename)
# in v3 call Describe(slicename)
manifest2 = self.subtest_generic_ListResources( slicename=slicename )
# in v3 ListResources(slicename) should FAIL
## Should this succeed by giving an advertisement? Or FAIL as shown?
# Test passing a usercred as though it is a slice cred -- should fail
self.subtest_ListResources_slice_with_usercred(slicename)
if self.options_copy.api_version >= 3:
self.options_copy.devmode = True
# Seems like we should be checking for something more
# here?
# NotSuccess would be if teh AM
# refused. WrongRspecType would be if the AM ignored
# the slice_urn option and treated this as an Ad request.
self.assertRaises((NotSuccessError, WrongRspecType),
self.subtest_ListResources,
slicename=slicename )
self.assertRaises(NotSuccessError,
self.subtest_Describe,
slicename=None )
self.options_copy.devmode = False
self.subtest_Describe_geni_compressed( slicename )
self.options_copy.devmode = True
# Call describe on an individual sliver
# Then Call Describe() on a urn of type 'node' not 'sliver' - should fail
if len(slivers)>0:
sliver = slivers[0]
sliver_urn = sliver['geni_sliver_urn']
allsliverurns = []
for sliveritem in slivers:
allsliverurns.append(sliveritem['geni_sliver_urn'])
# Make sure can call Status on an individual sliver
self.subtest_Status(slicename, sliverlist = [sliver_urn])
# If not geni_single_allocation, then Renew, Describe, Provision, POA on an
# individual sliver should work. Else, should need all slivers
geni_single_allocation = False
# 1: Get GetVersion Result
omniargs = ["getversion", "-o", "--ForceUseGetVersionCache"]
(text, ret_dict) = self.call(omniargs, self.options_copy)
self.assertTrue(len(ret_dict.keys()) > 0,
"GetVersion returned nothing")
aggName = ret_dict.keys()[0]
self.assertDict( ret_dict[aggName], "GetVersion return malformed" )
aggVersion = self.assertReturnKeyValueType( "GetVersion", aggName,
ret_dict[aggName], 'value', dict )
# 2: Pull geni_single_allocation value
geni_single_allocation = self.assertGeniSingleAllocationIfExists( "GetVersion", aggName, aggVersion )
if geni_single_allocation:
# print "AM does geni_single_allocation: testing Renew/Describe with all sliver URNs at once"
sliverurns = allsliverurns
else:
# print "AM does NOT do geni_single_allocation: testing Renew/Describe with one sliver URN"
sliverurns = [sliver_urn]
now = ut.OmniUnittest.now_in_seconds()
fivemin = (now + datetime.timedelta(minutes=5)).isoformat()
self.subtest_Renew(slicename, newtime=fivemin, sliverlist=sliverurns)
# FIXME: Try Provision or POA on an individual sliver?
sliver_urn2 = re.sub('\+sliver\+', '+node+', sliver_urn)
self.logger.info("\n===Describe on a node urn where sliver expected - should fail")
self.subtest_Describe(slicename=slicename, sliverurns=sliverurns )
badurnslist = sliverurns.append(sliver_urn2)
self.assertRaises(NotSuccessError,
self.subtest_Describe,
slicename=slicename,
sliverurns=[sliver_urn2] )
# Call Describe() on a urn of type 'sliver' which isn't valid
sliver_urn3 = re.sub('\+sliver\+.*', '+sliver+INVALID', sliver_urn)
badurnslist = sliverurns.append(sliver_urn3)
self.assertRaises(NotSuccessError,
self.subtest_Describe,
slicename=slicename,
sliverurns=[sliver_urn3] )
self.options_copy.devmode = False
self.assertRspecType( manifest2, 'manifest')
self.assertRspec( "ListResources", manifest2,
rspec_namespace, rspec_schema,
self.options_copy.rspeclint )
# Make sure the Manifest returned the nodes identified in
# the Request
self.assertManifestMatchesRequest( request, manifest2,
self.RSpecVersion(),
self.options_copy.bound,
"ListResources/Described resources in slice")
time.sleep(self.options_copy.sleep_time)
# RenewSliver past slice expiration - should fail
self.subtest_RenewPastSliceExpiration( slicename )
time.sleep(self.options_copy.sleep_time)
# RenewSliver for 5 mins, 2 days, and 5 days
self.subtest_generic_RenewSliver_many( slicename )
except:
raise
finally:
time.sleep(self.options_copy.sleep_time)
try:
self.subtest_generic_DeleteSliver( slicename )
except:
pass
# Test SliverStatus, ListResources and DeleteSliver on a deleted sliver
self.subtest_CreateSliverWorkflow_failure( slicename )
if not self.options_copy.reuse_slice_name:
self.subtest_deleteslice( slicename )
def subtest_MinCreateSliverWorkflow(self, slicename=None):
if slicename==None:
slicename = self.create_slice_name()
# if reusing a slice name, don't create (or delete) the slice
if not self.options_copy.reuse_slice_name:
self.subtest_createslice( slicename )
time.sleep(self.options_copy.sleep_time)
# cleanup up any previous failed runs
try:
self.subtest_generic_DeleteSliver( slicename )
except:
pass
# # 2 False args mean in v3+ don't do Provision or poa
# manifest = self.subtest_generic_CreateSliver( slicename, False, False )
manifest = self.subtest_generic_CreateSliver( slicename )
# with open(self.options_copy.rspec_file) as f:
# req = f.readlines()
# request = "".join(req)
try:
self.subtest_generic_DeleteSliver( slicename )
except:
pass
if not self.options_copy.reuse_slice_name:
self.subtest_deleteslice( slicename )
def test_CreateSliverWorkflow_fail_notexist( self ):
"""test_CreateSliverWorkflow_fail_notexist: Passes if the sliver creation workflow
fails when the sliver has never existed."""
self.logger.info("\n=== Test.test_CreateSliverWorkflow_fail_notexist -- should FAIL")
slicename = self.create_slice_name_uniq(prefix='non')
# Create slice so that lack of existance of the slice doesn't
# cause the AM test to fail
self.subtest_createslice( slicename )
# Test SliverStatus, ListResources and DeleteSliver on a
# non-existant sliver
self.subtest_CreateSliverWorkflow_failure( slicename )
self.success = True
def subtest_CreateSliverWorkflow_failure( self, slicename ):
# Call Status, List, then Delete
# v3 allows return with no slivers, so expect no errors.
# Currently, PGv3 AM gives some other random error code (not
# 0). But that isn't really right.
# The GCF AM returns a SEARCHFAILED - a NotSuccessError.
# PL returns an empty list
# We should support all of those. See ticket #220
self.logger.info("Get Status: should fail (error or 0 slivers)")
gotRet = False
if self.options_copy.api_version >= 3:
# FIXME: Factor this out assertExceptionOrEmptyReturn