-
Notifications
You must be signed in to change notification settings - Fork 21
/
sliderule.py
1193 lines (1039 loc) · 41.1 KB
/
sliderule.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
# Copyright (c) 2021, University of Washington
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# 1. Redistributions of source code must retain the above copyright notice,
# this list of conditions and the following disclaimer.
#
# 2. Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions and the following disclaimer in the documentation
# and/or other materials provided with the distribution.
#
# 3. Neither the name of the University of Washington nor the names of its
# contributors may be used to endorse or promote products derived from this
# software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE UNIVERSITY OF WASHINGTON AND CONTRIBUTORS
# “AS IS” AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
# TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
# PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE UNIVERSITY OF WASHINGTON OR
# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
# EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
# PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
# OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
# WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
# OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
# ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
import os
import netrc
import requests
import socket
import json
import struct
import ctypes
import time
import logging
import warnings
import numpy
import geopandas
from shapely.geometry import Polygon
from datetime import datetime, timedelta
from sliderule import version
###############################################################################
# GLOBALS
###############################################################################
# WGS84 / Mercator, Earth as Geoid, Coordinate system on the surface of a sphere or ellipsoid of reference.
EPSG_MERCATOR = "EPSG:4326"
PUBLIC_URL = "slideruleearth.io"
PUBLIC_ORG = "sliderule"
service_url = PUBLIC_URL
service_org = PUBLIC_ORG
session = requests.Session()
session.trust_env = False
ps_refresh_token = None
ps_access_token = None
ps_token_exp = None
MAX_PS_CLUSTER_WAIT_SECS = 600
verbose = False
request_timeout = (10, 60) # (connection, read) in seconds
logger = logging.getLogger(__name__)
clustering_enabled = False
try:
from sklearn.cluster import KMeans
clustering_enabled = True
except:
logger.warning("Unable to import sklearn... clustering support disabled")
recdef_table = {}
arrow_file_table = {}
profiles = {}
gps_epoch = datetime(1980, 1, 6)
tai_epoch = datetime(1970, 1, 1, 0, 0, 10)
eventformats = {
"TEXT": 0,
"JSON": 1
}
eventlogger = {
0: logger.debug,
1: logger.info,
2: logger.warning,
3: logger.error,
4: logger.critical
}
datatypes = {
"TEXT": 0,
"REAL": 1,
"INTEGER": 2,
"DYNAMIC": 3
}
basictypes = {
"INT8": { "fmt": 'b', "size": 1, "nptype": numpy.int8 },
"INT16": { "fmt": 'h', "size": 2, "nptype": numpy.int16 },
"INT32": { "fmt": 'i', "size": 4, "nptype": numpy.int32 },
"INT64": { "fmt": 'q', "size": 8, "nptype": numpy.int64 },
"UINT8": { "fmt": 'B', "size": 1, "nptype": numpy.uint8 },
"UINT16": { "fmt": 'H', "size": 2, "nptype": numpy.uint16 },
"UINT32": { "fmt": 'I', "size": 4, "nptype": numpy.uint32 },
"UINT64": { "fmt": 'Q', "size": 8, "nptype": numpy.uint64 },
"BITFIELD": { "fmt": 'x', "size": 0, "nptype": numpy.byte }, # unsupported
"FLOAT": { "fmt": 'f', "size": 4, "nptype": numpy.single },
"DOUBLE": { "fmt": 'd', "size": 8, "nptype": numpy.double },
"TIME8": { "fmt": 'q', "size": 8, "nptype": numpy.int64 }, # numpy.datetime64
"STRING": { "fmt": 's', "size": 1, "nptype": numpy.byte }
}
codedtype2str = {
0: "INT8",
1: "INT16",
2: "INT32",
3: "INT64",
4: "UINT8",
5: "UINT16",
6: "UINT32",
7: "UINT64",
8: "BITFIELD",
9: "FLOAT",
10: "DOUBLE",
11: "TIME8",
12: "STRING"
}
###############################################################################
# CLIENT EXCEPTIONS
###############################################################################
class FatalError(RuntimeError):
pass
class TransientError(RuntimeError):
pass
###############################################################################
# UTILITIES
###############################################################################
#
# __populate
#
def __populate(rectype):
global recdef_table
if rectype not in recdef_table:
recdef_table[rectype] = source("definition", {"rectype" : rectype})
return recdef_table[rectype]
#
# __parse_json
#
def __parse_json(data):
"""
data: request response
"""
lines = []
for line in data.iter_content(None):
lines.append(line)
response = b''.join(lines)
return json.loads(response)
#
# __decode_native
#
def __decode_native(rectype, rawdata):
"""
rectype: record type supplied in response (string)
rawdata: payload supplied in response (byte array)
"""
global recdef_table
# initialize record
rec = { "__rectype": rectype }
# get/populate record definition #
recdef = __populate(rectype)
# iterate through each field in definition
for fieldname in recdef.keys():
# double underline (__) as prefix indicates meta data
if fieldname.find("__") == 0:
continue
# get field properties
field = recdef[fieldname]
ftype = field["type"]
offset = int(field["offset"] / 8)
elems = field["elements"]
flags = field["flags"]
# do not process pointers
if "PTR" in flags:
continue
# get endianess
if "LE" in flags:
endian = '<'
else:
endian = '>'
# decode basic type
if ftype in basictypes:
# check if array
is_array = not (elems == 1)
# get number of elements
if elems <= 0:
elems = int((len(rawdata) - offset) / basictypes[ftype]["size"])
# build format string
fmt = endian + str(elems) + basictypes[ftype]["fmt"]
# parse data
value = struct.unpack_from(fmt, rawdata, offset)
# set field
if ftype == "STRING":
rec[fieldname] = ctypes.create_string_buffer(value[0]).value.decode('ascii')
elif is_array:
rec[fieldname] = value
else:
rec[fieldname] = value[0]
# decode user type
else:
# populate record definition (if needed) #
subrecdef = __populate(ftype)
# check if array
is_array = not (elems == 1)
# get number of elements
if elems <= 0:
elems = int((len(rawdata) - offset) / subrecdef["__datasize"])
# return parsed data
if is_array:
rec[fieldname] = []
for e in range(elems):
rec[fieldname].append(__decode_native(ftype, rawdata[offset:]))
offset += subrecdef["__datasize"]
else:
rec[fieldname] = __decode_native(ftype, rawdata[offset:])
# return record #
return rec
#
# __parse_native
#
def __parse_native(data, callbacks):
"""
data: request response
"""
recs = []
rec_hdr_size = 8
rec_size_index = 0
rec_size_rsps = []
rec_size = 0
rec_index = 0
rec_rsps = []
duration = 0.0
for line in data.iter_content(None):
# Capture Start Time (for duration)
tstart = time.perf_counter()
# Process Line Read
i = 0
while i < len(line):
# Parse Record Size
if(rec_size_index < rec_hdr_size):
bytes_available = len(line) - i
bytes_remaining = rec_hdr_size - rec_size_index
bytes_to_append = min(bytes_available, bytes_remaining)
rec_size_rsps.append(line[i:i+bytes_to_append])
rec_size_index += bytes_to_append
if(rec_size_index >= rec_hdr_size):
raw = b''.join(rec_size_rsps)
rec_version, rec_type_size, rec_data_size = struct.unpack('>hhi', raw)
if rec_version != 2:
raise FatalError("Invalid record format: %d" % (rec_version))
rec_size = rec_type_size + rec_data_size
rec_size_rsps.clear()
i += bytes_to_append
# Parse Record
elif(rec_size > 0):
bytes_available = len(line) - i
bytes_remaining = rec_size - rec_index
bytes_to_append = min(bytes_available, bytes_remaining)
rec_rsps.append(line[i:i+bytes_to_append])
rec_index += bytes_to_append
if(rec_index >= rec_size):
# Decode Record
rawbits = b''.join(rec_rsps)
rectype = ctypes.create_string_buffer(rawbits).value.decode('ascii')
rawdata = rawbits[len(rectype) + 1:]
rec = __decode_native(rectype, rawdata)
if callbacks != None and rectype in callbacks:
# Execute Call-Back on Record
callbacks[rectype](rec)
else:
# Append Record
recs.append(rec)
# Reset Record Parsing
rec_rsps.clear()
rec_size_index = 0
rec_size = 0
rec_index = 0
i += bytes_to_append
# Zero Sized Record
else:
rec_size_index = 0
rec_index = 0
# Capture Duration
duration = duration + (time.perf_counter() - tstart)
# Update Timing Profile
profiles[__parse_native.__name__] = duration
return recs
#
# __build_auth_header
#
def __build_auth_header():
"""
Build authentication header for use with provisioning system
"""
global service_url, ps_access_token, ps_refresh_token, ps_token_exp
headers = None
if ps_access_token:
# Check if Refresh Needed
if time.time() > ps_token_exp:
host = "https://ps." + service_url + "/api/org_token/refresh/"
rqst = {"refresh": ps_refresh_token}
hdrs = {'Content-Type': 'application/json', 'Authorization': 'Bearer ' + ps_access_token}
rsps = session.post(host, data=json.dumps(rqst), headers=hdrs, timeout=request_timeout).json()
ps_refresh_token = rsps["refresh"]
ps_access_token = rsps["access"]
ps_token_exp = time.time() + (float(rsps["access_lifetime"]) / 2)
# Build Authentication Header
headers = {'Authorization': 'Bearer ' + ps_access_token}
return headers
###############################################################################
# Overriding DNS
###############################################################################
local_dns = {}
socket_getaddrinfo = socket.getaddrinfo
def __override_getaddrinfo(*args):
if args[0] in local_dns:
logger.debug("getaddrinfo returned {} for {}".format(local_dns[args[0]], args[0]))
return socket_getaddrinfo(local_dns[args[0]], *args[1:])
else:
return socket_getaddrinfo(*args)
socket.getaddrinfo = __override_getaddrinfo
###############################################################################
# Default Record Processing
###############################################################################
#
# __logeventrec
#
def __logeventrec(rec):
if verbose:
eventlogger[rec['level']]('%s' % (rec["attr"]))
#
# __exceptrec
#
def __exceptrec(rec):
if verbose:
if rec["code"] >= 0:
eventlogger[rec["level"]]("Exception <%d>: %s", rec["code"], rec["text"])
else:
eventlogger[rec["level"]]("%s", rec["text"])
#
# _arrowrec
#
def __arrowrec(rec):
global arrow_file_table
try :
filename = rec["filename"]
if rec["__rectype"] == 'arrowrec.meta':
if filename in arrow_file_table:
raise FatalError("file transfer already in progress")
arrow_file_table[filename] = { "fp": open(filename, "wb"), "size": rec["size"], "progress": 0 }
else: # rec["__rectype"] == 'arrowrec.data'
data = rec['data']
file = arrow_file_table[filename]
file["fp"].write(bytearray(data))
file["progress"] += len(data)
if file["progress"] >= file["size"]:
file["fp"].close()
del arrow_file_table[filename]
except Exception as e:
raise FatalError("Failed to process arrow file: {}".format(e))
#
# Globals
#
__callbacks = {'eventrec': __logeventrec, 'exceptrec': __exceptrec, 'arrowrec.meta': __arrowrec, 'arrowrec.data': __arrowrec }
###############################################################################
# INTERNAL APIs
###############################################################################
#
# GeoDataFrame to Polygon
#
def gdf2poly(gdf):
# latch start time
tstart = time.perf_counter()
# pull out coordinates
hull = gdf.unary_union.convex_hull
polygon = [{"lon": coord[0], "lat": coord[1]} for coord in list(hull.exterior.coords)]
# determine winding of polygon #
# (x2 - x1) * (y2 + y1)
wind = sum([(polygon[i+1]["lon"] - polygon[i]["lon"]) * (polygon[i+1]["lat"] + polygon[i]["lat"]) for i in range(len(polygon) - 1)])
if wind > 0:
# reverse direction (make counter-clockwise) #
ccw_poly = []
for i in range(len(polygon), 0, -1):
ccw_poly.append(polygon[i - 1])
# replace region with counter-clockwise version #
polygon = ccw_poly
# Update Profile
profiles[gdf2poly.__name__] = time.perf_counter() - tstart
# return polygon
return polygon
#
# Create Empty GeoDataFrame
#
def emptyframe(**kwargs):
# set default keyword arguments
kwargs['crs'] = EPSG_MERCATOR
return geopandas.GeoDataFrame(geometry=geopandas.points_from_xy([], []), crs=kwargs['crs'])
#
# Process Output File
#
def procoutputfile(parm):
if "open_on_complete" in parm["output"] and parm["output"]["open_on_complete"]:
# Return GeoParquet File as GeoDataFrame
return geopandas.read_parquet(parm["output"]["path"])
else:
# Return Parquet Filename
return parm["output"]["path"]
#
# Get Values from Raw Buffer
#
def getvalues(data, dtype, size):
"""
data: tuple of bytes
dtype: element of codedtype
size: bytes in data
"""
raw = bytes(data)
datatype = basictypes[codedtype2str[dtype]]["nptype"]
num_elements = int(size / numpy.dtype(datatype).itemsize)
slicesize = num_elements * numpy.dtype(datatype).itemsize # truncates partial bytes
values = numpy.frombuffer(raw[:slicesize], dtype=datatype, count=num_elements)
return values
###############################################################################
# APIs
###############################################################################
#
# Initialize
#
def init (url=service_url, verbose=False, loglevel=logging.CRITICAL, organization=service_org, desired_nodes=None, time_to_live=60, plugins=[]):
'''
Initializes the Python client for use with SlideRule, and should be called before other ICESat-2 API calls.
This function is a wrapper for a handful of sliderule functions that would otherwise all have to be called in order to initialize the client.
Parameters
----------
url : str
the IP address or hostname of the SlideRule service (slidereearth.io by default)
verbose : bool
whether or not user level log messages received from SlideRule generate a Python log message
loglevel : int
minimum severity of log message to output
organization: str
SlideRule provisioning system organization the user belongs to (see sliderule.authenticate for details)
plugins: list
names of the plugins that need to be available on the server
Examples
--------
>>> import sliderule
>>> sliderule.init()
'''
if verbose:
loglevel = logging.INFO
logging.basicConfig(level=loglevel)
set_verbose(verbose)
set_url(url) # configure domain
authenticate(organization) # configure credentials (if any) for organization
local_dns.clear() # clear cache of DNS lookups for clusters
scaleout(desired_nodes, time_to_live) # set cluster to desired number of nodes (if permitted based on credentials)
check_version(plugins=plugins) # verify compatibility between client and server versions
#
# source
#
def source (api, parm={}, stream=False, callbacks={}, path="/source", silence=False):
'''
Perform API call to SlideRule service
Parameters
----------
api: str
name of the SlideRule endpoint
parm: dict
dictionary of request parameters
stream: bool
whether the request is a **normal** service or a **stream** service (see `De-serialization </rtd/user_guide/SlideRule.html#de-serialization>`_ for more details)
callbacks: dict
record type callbacks (advanced use)
path: str
path to api being requested
silence: bool
whether error log messages should be generated
Returns
-------
dictionary
response data
Examples
--------
>>> import sliderule
>>> sliderule.set_url("slideruleearth.io")
>>> rqst = {
... "time": "NOW",
... "input": "NOW",
... "output": "GPS"
... }
>>> rsps = sliderule.source("time", rqst)
>>> print(rsps)
{'time': 1300556199523.0, 'format': 'GPS'}
'''
global service_url, service_org
rqst = json.dumps(parm)
rsps = {}
headers = None
# Build Callbacks
for c in __callbacks:
if c not in callbacks:
callbacks[c] = __callbacks[c]
# Attempt Request
complete = False
attempts = 3
while not complete and attempts > 0:
attempts -= 1
try:
# Construct Request URL and Authorization
if service_org:
url = 'https://%s.%s%s/%s' % (service_org, service_url, path, api)
headers = __build_auth_header()
else:
url = 'http://%s%s/%s' % (service_url, path, api)
# Perform Request
if not stream:
data = session.get(url, data=rqst, headers=headers, timeout=request_timeout)
else:
data = session.post(url, data=rqst, headers=headers, timeout=request_timeout, stream=True)
data.raise_for_status()
# Parse Response
format = data.headers['Content-Type']
if format == 'text/plain':
rsps = __parse_json(data)
elif format == 'application/json':
rsps = __parse_json(data)
elif format == 'application/octet-stream':
rsps = __parse_native(data, callbacks)
else:
raise FatalError('unsupported content type: %s' % (format))
# Success
complete = True
except requests.exceptions.SSLError as e:
logger.debug("Exception in request to {}: {}".format(url, e))
if not silence:
logger.error("Unable to verify SSL certificate for {} ...retrying request".format(url))
except requests.ConnectionError as e:
logger.debug("Exception in request to {}: {}".format(url, e))
if not silence:
logger.error("Connection error to endpoint {} ...retrying request".format(url))
except requests.Timeout as e:
logger.debug("Exception in request to {}: {}".format(url, e))
if not silence:
logger.error("Timed-out waiting for response from endpoint {} ...retrying request".format(url))
except requests.exceptions.ChunkedEncodingError as e:
logger.debug("Exception in request to {}: {}".format(url, e))
if not silence:
logger.error("Unexpected termination of response from endpoint {} ...retrying request".format(url))
except requests.HTTPError as e:
logger.debug("Exception in request to {}: {}".format(url, e))
if e.response.status_code == 503:
raise TransientError("Server experiencing heavy load, stalling on request to {}".format(url))
else:
raise FatalError("HTTP error {} from endpoint {}".format(e.response.status_code, url))
except:
raise
# Check Success
if not complete:
raise FatalError("Unable to complete request due to errors")
# Return Response
return rsps
#
# set_url
#
def set_url (url):
'''
Configure sliderule package with URL of service
Parameters
----------
urls: str
IP address or hostname of SlideRule service (note, there is a special case where the url is provided as a list of strings
instead of just a string; when a list is provided, the client hardcodes the set of servers that are used to process requests
to the exact set provided; this is used for testing and for local installations and can be ignored by most users)
Examples
--------
>>> import sliderule
>>> sliderule.set_url("service.my-sliderule-server.org")
'''
global service_url
service_url = url
#
# set_verbose
#
def set_verbose (enable):
'''
Configure sliderule package for verbose logging
Parameters
----------
enable: bool
whether or not user level log messages received from SlideRule generate a Python log message
Examples
--------
>>> import sliderule
>>> sliderule.set_verbose(True)
The default behavior of Python log messages is for them to be displayed to standard output.
If you want more control over the behavior of the log messages being display, create and configure a Python log handler as shown below:
>>> # import packages
>>> import logging
>>> from sliderule import sliderule
>>> # Configure Logging
>>> sliderule_logger = logging.getLogger("sliderule.sliderule")
>>> sliderule_logger.setLevel(logging.INFO)
>>> # Create Console Output
>>> ch = logging.StreamHandler()
>>> ch.setLevel(logging.INFO)
>>> sliderule_logger.addHandler(ch)
'''
global verbose
verbose = (enable == True)
#
# set_rqst_timeout
#
def set_rqst_timeout (timeout):
'''
Sets the TCP/IP connection and reading timeouts for future requests made to sliderule servers.
Setting it lower means the client will failover more quickly, but may generate false positives if a processing request stalls or takes a long time returning data.
Setting it higher means the client will wait longer before designating it a failed request which in the presence of a persistent failure means it will take longer for the client to remove the node from its available servers list.
Parameters
----------
timeout: tuple
(<connection timeout in seconds>, <read timeout in seconds>)
Examples
--------
>>> import sliderule
>>> sliderule.set_rqst_timeout((10, 60))
'''
global request_timeout
if type(timeout) == tuple:
request_timeout = timeout
else:
raise FatalError('timeout must be a tuple (<connection timeout>, <read timeout>)')
#
# update_available_servers
#
def update_available_servers (desired_nodes=None, time_to_live=None):
'''
Manages the number of servers in the cluster.
If the desired_nodes parameter is set, then a request is made to change the number of servers in the cluster to the number specified.
In all cases, the number of nodes currently running in the cluster are returned - even if desired_nodes is set;
subsequent calls to this function is needed to check when the current number of nodes matches the desired_nodes.
Parameters
----------
desired_nodes: int
the desired number of nodes in the cluster
time_to_live: int
number of minutes for the desired nodes to run
Returns
-------
int
number of nodes currently in the cluster
int
number of nodes available for work in the cluster
Examples
--------
>>> import sliderule
>>> num_servers, max_workers = sliderule.update_available_servers(10)
'''
global service_url, service_org, request_timeout, local_dns
# Update number of nodes
if type(desired_nodes) == int:
headers = __build_auth_header()
if type(time_to_live) == int:
host = "https://ps." + service_url + "/api/desired_org_num_nodes_ttl/" + service_org + "/" + str(desired_nodes) + "/" + str(time_to_live) + "/"
rsps = session.post(host, headers=headers, timeout=request_timeout)
else:
host = "https://ps." + service_url + "/api/desired_org_num_nodes/" + service_org + "/" + str(desired_nodes) + "/"
rsps = session.put(host, headers=headers, timeout=request_timeout)
rsps.raise_for_status()
# Get number of nodes currently registered
try:
rsps = source("status", parm={"service":"sliderule"}, path="/discovery", silence=True)
available_servers = rsps["nodes"]
except FatalError:
available_servers = 0
return available_servers, available_servers
#
# scaleout
#
def scaleout(desired_nodes, time_to_live):
'''
Scale the cluster and wait for cluster to reach desired state
Parameters
----------
desired_nodes: int
the desired number of nodes in the cluster
time_to_live: int
number of minutes for the desired nodes to run
Examples
--------
>>> import sliderule
>>> sliderule.scaleout(4, 300)
'''
if desired_nodes is None:
return # nothing needs to be done
if desired_nodes < 0:
raise FatalError("Number of desired nodes must be greater than zero ({})".format(desired_nodes))
# Send Initial Request for Desired Cluster State
update_available_servers(desired_nodes=desired_nodes, time_to_live=time_to_live)
start = time.time()
available_nodes,_ = update_available_servers()
scale_up_needed = False
dns_overridden = False
# Wait for Cluster to Reach Desired State
while available_nodes < desired_nodes:
scale_up_needed = True
logger.info("Waiting while cluster scales to desired capacity (currently at {} nodes, desired is {} nodes)... {} seconds".format(available_nodes, desired_nodes, int(time.time() - start)))
time.sleep(10.0)
available_nodes,_ = update_available_servers()
# Override DNS if Cluster is Starting
if available_nodes == 0 and not dns_overridden:
headers = __build_auth_header()
host = "https://ps." + service_url + "/api/org_ip_adr/" + service_org + "/"
rsps = session.get(host, headers=headers, timeout=request_timeout).json()
if rsps["status"] == "SUCCESS":
dns_overridden = True
url_to_override = service_org + "." + service_url
local_dns[url_to_override] = rsps["ip_address"]
logger.info("Overriding DNS for {} with {}".format(url_to_override, rsps["ip_address"]))
# Timeout Occurred
if int(time.time() - start) > MAX_PS_CLUSTER_WAIT_SECS:
logger.error("Maximum time allowed waiting for cluster has been exceeded")
break
# Log Final Message if Cluster Needed State Change
if scale_up_needed:
logger.info("Cluster has reached capacity of {} nodes... {} seconds".format(available_nodes, int(time.time() - start)))
#
# authenticate
#
def authenticate (ps_organization, ps_username=None, ps_password=None):
'''
Authenticate to SlideRule Provisioning System
The username and password can be provided the following way in order of priority:
(1) The passed in arguments `ps_username' and 'ps_password';
(2) The O.S. environment variables 'PS_USERNAME' and 'PS_PASSWORD';
(3) The `ps.<url>` entry in the .netrc file in your home directory
Parameters
----------
ps_organization: str
name of the SlideRule organization the user belongs to
ps_username: str
SlideRule provisioning system account name
ps_password: str
SlideRule provisioning system account password
Returns
-------
status
True of successful, False if unsuccessful
Examples
--------
>>> import sliderule
>>> sliderule.authenticate("myorg")
True
'''
global service_org, ps_refresh_token, ps_access_token, ps_token_exp
login_status = False
ps_url = "ps." + service_url
# set organization on any authentication request
service_org = ps_organization
# check for direct or public access
if service_org == None:
return True
# attempt retrieving from environment
if not ps_username or not ps_password:
ps_username = os.environ.get("PS_USERNAME")
ps_password = os.environ.get("PS_PASSWORD")
# attempt retrieving from netrc file
if not ps_username or not ps_password:
try:
netrc_file = netrc.netrc()
login_credentials = netrc_file.hosts[ps_url]
ps_username = login_credentials[0]
ps_password = login_credentials[2]
except Exception as e:
if ps_organization != PUBLIC_ORG:
logger.warning("Unable to retrieve username and password from netrc file for machine: {}".format(e))
# authenticate to provisioning system
if ps_username and ps_password:
rqst = {"username": ps_username, "password": ps_password, "org_name": ps_organization}
headers = {'Content-Type': 'application/json'}
try:
api = "https://" + ps_url + "/api/org_token/"
rsps = session.post(api, data=json.dumps(rqst), headers=headers, timeout=request_timeout)
rsps.raise_for_status()
rsps = rsps.json()
ps_refresh_token = rsps["refresh"]
ps_access_token = rsps["access"]
ps_token_exp = time.time() + (float(rsps["access_lifetime"]) / 2)
login_status = True
except:
logger.error("Unable to authenticate user %s to %s" % (ps_username, api))
# return login status
return login_status
#
# gps2utc
#
def gps2utc (gps_time, as_str=True):
'''
Convert a GPS based time returned from SlideRule into a UTC time.
Parameters
----------
gps_time: int
number of seconds since GPS epoch (January 6, 1980)
as_str: bool
if True, returns the time as a string; if False, returns the time as datatime object
Returns
-------
datetime
UTC time (i.e. GMT, or Zulu time)
Examples
--------
>>> import sliderule
>>> sliderule.gps2utc(1235331234)
'2019-02-27 19:34:03'
'''
rsps = source("time", {"time": gps_time, "input": "GPS", "output": "DATE"})
if as_str:
return rsps["time"]
else:
return datetime.strptime(rsps["time"], '%Y-%m-%dT%H:%M:%SZ')
#
# get_definition
#
def get_definition (rectype, fieldname):
'''
Get the underlying format specification of a field in a return record.
Parameters
----------
rectype: str
the name of the type of the record (i.e. "atl03rec")
fieldname: str
the name of the record field (i.e. "cycle")
Returns
-------
dict
description of each field; see the `sliderule.basictypes` variable for different field types
Examples
--------
>>> import sliderule
>>> sliderule.set_url("slideruleearth.io")
>>> sliderule.get_definition("atl03rec", "cycle")
{'fmt': 'H', 'size': 2, 'nptype': <class 'numpy.uint16'>}
'''
recdef = __populate(rectype)
if fieldname in recdef and recdef[fieldname]["type"] in basictypes:
return basictypes[recdef[fieldname]["type"]]
else:
return {}
#
# get_version
#
def get_version ():
'''
Get the version information for the running servers and Python client
Returns
-------
dict
dictionary of version information
'''
global service_org
rsps = source("version", {})
rsps["client"] = {"version": version.full_version}
rsps["organization"] = service_org
return rsps
#
# check_version