-
Notifications
You must be signed in to change notification settings - Fork 0
/
experimentlib.py
1888 lines (1477 loc) · 63.3 KB
/
experimentlib.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
"""
<Program Name>
experimentlib.py
<Authors>
Justin Samuel
<Date Started>
December 1, 2009
<Purpose>
A library for conducting experiments using Seattle vessels. The functions in
this library allow for communicating with vessels (e.g. to upload files and
run programs) as well as for communicating with SeattleGENI (e.g. to obtain
vessels to run experiments on).
<Usage>
Ensure that this file is in a directory containing the seattlelib files as
well as the seattleclearinghouse_xmlrpc.py module. In your own script, add:
import experimentlib
then call the methods desired.
Note that if your script resides outside of the directory that contains the
seattlelib files, experimentlib.py, and seattlegeni_client.py, then you'll
need to set that directory/those directories in your python path. For example,
if you downloaded an installer (even if you haven't installed Seattle on the
machine this script resides on, the path will be to the seattle_repy directory
that was among the extracted installer files. To set the path directly in your
script rather than through environment variables, you can use something like:
import sys
sys.path.append("/path/to/seattle_repy")
You would need to do the above *before* your line that says:
import experimentlib
For examples of using this experimentlib, see the examples/ directory.
Please also see the following wiki page for usage information and how to
obtain the latest version of this experiment library:
https://seattle.cs.washington.edu/wiki/ExperimentLibrary
<Notes>
Object Definitions:
* identity: a dictionary that minimally contains a public key but may also
contain the related private key and the username of a corresponding
SeattleGENI account. When one wants to perform any operation that would
require a public key, private key, or username, an identity must be
provided. An identity can be created using the functions named
create_identity_from_*.
* vesselhandle: a vesselhandle is a string that contains the information
required to uniquely identify a vessel, regardless of the current
location (IP address) of the node the vessel is on. This is in the format
of "nodeid:vesselname".
* nodeid: a string that contains the information required to uniquely
identify a node, regardless of its current location.
* vesselname: a string containing the name of a vessel. This name will
be unique on any given node, but the same name is likely is used for
vessels on other nodes. Thus, this does not uniquely identify a vessel,
in general. To uniquely identify a vessel, a vesselhandle is needed.
* nodelocation: a string containing the location of a node. This will not
always be "ip:port". It could, for example, be "NATid:port" in the case
of a node that is accessible through a NAT forwarder.
* vesseldict: a dictionary of details related to a given vessel. The keys
that will always be present are 'vesselhandle', 'nodelocation',
'vesselname', and 'nodeid'. Additional keys will be present depending on
the function that returns the vesseldict. See the individual function
docstring for details.
Exceptions:
All exceptions raised by functions in this module will either be or extend:
* SeattleExperimentError
* SeattleClearinghouseError
The SeattleClearinghouseError* exceptions will only be raised by the functions whose
names are seattlegeni_*. Any of the seattlegeni_* functions may raise the
following in addition to specific exceptions described in the function
docstrings (these are all subclasses of SeattleClearinghouseError):
* SeattleClearinghouseCommunicationError
* SeattleClearinghouseAuthenticationError
* SeattleClearinghouseInvalidRequestError
* SeattleClearinghouseInternalError
In the case of invalid arguments to functions, the following may be
raised (these will not always be documented for each function):
* TypeError
* ValueError
* IOError (if the function involves reading/writing files and the
filename provided is missing/unreadable/unwritable)
For the specific exceptions raised by a given function, see the function's
docstring.
"""
import os
import random
import time
import tracebackrepy
import xmlrpclib
import seattleclearinghouse_xmlrpc
# We use a helper module to do repy module imports so that we don't import
# unexpected items into this module's namespace. This helps reduce errors
# because editors/pylint make it clear when an unknown identifier is used
# and it also makes other things easier for developers, such as using ipython's
# tab completion and not causing unexpected imports if someone using this
# module decides to use "from experimentlib import *"
#import repyimporter
import fastnmclient
"""
repytime = repyimporter.import_repy_module("time")
rsa = repyimporter.import_repy_module("rsa")
parallelize = repyimporter.import_repy_module("parallelize")
advertise = repyimporter.import_repy_module("advertise")
"""
from repyportability import add_dy_support
add_dy_support(locals())
repytime = dy_import_module_symbols("time.r2py")
rsa = dy_import_module_symbols("rsa.r2py")
parallelize = dy_import_module_symbols("parallelize.r2py")
advertise = dy_import_module_symbols("advertise.r2py")
# The maximum number of node locations to return from a call to lookup_node_locations.
max_lookup_results = 1024 * 1024
# The timeout to use for communication, both in advertisement lookups and for
# contacting nodes directly.
defaulttimeout = 10
# The number of worker threads to use for each parallelized operation.
num_worker_threads = 5
# Whether additional information and debugging messages should be printed
# to stderr by this library.
print_debug_messages = True
# OpenDHT can be slow/hang, which isn't fun if the experimentlib is being used
# interactively. So, let's default to central advertise server lookups here
# until we're sure all issues with OpenDHT are resolved.
# A value of None indicates the default of ['opendht', 'central'].
#advertise_lookup_types = None
advertise_lookup_types = ['central']
# A few options to be passed along to the SeattleGENI xmlrpc client.
# None means the default.
SEATTLECLEARINGHOUSE_XMLRPC_URL = None
SEATTLECLEARINGHOUSE_ALLOW_SSL_INSECURE = None # Set to True to allow insecure SSL.
SEATTLECLEARINGHOUSE_CA_CERTS_FILES = None
# These constants can be used as the type argument to seattlegeni_acquire_vessels.
SEATTLECLEARINGHOUSE_VESSEL_TYPE_WAN = "wan"
SEATTLECLEARINGHOUSE_VESSEL_TYPE_LAN = "lan"
SEATTLECLEARINGHOUSE_VESSEL_TYPE_NAT = "nat"
SEATTLECLEARINGHOUSE_VESSEL_TYPE_RAND = "rand"
# Some of these vessel status explanations are from:
# https://seattle.cs.washington.edu/wiki/NodeManagerDesign
# Fresh: has never been started.
VESSEL_STATUS_FRESH = "Fresh"
# Started: has been started and is running when last checked.
VESSEL_STATUS_STARTED = "Started"
# Stopped: was running but stopped by NM command
VESSEL_STATUS_STOPPED = "Stopped"
# Stale: it last reported a start of "Started" but significant time has
# elapsed, likely due to a system crash (what does "system crash" mean?).
VESSEL_STATUS_STALE = "Stale"
# Terminated (the vessel stopped of its own volition, possibly due to an error)
VESSEL_STATUS_TERMINATED = "Terminated"
# The node is not advertising
VESSEL_STATUS_NO_SUCH_NODE = "NO_SUCH_NODE"
# The node can be communicated with but the specified vessel doesn't exist
# on the node. This will also be used when the vessel exists on the node but
# the identity being used is not a user or the owner of the vessel.
VESSEL_STATUS_NO_SUCH_VESSEL = "NO_SUCH_VESSEL"
# The node can't be communicated with or communication fails.
VESSEL_STATUS_NODE_UNREACHABLE = "NODE_UNREACHABLE"
# For convenience we define two sets of vessel status constants that include
# all possible statuses grouped by whether the status indicates the vessel is
# usable/active or whether it is unusable/inactive.
VESSEL_STATUS_SET_ACTIVE = set([VESSEL_STATUS_FRESH, VESSEL_STATUS_STARTED,
VESSEL_STATUS_STOPPED, VESSEL_STATUS_STALE,
VESSEL_STATUS_TERMINATED])
VESSEL_STATUS_SET_INACTIVE = set([VESSEL_STATUS_NO_SUCH_NODE, VESSEL_STATUS_NO_SUCH_VESSEL,
VESSEL_STATUS_NODE_UNREACHABLE])
# Whether _initialize_time() has been called.
_initialize_time_called = False
# Keys are node locations (a string of "host:port"), values are nmhandles.
# Note that this method of caching nmhandles will cause problems if multiple
# identities/keys are being used to contact the name node.
_nmhandle_cache = {}
# Keys are nodeids, values are nodelocations.
_node_location_cache = {}
class SeattleExperimentError(Exception):
"""Base class for other exceptions."""
class UnexpectedVesselStatusError(SeattleExperimentError):
"""
When a vessel status is reported by a node and that status is something
we don't understand. Mostly this is something we care about because we
want to definitely tell users what to expect in their code in terms of
status, so we should be very clear about the possibly values and never
have to raise this exception.
"""
class NodeCommunicationError(SeattleExperimentError):
"""Unable to perform a requested action on/communication with a node/vessel."""
class NodeLocationLookupError(SeattleExperimentError):
"""
Unable to determine the location of a node based on its nodeid or unable
to successfully perform an advertisement lookup.
"""
class NodeLocationNotAdvertisedError(NodeLocationLookupError):
"""
A lookup was successful but no node locations are being advertised under a
nodeid.
"""
class UnableToPerformLookupError(NodeLocationLookupError):
"""
Something is wrong with performing lookups. Either none of the lookup
services that were tried were successful or there's a bug in some underlying
code being used by this module.
"""
class IdentityInformationMissingError(SeattleExperimentError):
"""
The information that is part of an identity object is incomplete. For
example, if only the public key is in the identity but the identity is
used in a way that requires a private key, this exception would be
raised.
"""
#This is the base class for all SeattleGENI errors. We make this available
#in the namespace of the experimentlib so that clients do not have to import
#seattleclearinghouse_xmlrpc to catch these.
SeattleClearinghouseError = seattleclearinghouse_xmlrpc.SeattleClearinghouseError
# We make these available, as well, in case users find them useful. We prefix
# all of these error names with SeattleGENI.
SeattleClearinghouseCommunicationError = seattleclearinghouse_xmlrpc.CommunicationError
SeattleClearinghouseInternalError = seattleclearinghouse_xmlrpc.InternalError
SeattleClearinghouseAuthenticationError = seattleclearinghouse_xmlrpc.AuthenticationError
SeattleClearinghouseInvalidRequestError = seattleclearinghouse_xmlrpc.InvalidRequestError
SeattleClearinghouseNotEnoughCreditsError = seattleclearinghouse_xmlrpc.NotEnoughCreditsError
SeattleClearinghouseUnableToAcquireResourcesError = seattleclearinghouse_xmlrpc.UnableToAcquireResourcesError
def _validate_vesselhandle(vesselhandle):
if not isinstance(vesselhandle, basestring):
raise TypeError("vesselhandle must be a string, not a " + str(type(vesselhandle)))
parts = vesselhandle.split(':')
if len(parts) != 2:
raise ValueError("invalid vesselhandle '" + vesselhandle + "', should be nodeid:vesselname")
def _validate_vesselhandle_list(vesselhandle_list):
if not isinstance(vesselhandle_list, list):
raise TypeError("vesselhandle list must be a list, not a " + str(type(vesselhandle_list)))
for vesselhandle in vesselhandle_list:
_validate_vesselhandle(vesselhandle)
def _validate_nodelocation(nodelocation):
if not isinstance(nodelocation, basestring):
raise TypeError("nodelocation must be a string, not a " + str(type(nodelocation)))
parts = nodelocation.split(':')
if len(parts) != 2:
raise ValueError("nodelocation '" + nodelocation + "' invalid, should be host:port")
def _validate_nodelocation_list(nodelocation_list):
if not isinstance(nodelocation_list, list):
raise TypeError("nodelocation list must be a list, not a " + str(type(nodelocation_list)))
for nodelocation in nodelocation_list:
_validate_nodelocation(nodelocation)
def _validate_identity(identity, require_private_key=False, require_username=False):
if not isinstance(identity, dict):
raise TypeError("identity must be a dict, not a " + str(type(identity)))
if 'publickey_str' not in identity:
raise TypeError("identity dict doesn't have a 'publickey_str' key, so it's not an identity.")
if require_private_key:
if 'privatekey_str' not in identity:
raise IdentityInformationMissingError("identity must have a private key for the requested operation.")
if require_username:
if 'username' not in identity:
raise IdentityInformationMissingError("identity must have a username for the requested operation.")
def _initialize_time():
"""
Does its best to call time_updatetime() and raises a SeattleExperimentError
if it doesn't succeed after many tries.
"""
global _initialize_time_called
if not _initialize_time_called:
max_attempts = 10
possible_ports = range(10000, 60001)
# Ports to use for UDP listening when doing a time update.
portlist = random.sample(possible_ports, max_attempts)
for localport in portlist:
try:
repytime.time_updatetime(localport)
_initialize_time_called = True
return
except repytime.TimeError:
error_message = tracebackrepy.format_exception()
raise SeattleExperimentError("Failed to perform time_updatetime(): " + error_message)
def _create_list_from_key_in_dictlist(dictlist, key):
"""
List comprehensions are verboten by our coding style guide (generally for
good reason). Otherwise, we wouldn't have this function and would just write
the following wherever needed:
[x[key] for x in dictlist]
"""
new_list = []
for dictitem in dictlist:
new_list.append(dictitem[key])
return new_list
def _get_nmhandle(nodelocation, identity=None):
"""
Get an nmhandle for the nodelocation and identity, if provided. This will look
use a cache of nmhandles and only create a new one if the requested nmhandle
has not previously been requested.
"""
# Call _initialize_time() here because time must be updated at least once before
# nmhandles are used.
_initialize_time()
host, port = nodelocation.split(':')
port = int(port)
if identity is None:
identitystring = "None"
else:
identitystring = identity['publickey_str']
if identitystring not in _nmhandle_cache:
_nmhandle_cache[identitystring] = {}
if nodelocation not in _nmhandle_cache[identitystring]:
try:
if identity is None:
nmhandle = fastnmclient.nmclient_createhandle(host, port, timeout=defaulttimeout)
elif 'privatekey_dict' in identity:
nmhandle = fastnmclient.nmclient_createhandle(host, port, privatekey=identity['privatekey_dict'],
publickey=identity['publickey_dict'], timeout=defaulttimeout)
else:
nmhandle = fastnmclient.nmclient_createhandle(host, port, publickey=identity['publickey_dict'],
timeout=defaulttimeout)
except fastnmclient.NMClientException, e:
raise NodeCommunicationError(str(e))
_nmhandle_cache[identitystring][nodelocation] = nmhandle
return _nmhandle_cache[identitystring][nodelocation]
def run_parallelized(targetlist, func, *args):
"""
<Purpose>
Parallelize the calling of a given function using multiple threads.
<Arguments>
targetlist
a list what will be the first argument to func each time it is called.
func
the function to be called once for each item in targetlist.
*args
(optional) every additional argument will be passed to func after an
item from targetlist. That is, these will be the second, third, etc.
argument to func, if provided. These are not required a.
<Exceptions>
SeattleExperimentError
Raised if there is a problem performing parallel processing. This will
not be raised just because func raises exceptions. If func raises
exceptions when it is called, that exception information will be
available through the run_parallelized's return value.
<Side Effects>
Up to num_worker_threads (a global variable) threads will be spawned to
call func once for every item in targetlist.
<Returns>
A tuple of:
(successlist, failurelist)
where successlist is a list of tuples of the format:
(target, return_value_from_func)
and failurelist is a list of tuples of the format:
(target, exception_string)
Note that exception_string will not contain a full traceback, but rather
only the string representation of the exception.
"""
try:
phandle = parallelize.parallelize_initfunction(targetlist, func, num_worker_threads, *args)
while not parallelize.parallelize_isfunctionfinished(phandle):
# TODO: Give up after a timeout? This seems risky as run_parallelized may
# be used with functions that take a long time to complete and very large
# lists of targets. It would be a shame to break a user's program because
# of an assumption here. Maybe it should be an optional argument to
# run_parallelized.
time.sleep(.1)
results = parallelize.parallelize_getresults(phandle)
except parallelize.ParallelizeError:
raise SeattleExperimentError("Error occurred in run_parallelized: " +
tracebackrepy.format_exception())
finally:
parallelize.parallelize_closefunction(phandle)
# These are lists of tuples. The first is a list of (target, retval), the
# second is a list of (target, errormsg)
return results['returned'], results['exception']
def create_identity_from_key_files(publickey_fn, privatekey_fn=None):
"""
<Purpose>
Create an identity from key files.
<Arguments>
publickey_fn
The full path, including filename, to the public key this identity
should represent. Note that the identity's username will be assumed
to be the part of the base filename before the first period (or the
entire base filename if there is no period). So, to indicate a username
of "joe", the filename should be, for example, "joe.publickey".
privatekey_fn
(optional) The full path, including filename, to the private key that
corresponds to publickey_fn. If this is not provided, then the identity
will not be able to be used for operations the require a private key.
<Exceptions>
IOError
if the files do not exist or are not readable.
ValueError
if the files do not contain valid keys.
<Returns>
An identity object to be used with other functions in this module.
"""
identity = {}
identity["username"] = os.path.basename(publickey_fn).split(".")[0]
identity["publickey_fn"] = publickey_fn
try:
identity["publickey_dict"] = rsa.rsa_file_to_publickey(publickey_fn)
identity["publickey_str"] = rsa.rsa_publickey_to_string(identity["publickey_dict"])
if privatekey_fn is not None:
identity["privatekey_fn"] = privatekey_fn
identity["privatekey_dict"] = rsa.rsa_file_to_privatekey(privatekey_fn)
identity["privatekey_str"] = rsa.rsa_privatekey_to_string(identity["privatekey_dict"])
except IOError:
raise
except ValueError:
raise
return identity
def create_identity_from_key_strings(publickey_string, privatekey_string=None, username=None):
"""
<Purpose>
Create an identity from key strings.
<Arguments>
publickey_string
The string containing the public key this identity should represent. The
string must consists of the modulus, followed by a space, followed by
the public exponent. This will be the same as the contents of a public
key file.
privatekey_string
(optional) The full path, including filename, to the private key that
corresponds to publickey_fn. If this is not provided, then the identity
will not be able to be used for operations the require a private key.
username
(optional) A string containing the username to associate with this
identity. This is only necessary if using this identity with the
seattlegeni_* functions.
<Exceptions>
ValueError
if the strings do not contain valid keys.
<Returns>
An identity object to be used with other functions in this module.
"""
identity = {}
identity["username"] = username
try:
identity["publickey_dict"] = rsa.rsa_string_to_publickey(publickey_string)
identity["publickey_str"] = rsa.rsa_publickey_to_string(identity["publickey_dict"])
if privatekey_string is not None:
identity["privatekey_dict"] = rsa.rsa_string_to_privatekey(privatekey_string)
identity["privatekey_str"] = rsa.rsa_privatekey_to_string(identity["privatekey_dict"])
except IOError:
# Raised if there is a problem reading the file.
raise
except ValueError:
# Raised by the repy rsa module when the key is invald.
raise
return identity
def _lookup_node_locations(keystring, lookuptype=None):
"""Does the actual work of an advertise lookup."""
keydict = rsa.rsa_string_to_publickey(keystring)
try:
if lookuptype is not None:
nodelist = advertise.advertise_lookup(keydict, maxvals=max_lookup_results, timeout=defaulttimeout, lookuptype=lookuptype)
else:
nodelist = advertise.advertise_lookup(keydict, maxvals=max_lookup_results, timeout=defaulttimeout)
except advertise.AdvertiseError, e:
raise UnableToPerformLookupError("Failure when trying to perform advertise lookup: " +
tracebackrepy.format_exception())
# If there are no vessels for a user, the lookup may return ''.
for nodename in nodelist[:]:
if nodename == '':
nodelist.remove(nodename)
return nodelist
def lookup_node_locations_by_identity(identity):
"""
<Purpose>
Lookup the locations of nodes that are advertising their location under a
specific identity's public key.
<Arguments>
identity
The identity whose public key should be used to lookup nodelocations.
<Exceptions>
UnableToPerformLookupError
If a failure occurs when trying lookup advertised node locations.
<Returns>
A list of nodelocations.
"""
_validate_identity(identity)
keystring = str(identity['publickey_str'])
return _lookup_node_locations(keystring, lookuptype=advertise_lookup_types)
def lookup_node_locations_by_nodeid(nodeid):
"""
<Purpose>
Lookup the locations that a specific node has advertised under. There may
be multiple locations advertised if the node has recently changed location.
<Arguments>
nodeid
The nodeid of the node whose advertised locations are to be looked up.
<Exceptions>
UnableToPerformLookupError
If a failure occurs when trying lookup advertised node locations.
<Returns>
A list of nodelocations.
"""
return _lookup_node_locations(nodeid, lookuptype=advertise_lookup_types)
def find_vessels_on_nodes(identity, nodelocation_list):
"""
<Purpose>
Contact one or more nodes and determine which vessels on those nodes are
usable by a given identity.
<Arguments>
identity
The identity whose vessels we are interested in. This can be the identity
of either the vessel owner or a vessel user.
nodelocation_list
A list of nodelocations that should be contacted. This can be an empty
list (which will result in an empty list of vesselhandles returned).
<Exceptions>
SeattleExperimentError
If an error occurs performing a parallelized operation.
<Returns>
A list of vesselhandles.
"""
_validate_identity(identity)
_validate_nodelocation_list(nodelocation_list)
successlist, failurelist = run_parallelized(nodelocation_list, browse_node, identity)
vesseldicts = []
for (nodeid, vesseldicts_of_node) in successlist:
vesseldicts += vesseldicts_of_node
return _create_list_from_key_in_dictlist(vesseldicts, "vesselhandle")
def browse_node(nodelocation, identity=None):
"""
<Purpose>
Contact an individual node to gather detailed information about all of the
vessels on the node that are usable by a given identity.
<Arguments>
nodelocation
The nodelocation of the node that should be browsed.
identity
(optional) The identity whose vessels we are interested in. This can be
the identity of either the vessel owner or a vessel user. If None,
then the vesseldicts for all vessels on the node will be returned.
<Exceptions>
NodeCommunicationError
If the communication with the node fails for any reason, including the
node not being reachable, timeout in communicating with the node, the
node rejecting the
<Returns>
A list of vesseldicts. Each vesseldict contains the additional keys:
'status'
The status string of the vessel.
'ownerkey'
The vessel's owner key (in dict format).
'userkeys'
A list of the vessel's user keys (each in dict format).
"""
try:
_validate_nodelocation(nodelocation)
if identity is not None:
_validate_identity(identity)
nmhandle = _get_nmhandle(nodelocation, identity)
try:
nodeinfo = fastnmclient.nmclient_getvesseldict(nmhandle)
except fastnmclient.NMClientException, e:
raise NodeCommunicationError("Failed to communicate with node " + nodelocation + ": " + str(e))
# We do our own looking through the nodeinfo rather than use the function
# nmclient_listaccessiblevessels() as we don't want to contact the node a
# second time.
usablevessels = []
for vesselname in nodeinfo['vessels']:
if identity is None:
usablevessels.append(vesselname)
elif identity['publickey_dict'] == nodeinfo['vessels'][vesselname]['ownerkey']:
usablevessels.append(vesselname)
elif 'userkeys' in nodeinfo['vessels'][vesselname] and \
identity['publickey_dict'] in nodeinfo['vessels'][vesselname]['userkeys']:
usablevessels.append(vesselname)
nodeid = rsa.rsa_publickey_to_string(nodeinfo['nodekey'])
# For efficiency, let's update the _node_location_cache with this info.
# This can prevent individual advertise lookups of each nodeid by other
# functions in the experimentlib that may be called later.
_node_location_cache[nodeid] = nodelocation
vesseldict_list = []
for vesselname in usablevessels:
vesseldict = {}
# Required keys in vesseldicts (see the module comments for more info).
vesseldict['vesselhandle'] = nodeid + ":" + vesselname
vesseldict['nodelocation'] = nodelocation
vesseldict['vesselname'] = vesselname
vesseldict['nodeid'] = nodeid
# Additional keys that browse_node provides.
vesseldict['status'] = nodeinfo['vessels'][vesselname]['status']
vesseldict['ownerkey'] = nodeinfo['vessels'][vesselname]['ownerkey']
vesseldict['userkeys'] = nodeinfo['vessels'][vesselname]['userkeys']
vesseldict['version'] = nodeinfo['version']
vesseldict_list.append(vesseldict)
return vesseldict_list
except Exception, e:
# Useful for debugging during development of the experimentlib.
#traceback.print_exc()
raise
def get_vessel_status(vesselhandle, identity):
"""
<Purpose>
Determine the status of a vessel.
<Arguments>
vesselhandle
The vesselhandle of the vessel whose status is to be checked.
identity
The identity of the owner or a user of the vessel.
<Exceptions>
UnexpectedVesselStatusError
If the status returned by the node for the vessel is not a status value
that this experimentlib expects.
<Side Effects>
The node the vessel is on is communicated with.
<Returns>
A string that is one of the VESSEL_STATUS_* constants.
"""
_validate_vesselhandle(vesselhandle)
_validate_identity(identity)
# Determine the last known location of the node.
nodeid, vesselname = vesselhandle.split(":")
try:
# This will get a cached node location if one exists.
nodelocation = get_node_location(nodeid)
except NodeLocationNotAdvertisedError, e:
return VESSEL_STATUS_NO_SUCH_NODE
try:
vesselinfolist = browse_node(nodelocation, identity)
except NodeCommunicationError:
# Do a non-cache lookup of the nodeid to see if the node moved.
try:
nodelocation = get_node_location(nodeid, ignorecache=True)
except NodeLocationNotAdvertisedError, e:
return VESSEL_STATUS_NO_SUCH_NODE
# Try to communicate again.
try:
vesselinfolist = browse_node(nodelocation, identity)
except NodeCommunicationError, e:
return VESSEL_STATUS_NODE_UNREACHABLE
for vesselinfo in vesselinfolist:
if vesselinfo['vesselhandle'] == vesselhandle:
# The node is up and the vessel must have the identity's key as the owner
# or a user, but the status returned isn't one of the statuses we
# expect. If this does occur, it may indicate a bug in the experiment
# library where it doesn't know about all possible status a nodemanager
# may return for a vessel.
if vesselinfo['status'] not in VESSEL_STATUS_SET_ACTIVE:
raise UnexpectedVesselStatusError(vesselinfo['status'])
else:
return vesselinfo['status']
else:
# The node is up but this vessel doesn't exist.
return VESSEL_STATUS_NO_SUCH_VESSEL
def _do_public_node_request(nodeid, requestname, *args):
nodelocation = get_node_location(nodeid)
nmhandle = _get_nmhandle(nodelocation)
try:
return fastnmclient.nmclient_rawsay(nmhandle, requestname, *args)
except fastnmclient.NMClientException, e:
raise NodeCommunicationError(str(e))
def _do_signed_vessel_request(identity, vesselhandle, requestname, *args):
_validate_identity(identity, require_private_key=True)
nodeid, vesselname = vesselhandle.split(':')
nodelocation = get_node_location(nodeid)
nmhandle = _get_nmhandle(nodelocation, identity)
try:
return fastnmclient.nmclient_signedsay(nmhandle, requestname, vesselname, *args)
except fastnmclient.NMClientException, e:
raise NodeCommunicationError(str(e))
def get_node_offcut_resources(nodeid):
"""
<Purpose>
Obtain information about offcut resources on a node.
<Arguments>
nodeid
The nodeid of the node whose offcut resources are to be queried.
<Exceptions>
NodeCommunicationError
If communication with the node failed, either because the node is down,
the communication timed out, the signature was invalid, or the identity
unauthorized for this action.
<Side Effects>
None
<Returns>
A string containing information about the node's offcut resources.
"""
# TODO: This function might be more useful if it processed the string
# returned by the nodemanager and return it from this function as some
# well-defined data structure.
return _do_public_node_request(nodeid, "GetOffcutResources")
def get_vessel_resources(vesselhandle):
"""
<Purpose>
Obtain vessel resource/restrictions information.
<Arguments>
vesselhandle
The vesselhandle of the vessels whose restrictions/resources info are to
be returned.
<Exceptions>
NodeCommunicationError
If communication with the node failed, either because the node is down,
the communication timed out, the signature was invalid, or the identity
unauthorized for this action.
<Side Effects>
None
<Returns>
A string containing the vessel resource/restrictions information.
"""
# TODO: This function might be more useful if it processed the string
# returned by the nodemanager and return it from this function as some
# well-defined data structure.
nodeid, vesselname = get_nodeid_and_vesselname(vesselhandle)
return _do_public_node_request(nodeid, "GetVesselResources", vesselhandle)
def get_vessel_log(vesselhandle, identity):
"""
<Purpose>
Read the vessel log.
<Arguments>
vesselhandle
The vesselhandle of the vessel whose log is to be read.
identity
The identity of either the owner or a user of the vessel.
<Exceptions>
NodeCommunicationError
If communication with the node failed, either because the node is down,
the communication timed out, the signature was invalid, or the identity
unauthorized for this action.
<Side Effects>
None
<Returns>
A string containing the data in the vessel log.
"""
_validate_vesselhandle(vesselhandle)
return _do_signed_vessel_request(identity, vesselhandle, "ReadVesselLog")
def get_vessel_file_list(vesselhandle, identity):
"""
<Purpose>
Get a list of files that are on the vessel.
<Arguments>
vesselhandle
The vesselhandle of the vessel whose file list is to be obtained.
identity
The identity of either the owner or a user of the vessel.
<Exceptions>
NodeCommunicationError
If communication with the node failed, either because the node is down,
the communication timed out, the signature was invalid, or the identity
unauthorized for this action.
<Side Effects>
None
<Returns>
A list of filenames (strings).
"""
_validate_vesselhandle(vesselhandle)
file_list_string = _do_signed_vessel_request(identity, vesselhandle, "ListFilesInVessel")
if not file_list_string:
return []
else:
return file_list_string.split(' ')
def upload_file_to_vessel(vesselhandle, identity, local_filename, remote_filename=None):
"""
<Purpose>
Upload a file to a vessel.
<Arguments>
vesselhandle
The vesselhandle of the vessel that the file is to be uploaded to.
identity
The identity of either the owner or a user of the vessel.
local_filename
The name of the local file to be uploaded. That can include a directory
path.
remote_filename
(optional) The filename to use when storing the file on the vessel. If
not provided, this will be the same as the basename of local_filename.